babylon.2.0-beta.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. 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));
  657. 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));
  658. 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));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. 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);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. 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;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. 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)
  1124. }
  1125. else {
  1126. 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)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. var data = matrix.m;
  1163. var m11 = data[0], m12 = data[4], m13 = data[8];
  1164. var m21 = data[1], m22 = data[5], m23 = data[9];
  1165. var m31 = data[2], m32 = data[6], m33 = data[10];
  1166. var trace = m11 + m22 + m33;
  1167. var s;
  1168. if (trace > 0) {
  1169. s = 0.5 / Math.sqrt(trace + 1.0);
  1170. this.w = 0.25 / s;
  1171. this.x = (m32 - m23) * s;
  1172. this.y = (m13 - m31) * s;
  1173. this.z = (m21 - m12) * s;
  1174. return this;
  1175. }
  1176. if (m11 > m22 && m11 > m33) {
  1177. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1178. this.w = (m32 - m23) / s;
  1179. this.x = 0.25 * s;
  1180. this.y = (m12 + m21) / s;
  1181. this.z = (m13 + m31) / s;
  1182. return this;
  1183. }
  1184. if (m22 > m33) {
  1185. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1186. this.w = (m13 - m31) / s;
  1187. this.x = (m12 + m21) / s;
  1188. this.y = 0.25 * s;
  1189. this.z = (m23 + m32) / s;
  1190. return this;
  1191. }
  1192. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1193. this.w = (m21 - m12) / s;
  1194. this.x = (m13 + m31) / s;
  1195. this.y = (m23 + m32) / s;
  1196. this.z = 0.25 * s;
  1197. return this;
  1198. };
  1199. // Statics
  1200. Quaternion.Inverse = function (q) {
  1201. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1202. };
  1203. Quaternion.Identity = function () {
  1204. return new Quaternion(0, 0, 0, 1);
  1205. };
  1206. Quaternion.RotationAxis = function (axis, angle) {
  1207. var result = new Quaternion();
  1208. var sin = Math.sin(angle / 2);
  1209. result.w = Math.cos(angle / 2);
  1210. result.x = axis.x * sin;
  1211. result.y = axis.y * sin;
  1212. result.z = axis.z * sin;
  1213. return result;
  1214. };
  1215. Quaternion.FromArray = function (array, offset) {
  1216. if (!offset) {
  1217. offset = 0;
  1218. }
  1219. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1220. };
  1221. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1222. var result = new Quaternion();
  1223. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1224. return result;
  1225. };
  1226. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1227. var halfRoll = roll * 0.5;
  1228. var halfPitch = pitch * 0.5;
  1229. var halfYaw = yaw * 0.5;
  1230. var sinRoll = Math.sin(halfRoll);
  1231. var cosRoll = Math.cos(halfRoll);
  1232. var sinPitch = Math.sin(halfPitch);
  1233. var cosPitch = Math.cos(halfPitch);
  1234. var sinYaw = Math.sin(halfYaw);
  1235. var cosYaw = Math.cos(halfYaw);
  1236. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1237. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1238. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1239. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1240. };
  1241. Quaternion.Slerp = function (left, right, amount) {
  1242. var num2;
  1243. var num3;
  1244. var num = amount;
  1245. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1246. var flag = false;
  1247. if (num4 < 0) {
  1248. flag = true;
  1249. num4 = -num4;
  1250. }
  1251. if (num4 > 0.999999) {
  1252. num3 = 1 - num;
  1253. num2 = flag ? -num : num;
  1254. }
  1255. else {
  1256. var num5 = Math.acos(num4);
  1257. var num6 = (1.0 / Math.sin(num5));
  1258. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1259. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1260. }
  1261. 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));
  1262. };
  1263. return Quaternion;
  1264. })();
  1265. BABYLON.Quaternion = Quaternion;
  1266. var Matrix = (function () {
  1267. function Matrix() {
  1268. this.m = new Float32Array(16);
  1269. }
  1270. // Properties
  1271. Matrix.prototype.isIdentity = function () {
  1272. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1273. return false;
  1274. 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)
  1275. return false;
  1276. return true;
  1277. };
  1278. Matrix.prototype.determinant = function () {
  1279. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1280. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1281. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1282. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1283. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1284. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1285. 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))));
  1286. };
  1287. // Methods
  1288. Matrix.prototype.toArray = function () {
  1289. return this.m;
  1290. };
  1291. Matrix.prototype.asArray = function () {
  1292. return this.toArray();
  1293. };
  1294. Matrix.prototype.invert = function () {
  1295. this.invertToRef(this);
  1296. return this;
  1297. };
  1298. Matrix.prototype.invertToRef = function (other) {
  1299. var l1 = this.m[0];
  1300. var l2 = this.m[1];
  1301. var l3 = this.m[2];
  1302. var l4 = this.m[3];
  1303. var l5 = this.m[4];
  1304. var l6 = this.m[5];
  1305. var l7 = this.m[6];
  1306. var l8 = this.m[7];
  1307. var l9 = this.m[8];
  1308. var l10 = this.m[9];
  1309. var l11 = this.m[10];
  1310. var l12 = this.m[11];
  1311. var l13 = this.m[12];
  1312. var l14 = this.m[13];
  1313. var l15 = this.m[14];
  1314. var l16 = this.m[15];
  1315. var l17 = (l11 * l16) - (l12 * l15);
  1316. var l18 = (l10 * l16) - (l12 * l14);
  1317. var l19 = (l10 * l15) - (l11 * l14);
  1318. var l20 = (l9 * l16) - (l12 * l13);
  1319. var l21 = (l9 * l15) - (l11 * l13);
  1320. var l22 = (l9 * l14) - (l10 * l13);
  1321. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1322. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1323. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1324. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1325. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1326. var l28 = (l7 * l16) - (l8 * l15);
  1327. var l29 = (l6 * l16) - (l8 * l14);
  1328. var l30 = (l6 * l15) - (l7 * l14);
  1329. var l31 = (l5 * l16) - (l8 * l13);
  1330. var l32 = (l5 * l15) - (l7 * l13);
  1331. var l33 = (l5 * l14) - (l6 * l13);
  1332. var l34 = (l7 * l12) - (l8 * l11);
  1333. var l35 = (l6 * l12) - (l8 * l10);
  1334. var l36 = (l6 * l11) - (l7 * l10);
  1335. var l37 = (l5 * l12) - (l8 * l9);
  1336. var l38 = (l5 * l11) - (l7 * l9);
  1337. var l39 = (l5 * l10) - (l6 * l9);
  1338. other.m[0] = l23 * l27;
  1339. other.m[4] = l24 * l27;
  1340. other.m[8] = l25 * l27;
  1341. other.m[12] = l26 * l27;
  1342. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1343. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1344. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1345. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1346. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1347. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1348. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1349. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1350. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1351. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1352. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1353. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1354. return this;
  1355. };
  1356. Matrix.prototype.setTranslation = function (vector3) {
  1357. this.m[12] = vector3.x;
  1358. this.m[13] = vector3.y;
  1359. this.m[14] = vector3.z;
  1360. return this;
  1361. };
  1362. Matrix.prototype.multiply = function (other) {
  1363. var result = new Matrix();
  1364. this.multiplyToRef(other, result);
  1365. return result;
  1366. };
  1367. Matrix.prototype.copyFrom = function (other) {
  1368. for (var index = 0; index < 16; index++) {
  1369. this.m[index] = other.m[index];
  1370. }
  1371. return this;
  1372. };
  1373. Matrix.prototype.copyToArray = function (array, offset) {
  1374. if (offset === void 0) { offset = 0; }
  1375. for (var index = 0; index < 16; index++) {
  1376. array[offset + index] = this.m[index];
  1377. }
  1378. return this;
  1379. };
  1380. Matrix.prototype.multiplyToRef = function (other, result) {
  1381. this.multiplyToArray(other, result.m, 0);
  1382. return this;
  1383. };
  1384. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1385. var tm0 = this.m[0];
  1386. var tm1 = this.m[1];
  1387. var tm2 = this.m[2];
  1388. var tm3 = this.m[3];
  1389. var tm4 = this.m[4];
  1390. var tm5 = this.m[5];
  1391. var tm6 = this.m[6];
  1392. var tm7 = this.m[7];
  1393. var tm8 = this.m[8];
  1394. var tm9 = this.m[9];
  1395. var tm10 = this.m[10];
  1396. var tm11 = this.m[11];
  1397. var tm12 = this.m[12];
  1398. var tm13 = this.m[13];
  1399. var tm14 = this.m[14];
  1400. var tm15 = this.m[15];
  1401. var om0 = other.m[0];
  1402. var om1 = other.m[1];
  1403. var om2 = other.m[2];
  1404. var om3 = other.m[3];
  1405. var om4 = other.m[4];
  1406. var om5 = other.m[5];
  1407. var om6 = other.m[6];
  1408. var om7 = other.m[7];
  1409. var om8 = other.m[8];
  1410. var om9 = other.m[9];
  1411. var om10 = other.m[10];
  1412. var om11 = other.m[11];
  1413. var om12 = other.m[12];
  1414. var om13 = other.m[13];
  1415. var om14 = other.m[14];
  1416. var om15 = other.m[15];
  1417. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1418. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1419. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1420. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1421. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1422. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1423. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1424. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1425. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1426. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1427. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1428. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1429. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1430. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1431. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1432. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1433. return this;
  1434. };
  1435. Matrix.prototype.equals = function (value) {
  1436. 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]);
  1437. };
  1438. Matrix.prototype.clone = function () {
  1439. 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]);
  1440. };
  1441. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1442. translation.x = this.m[12];
  1443. translation.y = this.m[13];
  1444. translation.z = this.m[14];
  1445. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1446. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1447. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1448. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1449. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1450. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1451. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1452. rotation.x = 0;
  1453. rotation.y = 0;
  1454. rotation.z = 0;
  1455. rotation.w = 1;
  1456. return false;
  1457. }
  1458. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1459. rotation.fromRotationMatrix(rotationMatrix);
  1460. return true;
  1461. };
  1462. // Statics
  1463. Matrix.FromArray = function (array, offset) {
  1464. var result = new Matrix();
  1465. if (!offset) {
  1466. offset = 0;
  1467. }
  1468. Matrix.FromArrayToRef(array, offset, result);
  1469. return result;
  1470. };
  1471. Matrix.FromArrayToRef = function (array, offset, result) {
  1472. for (var index = 0; index < 16; index++) {
  1473. result.m[index] = array[index + offset];
  1474. }
  1475. };
  1476. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1477. result.m[0] = initialM11;
  1478. result.m[1] = initialM12;
  1479. result.m[2] = initialM13;
  1480. result.m[3] = initialM14;
  1481. result.m[4] = initialM21;
  1482. result.m[5] = initialM22;
  1483. result.m[6] = initialM23;
  1484. result.m[7] = initialM24;
  1485. result.m[8] = initialM31;
  1486. result.m[9] = initialM32;
  1487. result.m[10] = initialM33;
  1488. result.m[11] = initialM34;
  1489. result.m[12] = initialM41;
  1490. result.m[13] = initialM42;
  1491. result.m[14] = initialM43;
  1492. result.m[15] = initialM44;
  1493. };
  1494. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1495. var result = new Matrix();
  1496. result.m[0] = initialM11;
  1497. result.m[1] = initialM12;
  1498. result.m[2] = initialM13;
  1499. result.m[3] = initialM14;
  1500. result.m[4] = initialM21;
  1501. result.m[5] = initialM22;
  1502. result.m[6] = initialM23;
  1503. result.m[7] = initialM24;
  1504. result.m[8] = initialM31;
  1505. result.m[9] = initialM32;
  1506. result.m[10] = initialM33;
  1507. result.m[11] = initialM34;
  1508. result.m[12] = initialM41;
  1509. result.m[13] = initialM42;
  1510. result.m[14] = initialM43;
  1511. result.m[15] = initialM44;
  1512. return result;
  1513. };
  1514. Matrix.Compose = function (scale, rotation, translation) {
  1515. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1516. var rotationMatrix = Matrix.Identity();
  1517. rotation.toRotationMatrix(rotationMatrix);
  1518. result = result.multiply(rotationMatrix);
  1519. result.setTranslation(translation);
  1520. return result;
  1521. };
  1522. Matrix.Identity = function () {
  1523. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1524. };
  1525. Matrix.IdentityToRef = function (result) {
  1526. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1527. };
  1528. Matrix.Zero = function () {
  1529. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1530. };
  1531. Matrix.RotationX = function (angle) {
  1532. var result = new Matrix();
  1533. Matrix.RotationXToRef(angle, result);
  1534. return result;
  1535. };
  1536. Matrix.Invert = function (source) {
  1537. var result = new Matrix();
  1538. source.invertToRef(result);
  1539. return result;
  1540. };
  1541. Matrix.RotationXToRef = function (angle, result) {
  1542. var s = Math.sin(angle);
  1543. var c = Math.cos(angle);
  1544. result.m[0] = 1.0;
  1545. result.m[15] = 1.0;
  1546. result.m[5] = c;
  1547. result.m[10] = c;
  1548. result.m[9] = -s;
  1549. result.m[6] = s;
  1550. result.m[1] = 0;
  1551. result.m[2] = 0;
  1552. result.m[3] = 0;
  1553. result.m[4] = 0;
  1554. result.m[7] = 0;
  1555. result.m[8] = 0;
  1556. result.m[11] = 0;
  1557. result.m[12] = 0;
  1558. result.m[13] = 0;
  1559. result.m[14] = 0;
  1560. };
  1561. Matrix.RotationY = function (angle) {
  1562. var result = new Matrix();
  1563. Matrix.RotationYToRef(angle, result);
  1564. return result;
  1565. };
  1566. Matrix.RotationYToRef = function (angle, result) {
  1567. var s = Math.sin(angle);
  1568. var c = Math.cos(angle);
  1569. result.m[5] = 1.0;
  1570. result.m[15] = 1.0;
  1571. result.m[0] = c;
  1572. result.m[2] = -s;
  1573. result.m[8] = s;
  1574. result.m[10] = c;
  1575. result.m[1] = 0;
  1576. result.m[3] = 0;
  1577. result.m[4] = 0;
  1578. result.m[6] = 0;
  1579. result.m[7] = 0;
  1580. result.m[9] = 0;
  1581. result.m[11] = 0;
  1582. result.m[12] = 0;
  1583. result.m[13] = 0;
  1584. result.m[14] = 0;
  1585. };
  1586. Matrix.RotationZ = function (angle) {
  1587. var result = new Matrix();
  1588. Matrix.RotationZToRef(angle, result);
  1589. return result;
  1590. };
  1591. Matrix.RotationZToRef = function (angle, result) {
  1592. var s = Math.sin(angle);
  1593. var c = Math.cos(angle);
  1594. result.m[10] = 1.0;
  1595. result.m[15] = 1.0;
  1596. result.m[0] = c;
  1597. result.m[1] = s;
  1598. result.m[4] = -s;
  1599. result.m[5] = c;
  1600. result.m[2] = 0;
  1601. result.m[3] = 0;
  1602. result.m[6] = 0;
  1603. result.m[7] = 0;
  1604. result.m[8] = 0;
  1605. result.m[9] = 0;
  1606. result.m[11] = 0;
  1607. result.m[12] = 0;
  1608. result.m[13] = 0;
  1609. result.m[14] = 0;
  1610. };
  1611. Matrix.RotationAxis = function (axis, angle) {
  1612. var s = Math.sin(-angle);
  1613. var c = Math.cos(-angle);
  1614. var c1 = 1 - c;
  1615. axis.normalize();
  1616. var result = Matrix.Zero();
  1617. result.m[0] = (axis.x * axis.x) * c1 + c;
  1618. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1619. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1620. result.m[3] = 0.0;
  1621. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1622. result.m[5] = (axis.y * axis.y) * c1 + c;
  1623. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1624. result.m[7] = 0.0;
  1625. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1626. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1627. result.m[10] = (axis.z * axis.z) * c1 + c;
  1628. result.m[11] = 0.0;
  1629. result.m[15] = 1.0;
  1630. return result;
  1631. };
  1632. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1633. var result = new Matrix();
  1634. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1635. return result;
  1636. };
  1637. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1638. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1639. this._tempQuaternion.toRotationMatrix(result);
  1640. };
  1641. Matrix.Scaling = function (x, y, z) {
  1642. var result = Matrix.Zero();
  1643. Matrix.ScalingToRef(x, y, z, result);
  1644. return result;
  1645. };
  1646. Matrix.ScalingToRef = function (x, y, z, result) {
  1647. result.m[0] = x;
  1648. result.m[1] = 0;
  1649. result.m[2] = 0;
  1650. result.m[3] = 0;
  1651. result.m[4] = 0;
  1652. result.m[5] = y;
  1653. result.m[6] = 0;
  1654. result.m[7] = 0;
  1655. result.m[8] = 0;
  1656. result.m[9] = 0;
  1657. result.m[10] = z;
  1658. result.m[11] = 0;
  1659. result.m[12] = 0;
  1660. result.m[13] = 0;
  1661. result.m[14] = 0;
  1662. result.m[15] = 1.0;
  1663. };
  1664. Matrix.Translation = function (x, y, z) {
  1665. var result = Matrix.Identity();
  1666. Matrix.TranslationToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.TranslationToRef = function (x, y, z, result) {
  1670. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1671. };
  1672. Matrix.LookAtLH = function (eye, target, up) {
  1673. var result = Matrix.Zero();
  1674. Matrix.LookAtLHToRef(eye, target, up, result);
  1675. return result;
  1676. };
  1677. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1678. // Z axis
  1679. target.subtractToRef(eye, this._zAxis);
  1680. this._zAxis.normalize();
  1681. // X axis
  1682. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1683. this._xAxis.normalize();
  1684. // Y axis
  1685. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1686. this._yAxis.normalize();
  1687. // Eye angles
  1688. var ex = -Vector3.Dot(this._xAxis, eye);
  1689. var ey = -Vector3.Dot(this._yAxis, eye);
  1690. var ez = -Vector3.Dot(this._zAxis, eye);
  1691. 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);
  1692. };
  1693. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1694. var hw = 2.0 / width;
  1695. var hh = 2.0 / height;
  1696. var id = 1.0 / (zfar - znear);
  1697. var nid = znear / (znear - zfar);
  1698. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1699. };
  1700. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1701. var matrix = Matrix.Zero();
  1702. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1703. return matrix;
  1704. };
  1705. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1706. result.m[0] = 2.0 / (right - left);
  1707. result.m[1] = result.m[2] = result.m[3] = 0;
  1708. result.m[5] = 2.0 / (top - bottom);
  1709. result.m[4] = result.m[6] = result.m[7] = 0;
  1710. result.m[10] = -1.0 / (znear - zfar);
  1711. result.m[8] = result.m[9] = result.m[11] = 0;
  1712. result.m[12] = (left + right) / (left - right);
  1713. result.m[13] = (top + bottom) / (bottom - top);
  1714. result.m[14] = znear / (znear - zfar);
  1715. result.m[15] = 1.0;
  1716. };
  1717. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1718. var matrix = Matrix.Zero();
  1719. matrix.m[0] = (2.0 * znear) / width;
  1720. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1721. matrix.m[5] = (2.0 * znear) / height;
  1722. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1723. matrix.m[10] = -zfar / (znear - zfar);
  1724. matrix.m[8] = matrix.m[9] = 0.0;
  1725. matrix.m[11] = 1.0;
  1726. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1727. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1728. return matrix;
  1729. };
  1730. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1731. var matrix = Matrix.Zero();
  1732. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1733. return matrix;
  1734. };
  1735. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1736. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1737. var tan = 1.0 / (Math.tan(fov * 0.5));
  1738. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1739. if (v_fixed) {
  1740. result.m[0] = tan / aspect;
  1741. }
  1742. else {
  1743. result.m[0] = tan;
  1744. }
  1745. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1746. if (v_fixed) {
  1747. result.m[5] = tan;
  1748. }
  1749. else {
  1750. result.m[5] = tan * aspect;
  1751. }
  1752. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1753. result.m[8] = result.m[9] = 0.0;
  1754. result.m[10] = -zfar / (znear - zfar);
  1755. result.m[11] = 1.0;
  1756. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1757. result.m[14] = (znear * zfar) / (znear - zfar);
  1758. };
  1759. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1760. var cw = viewport.width;
  1761. var ch = viewport.height;
  1762. var cx = viewport.x;
  1763. var cy = viewport.y;
  1764. 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);
  1765. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1766. };
  1767. Matrix.Transpose = function (matrix) {
  1768. var result = new Matrix();
  1769. result.m[0] = matrix.m[0];
  1770. result.m[1] = matrix.m[4];
  1771. result.m[2] = matrix.m[8];
  1772. result.m[3] = matrix.m[12];
  1773. result.m[4] = matrix.m[1];
  1774. result.m[5] = matrix.m[5];
  1775. result.m[6] = matrix.m[9];
  1776. result.m[7] = matrix.m[13];
  1777. result.m[8] = matrix.m[2];
  1778. result.m[9] = matrix.m[6];
  1779. result.m[10] = matrix.m[10];
  1780. result.m[11] = matrix.m[14];
  1781. result.m[12] = matrix.m[3];
  1782. result.m[13] = matrix.m[7];
  1783. result.m[14] = matrix.m[11];
  1784. result.m[15] = matrix.m[15];
  1785. return result;
  1786. };
  1787. Matrix.Reflection = function (plane) {
  1788. var matrix = new Matrix();
  1789. Matrix.ReflectionToRef(plane, matrix);
  1790. return matrix;
  1791. };
  1792. Matrix.ReflectionToRef = function (plane, result) {
  1793. plane.normalize();
  1794. var x = plane.normal.x;
  1795. var y = plane.normal.y;
  1796. var z = plane.normal.z;
  1797. var temp = -2 * x;
  1798. var temp2 = -2 * y;
  1799. var temp3 = -2 * z;
  1800. result.m[0] = (temp * x) + 1;
  1801. result.m[1] = temp2 * x;
  1802. result.m[2] = temp3 * x;
  1803. result.m[3] = 0.0;
  1804. result.m[4] = temp * y;
  1805. result.m[5] = (temp2 * y) + 1;
  1806. result.m[6] = temp3 * y;
  1807. result.m[7] = 0.0;
  1808. result.m[8] = temp * z;
  1809. result.m[9] = temp2 * z;
  1810. result.m[10] = (temp3 * z) + 1;
  1811. result.m[11] = 0.0;
  1812. result.m[12] = temp * plane.d;
  1813. result.m[13] = temp2 * plane.d;
  1814. result.m[14] = temp3 * plane.d;
  1815. result.m[15] = 1.0;
  1816. };
  1817. Matrix._tempQuaternion = new Quaternion();
  1818. Matrix._xAxis = Vector3.Zero();
  1819. Matrix._yAxis = Vector3.Zero();
  1820. Matrix._zAxis = Vector3.Zero();
  1821. return Matrix;
  1822. })();
  1823. BABYLON.Matrix = Matrix;
  1824. var Plane = (function () {
  1825. function Plane(a, b, c, d) {
  1826. this.normal = new Vector3(a, b, c);
  1827. this.d = d;
  1828. }
  1829. Plane.prototype.asArray = function () {
  1830. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1831. };
  1832. // Methods
  1833. Plane.prototype.clone = function () {
  1834. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1835. };
  1836. Plane.prototype.normalize = function () {
  1837. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1838. var magnitude = 0;
  1839. if (norm !== 0) {
  1840. magnitude = 1.0 / norm;
  1841. }
  1842. this.normal.x *= magnitude;
  1843. this.normal.y *= magnitude;
  1844. this.normal.z *= magnitude;
  1845. this.d *= magnitude;
  1846. return this;
  1847. };
  1848. Plane.prototype.transform = function (transformation) {
  1849. var transposedMatrix = Matrix.Transpose(transformation);
  1850. var x = this.normal.x;
  1851. var y = this.normal.y;
  1852. var z = this.normal.z;
  1853. var d = this.d;
  1854. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1855. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1856. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1857. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1858. return new Plane(normalX, normalY, normalZ, finalD);
  1859. };
  1860. Plane.prototype.dotCoordinate = function (point) {
  1861. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1862. };
  1863. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1864. var x1 = point2.x - point1.x;
  1865. var y1 = point2.y - point1.y;
  1866. var z1 = point2.z - point1.z;
  1867. var x2 = point3.x - point1.x;
  1868. var y2 = point3.y - point1.y;
  1869. var z2 = point3.z - point1.z;
  1870. var yz = (y1 * z2) - (z1 * y2);
  1871. var xz = (z1 * x2) - (x1 * z2);
  1872. var xy = (x1 * y2) - (y1 * x2);
  1873. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1874. var invPyth;
  1875. if (pyth !== 0) {
  1876. invPyth = 1.0 / pyth;
  1877. }
  1878. else {
  1879. invPyth = 0;
  1880. }
  1881. this.normal.x = yz * invPyth;
  1882. this.normal.y = xz * invPyth;
  1883. this.normal.z = xy * invPyth;
  1884. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1885. return this;
  1886. };
  1887. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1888. var dot = Vector3.Dot(this.normal, direction);
  1889. return (dot <= epsilon);
  1890. };
  1891. Plane.prototype.signedDistanceTo = function (point) {
  1892. return Vector3.Dot(point, this.normal) + this.d;
  1893. };
  1894. // Statics
  1895. Plane.FromArray = function (array) {
  1896. return new Plane(array[0], array[1], array[2], array[3]);
  1897. };
  1898. Plane.FromPoints = function (point1, point2, point3) {
  1899. var result = new Plane(0, 0, 0, 0);
  1900. result.copyFromPoints(point1, point2, point3);
  1901. return result;
  1902. };
  1903. Plane.FromPositionAndNormal = function (origin, normal) {
  1904. var result = new Plane(0, 0, 0, 0);
  1905. normal.normalize();
  1906. result.normal = normal;
  1907. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1908. return result;
  1909. };
  1910. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1911. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1912. return Vector3.Dot(point, normal) + d;
  1913. };
  1914. return Plane;
  1915. })();
  1916. BABYLON.Plane = Plane;
  1917. var Viewport = (function () {
  1918. function Viewport(x, y, width, height) {
  1919. this.x = x;
  1920. this.y = y;
  1921. this.width = width;
  1922. this.height = height;
  1923. }
  1924. Viewport.prototype.toGlobal = function (engine) {
  1925. var width = engine.getRenderWidth();
  1926. var height = engine.getRenderHeight();
  1927. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1928. };
  1929. return Viewport;
  1930. })();
  1931. BABYLON.Viewport = Viewport;
  1932. var Frustum = (function () {
  1933. function Frustum() {
  1934. }
  1935. Frustum.GetPlanes = function (transform) {
  1936. var frustumPlanes = [];
  1937. for (var index = 0; index < 6; index++) {
  1938. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1939. }
  1940. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1941. return frustumPlanes;
  1942. };
  1943. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1944. // Near
  1945. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1946. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1947. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1948. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1949. frustumPlanes[0].normalize();
  1950. // Far
  1951. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1952. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1953. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1954. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1955. frustumPlanes[1].normalize();
  1956. // Left
  1957. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1958. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1959. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1960. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1961. frustumPlanes[2].normalize();
  1962. // Right
  1963. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1964. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1965. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1966. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1967. frustumPlanes[3].normalize();
  1968. // Top
  1969. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1970. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1971. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1972. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1973. frustumPlanes[4].normalize();
  1974. // Bottom
  1975. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1976. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1977. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1978. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1979. frustumPlanes[5].normalize();
  1980. };
  1981. return Frustum;
  1982. })();
  1983. BABYLON.Frustum = Frustum;
  1984. var Ray = (function () {
  1985. function Ray(origin, direction, length) {
  1986. if (length === void 0) { length = Number.MAX_VALUE; }
  1987. this.origin = origin;
  1988. this.direction = direction;
  1989. this.length = length;
  1990. }
  1991. // Methods
  1992. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1993. var d = 0.0;
  1994. var maxValue = Number.MAX_VALUE;
  1995. if (Math.abs(this.direction.x) < 0.0000001) {
  1996. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1997. return false;
  1998. }
  1999. }
  2000. else {
  2001. var inv = 1.0 / this.direction.x;
  2002. var min = (minimum.x - this.origin.x) * inv;
  2003. var max = (maximum.x - this.origin.x) * inv;
  2004. if (max === -Infinity) {
  2005. max = Infinity;
  2006. }
  2007. if (min > max) {
  2008. var temp = min;
  2009. min = max;
  2010. max = temp;
  2011. }
  2012. d = Math.max(min, d);
  2013. maxValue = Math.min(max, maxValue);
  2014. if (d > maxValue) {
  2015. return false;
  2016. }
  2017. }
  2018. if (Math.abs(this.direction.y) < 0.0000001) {
  2019. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2020. return false;
  2021. }
  2022. }
  2023. else {
  2024. inv = 1.0 / this.direction.y;
  2025. min = (minimum.y - this.origin.y) * inv;
  2026. max = (maximum.y - this.origin.y) * inv;
  2027. if (max === -Infinity) {
  2028. max = Infinity;
  2029. }
  2030. if (min > max) {
  2031. temp = min;
  2032. min = max;
  2033. max = temp;
  2034. }
  2035. d = Math.max(min, d);
  2036. maxValue = Math.min(max, maxValue);
  2037. if (d > maxValue) {
  2038. return false;
  2039. }
  2040. }
  2041. if (Math.abs(this.direction.z) < 0.0000001) {
  2042. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2043. return false;
  2044. }
  2045. }
  2046. else {
  2047. inv = 1.0 / this.direction.z;
  2048. min = (minimum.z - this.origin.z) * inv;
  2049. max = (maximum.z - this.origin.z) * inv;
  2050. if (max === -Infinity) {
  2051. max = Infinity;
  2052. }
  2053. if (min > max) {
  2054. temp = min;
  2055. min = max;
  2056. max = temp;
  2057. }
  2058. d = Math.max(min, d);
  2059. maxValue = Math.min(max, maxValue);
  2060. if (d > maxValue) {
  2061. return false;
  2062. }
  2063. }
  2064. return true;
  2065. };
  2066. Ray.prototype.intersectsBox = function (box) {
  2067. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2068. };
  2069. Ray.prototype.intersectsSphere = function (sphere) {
  2070. var x = sphere.center.x - this.origin.x;
  2071. var y = sphere.center.y - this.origin.y;
  2072. var z = sphere.center.z - this.origin.z;
  2073. var pyth = (x * x) + (y * y) + (z * z);
  2074. var rr = sphere.radius * sphere.radius;
  2075. if (pyth <= rr) {
  2076. return true;
  2077. }
  2078. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2079. if (dot < 0.0) {
  2080. return false;
  2081. }
  2082. var temp = pyth - (dot * dot);
  2083. return temp <= rr;
  2084. };
  2085. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2086. if (!this._edge1) {
  2087. this._edge1 = Vector3.Zero();
  2088. this._edge2 = Vector3.Zero();
  2089. this._pvec = Vector3.Zero();
  2090. this._tvec = Vector3.Zero();
  2091. this._qvec = Vector3.Zero();
  2092. }
  2093. vertex1.subtractToRef(vertex0, this._edge1);
  2094. vertex2.subtractToRef(vertex0, this._edge2);
  2095. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2096. var det = Vector3.Dot(this._edge1, this._pvec);
  2097. if (det === 0) {
  2098. return null;
  2099. }
  2100. var invdet = 1 / det;
  2101. this.origin.subtractToRef(vertex0, this._tvec);
  2102. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2103. if (bu < 0 || bu > 1.0) {
  2104. return null;
  2105. }
  2106. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2107. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2108. if (bv < 0 || bu + bv > 1.0) {
  2109. return null;
  2110. }
  2111. //check if the distance is longer than the predefined length.
  2112. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2113. if (distance > this.length) {
  2114. return null;
  2115. }
  2116. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2117. };
  2118. // Statics
  2119. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2120. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2121. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2122. var direction = end.subtract(start);
  2123. direction.normalize();
  2124. return new Ray(start, direction);
  2125. };
  2126. /**
  2127. * 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
  2128. * transformed to the given world matrix.
  2129. * @param origin The origin point
  2130. * @param end The end point
  2131. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2132. */
  2133. Ray.CreateNewFromTo = function (origin, end, world) {
  2134. if (world === void 0) { world = Matrix.Identity(); }
  2135. var direction = end.subtract(origin);
  2136. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2137. direction.normalize();
  2138. return Ray.Transform(new Ray(origin, direction, length), world);
  2139. };
  2140. Ray.Transform = function (ray, matrix) {
  2141. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2142. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2143. return new Ray(newOrigin, newDirection, ray.length);
  2144. };
  2145. return Ray;
  2146. })();
  2147. BABYLON.Ray = Ray;
  2148. (function (Space) {
  2149. Space[Space["LOCAL"] = 0] = "LOCAL";
  2150. Space[Space["WORLD"] = 1] = "WORLD";
  2151. })(BABYLON.Space || (BABYLON.Space = {}));
  2152. var Space = BABYLON.Space;
  2153. var Axis = (function () {
  2154. function Axis() {
  2155. }
  2156. Axis.X = new Vector3(1, 0, 0);
  2157. Axis.Y = new Vector3(0, 1, 0);
  2158. Axis.Z = new Vector3(0, 0, 1);
  2159. return Axis;
  2160. })();
  2161. BABYLON.Axis = Axis;
  2162. ;
  2163. var BezierCurve = (function () {
  2164. function BezierCurve() {
  2165. }
  2166. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2167. // Extract X (which is equal to time here)
  2168. var f0 = 1 - 3 * x2 + 3 * x1;
  2169. var f1 = 3 * x2 - 6 * x1;
  2170. var f2 = 3 * x1;
  2171. var refinedT = t;
  2172. for (var i = 0; i < 5; i++) {
  2173. var refinedT2 = refinedT * refinedT;
  2174. var refinedT3 = refinedT2 * refinedT;
  2175. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2176. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2177. refinedT -= (x - t) * slope;
  2178. refinedT = Math.min(1, Math.max(0, refinedT));
  2179. }
  2180. // Resolve cubic bezier for the given x
  2181. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2182. };
  2183. return BezierCurve;
  2184. })();
  2185. BABYLON.BezierCurve = BezierCurve;
  2186. (function (Orientation) {
  2187. Orientation[Orientation["CW"] = 0] = "CW";
  2188. Orientation[Orientation["CCW"] = 1] = "CCW";
  2189. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2190. var Orientation = BABYLON.Orientation;
  2191. var Angle = (function () {
  2192. function Angle(radians) {
  2193. var _this = this;
  2194. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2195. this.radians = function () { return _this._radians; };
  2196. this._radians = radians;
  2197. if (this._radians < 0)
  2198. this._radians += (2 * Math.PI);
  2199. }
  2200. Angle.BetweenTwoPoints = function (a, b) {
  2201. var delta = b.subtract(a);
  2202. var theta = Math.atan2(delta.y, delta.x);
  2203. return new Angle(theta);
  2204. };
  2205. Angle.FromRadians = function (radians) {
  2206. return new Angle(radians);
  2207. };
  2208. Angle.FromDegrees = function (degrees) {
  2209. return new Angle(degrees * Math.PI / 180);
  2210. };
  2211. return Angle;
  2212. })();
  2213. BABYLON.Angle = Angle;
  2214. var Arc2 = (function () {
  2215. function Arc2(startPoint, midPoint, endPoint) {
  2216. this.startPoint = startPoint;
  2217. this.midPoint = midPoint;
  2218. this.endPoint = endPoint;
  2219. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2220. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2221. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2222. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2223. 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);
  2224. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2225. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2226. var a1 = this.startAngle.degrees();
  2227. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2228. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2229. // angles correction
  2230. if (a2 - a1 > +180.0)
  2231. a2 -= 360.0;
  2232. if (a2 - a1 < -180.0)
  2233. a2 += 360.0;
  2234. if (a3 - a2 > +180.0)
  2235. a3 -= 360.0;
  2236. if (a3 - a2 < -180.0)
  2237. a3 += 360.0;
  2238. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2239. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2240. }
  2241. return Arc2;
  2242. })();
  2243. BABYLON.Arc2 = Arc2;
  2244. var PathCursor = (function () {
  2245. function PathCursor(path) {
  2246. this.path = path;
  2247. this._onchange = new Array();
  2248. this.value = 0;
  2249. this.animations = new Array();
  2250. }
  2251. PathCursor.prototype.getPoint = function () {
  2252. var point = this.path.getPointAtLengthPosition(this.value);
  2253. return new Vector3(point.x, 0, point.y);
  2254. };
  2255. PathCursor.prototype.moveAhead = function (step) {
  2256. if (step === void 0) { step = 0.002; }
  2257. this.move(step);
  2258. return this;
  2259. };
  2260. PathCursor.prototype.moveBack = function (step) {
  2261. if (step === void 0) { step = 0.002; }
  2262. this.move(-step);
  2263. return this;
  2264. };
  2265. PathCursor.prototype.move = function (step) {
  2266. if (Math.abs(step) > 1) {
  2267. throw "step size should be less than 1.";
  2268. }
  2269. this.value += step;
  2270. this.ensureLimits();
  2271. this.raiseOnChange();
  2272. return this;
  2273. };
  2274. PathCursor.prototype.ensureLimits = function () {
  2275. while (this.value > 1) {
  2276. this.value -= 1;
  2277. }
  2278. while (this.value < 0) {
  2279. this.value += 1;
  2280. }
  2281. return this;
  2282. };
  2283. // used by animation engine
  2284. PathCursor.prototype.markAsDirty = function (propertyName) {
  2285. this.ensureLimits();
  2286. this.raiseOnChange();
  2287. return this;
  2288. };
  2289. PathCursor.prototype.raiseOnChange = function () {
  2290. var _this = this;
  2291. this._onchange.forEach(function (f) { return f(_this); });
  2292. return this;
  2293. };
  2294. PathCursor.prototype.onchange = function (f) {
  2295. this._onchange.push(f);
  2296. return this;
  2297. };
  2298. return PathCursor;
  2299. })();
  2300. BABYLON.PathCursor = PathCursor;
  2301. var Path2 = (function () {
  2302. function Path2(x, y) {
  2303. this._points = [];
  2304. this._length = 0;
  2305. this.closed = false;
  2306. this._points.push(new Vector2(x, y));
  2307. }
  2308. Path2.prototype.addLineTo = function (x, y) {
  2309. if (closed) {
  2310. BABYLON.Tools.Error("cannot add lines to closed paths");
  2311. return this;
  2312. }
  2313. var newPoint = new Vector2(x, y);
  2314. var previousPoint = this._points[this._points.length - 1];
  2315. this._points.push(newPoint);
  2316. this._length += newPoint.subtract(previousPoint).length();
  2317. return this;
  2318. };
  2319. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2320. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2321. if (closed) {
  2322. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2323. return this;
  2324. }
  2325. var startPoint = this._points[this._points.length - 1];
  2326. var midPoint = new Vector2(midX, midY);
  2327. var endPoint = new Vector2(endX, endY);
  2328. var arc = new Arc2(startPoint, midPoint, endPoint);
  2329. var increment = arc.angle.radians() / numberOfSegments;
  2330. if (arc.orientation === 0 /* CW */)
  2331. increment *= -1;
  2332. var currentAngle = arc.startAngle.radians() + increment;
  2333. for (var i = 0; i < numberOfSegments; i++) {
  2334. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2335. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2336. this.addLineTo(x, y);
  2337. currentAngle += increment;
  2338. }
  2339. return this;
  2340. };
  2341. Path2.prototype.close = function () {
  2342. this.closed = true;
  2343. return this;
  2344. };
  2345. Path2.prototype.length = function () {
  2346. var result = this._length;
  2347. if (!this.closed) {
  2348. var lastPoint = this._points[this._points.length - 1];
  2349. var firstPoint = this._points[0];
  2350. result += (firstPoint.subtract(lastPoint).length());
  2351. }
  2352. return result;
  2353. };
  2354. Path2.prototype.getPoints = function () {
  2355. return this._points;
  2356. };
  2357. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2358. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2359. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2360. return Vector2.Zero();
  2361. }
  2362. var lengthPosition = normalizedLengthPosition * this.length();
  2363. var previousOffset = 0;
  2364. for (var i = 0; i < this._points.length; i++) {
  2365. var j = (i + 1) % this._points.length;
  2366. var a = this._points[i];
  2367. var b = this._points[j];
  2368. var bToA = b.subtract(a);
  2369. var nextOffset = (bToA.length() + previousOffset);
  2370. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2371. var dir = bToA.normalize();
  2372. var localOffset = lengthPosition - previousOffset;
  2373. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2374. }
  2375. previousOffset = nextOffset;
  2376. }
  2377. BABYLON.Tools.Error("internal error");
  2378. return Vector2.Zero();
  2379. };
  2380. Path2.StartingAt = function (x, y) {
  2381. return new Path2(x, y);
  2382. };
  2383. return Path2;
  2384. })();
  2385. BABYLON.Path2 = Path2;
  2386. })(BABYLON || (BABYLON = {}));
  2387. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2388. (function (BABYLON) {
  2389. // Screenshots
  2390. var screenshotCanvas;
  2391. var cloneValue = function (source, destinationObject) {
  2392. if (!source)
  2393. return null;
  2394. if (source instanceof BABYLON.Mesh) {
  2395. return null;
  2396. }
  2397. if (source instanceof BABYLON.SubMesh) {
  2398. return source.clone(destinationObject);
  2399. }
  2400. else if (source.clone) {
  2401. return source.clone();
  2402. }
  2403. return null;
  2404. };
  2405. var Tools = (function () {
  2406. function Tools() {
  2407. }
  2408. Tools.GetFilename = function (path) {
  2409. var index = path.lastIndexOf("/");
  2410. if (index < 0)
  2411. return path;
  2412. return path.substring(index + 1);
  2413. };
  2414. Tools.GetDOMTextContent = function (element) {
  2415. var result = "";
  2416. var child = element.firstChild;
  2417. while (child) {
  2418. if (child.nodeType == 3) {
  2419. result += child.textContent;
  2420. }
  2421. child = child.nextSibling;
  2422. }
  2423. return result;
  2424. };
  2425. Tools.ToDegrees = function (angle) {
  2426. return angle * 180 / Math.PI;
  2427. };
  2428. Tools.ToRadians = function (angle) {
  2429. return angle * Math.PI / 180;
  2430. };
  2431. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2432. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2433. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2434. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2435. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2436. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2437. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2438. }
  2439. return {
  2440. minimum: minimum,
  2441. maximum: maximum
  2442. };
  2443. };
  2444. Tools.ExtractMinAndMax = function (positions, start, count) {
  2445. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2446. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2447. for (var index = start; index < start + count; index++) {
  2448. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2449. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2450. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2451. }
  2452. return {
  2453. minimum: minimum,
  2454. maximum: maximum
  2455. };
  2456. };
  2457. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2458. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2459. return undefined;
  2460. return Array.isArray(obj) ? obj : [obj];
  2461. };
  2462. // Misc.
  2463. Tools.GetPointerPrefix = function () {
  2464. var eventPrefix = "pointer";
  2465. // Check if hand.js is referenced or if the browser natively supports pointer events
  2466. if (!navigator.pointerEnabled) {
  2467. eventPrefix = "mouse";
  2468. }
  2469. return eventPrefix;
  2470. };
  2471. Tools.QueueNewFrame = function (func) {
  2472. if (window.requestAnimationFrame)
  2473. window.requestAnimationFrame(func);
  2474. else if (window.msRequestAnimationFrame)
  2475. window.msRequestAnimationFrame(func);
  2476. else if (window.webkitRequestAnimationFrame)
  2477. window.webkitRequestAnimationFrame(func);
  2478. else if (window.mozRequestAnimationFrame)
  2479. window.mozRequestAnimationFrame(func);
  2480. else if (window.oRequestAnimationFrame)
  2481. window.oRequestAnimationFrame(func);
  2482. else {
  2483. window.setTimeout(func, 16);
  2484. }
  2485. };
  2486. Tools.RequestFullscreen = function (element) {
  2487. if (element.requestFullscreen)
  2488. element.requestFullscreen();
  2489. else if (element.msRequestFullscreen)
  2490. element.msRequestFullscreen();
  2491. else if (element.webkitRequestFullscreen)
  2492. element.webkitRequestFullscreen();
  2493. else if (element.mozRequestFullScreen)
  2494. element.mozRequestFullScreen();
  2495. };
  2496. Tools.ExitFullscreen = function () {
  2497. if (document.exitFullscreen) {
  2498. document.exitFullscreen();
  2499. }
  2500. else if (document.mozCancelFullScreen) {
  2501. document.mozCancelFullScreen();
  2502. }
  2503. else if (document.webkitCancelFullScreen) {
  2504. document.webkitCancelFullScreen();
  2505. }
  2506. else if (document.msCancelFullScreen) {
  2507. document.msCancelFullScreen();
  2508. }
  2509. };
  2510. // External files
  2511. Tools.CleanUrl = function (url) {
  2512. url = url.replace(/#/mg, "%23");
  2513. return url;
  2514. };
  2515. Tools.LoadImage = function (url, onload, onerror, database) {
  2516. url = Tools.CleanUrl(url);
  2517. var img = new Image();
  2518. if (url.substr(0, 5) != "data:")
  2519. img.crossOrigin = 'anonymous';
  2520. img.onload = function () {
  2521. onload(img);
  2522. };
  2523. img.onerror = function (err) {
  2524. onerror(img, err);
  2525. };
  2526. var noIndexedDB = function () {
  2527. img.src = url;
  2528. };
  2529. var loadFromIndexedDB = function () {
  2530. database.loadImageFromDB(url, img);
  2531. };
  2532. //ANY database to do!
  2533. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2534. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2535. }
  2536. else {
  2537. if (url.indexOf("file:") === -1) {
  2538. noIndexedDB();
  2539. }
  2540. else {
  2541. try {
  2542. var textureName = url.substring(5);
  2543. var blobURL;
  2544. try {
  2545. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2546. }
  2547. catch (ex) {
  2548. // Chrome doesn't support oneTimeOnly parameter
  2549. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2550. }
  2551. img.src = blobURL;
  2552. }
  2553. catch (e) {
  2554. Tools.Log("Error while trying to load texture: " + textureName);
  2555. img.src = null;
  2556. }
  2557. }
  2558. }
  2559. return img;
  2560. };
  2561. //ANY
  2562. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2563. url = Tools.CleanUrl(url);
  2564. var noIndexedDB = function () {
  2565. var request = new XMLHttpRequest();
  2566. var loadUrl = Tools.BaseUrl + url;
  2567. request.open('GET', loadUrl, true);
  2568. if (useArrayBuffer) {
  2569. request.responseType = "arraybuffer";
  2570. }
  2571. request.onprogress = progressCallBack;
  2572. request.onreadystatechange = function () {
  2573. if (request.readyState == 4) {
  2574. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2575. callback(!useArrayBuffer ? request.responseText : request.response);
  2576. }
  2577. else {
  2578. if (onError) {
  2579. onError();
  2580. }
  2581. else {
  2582. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2583. }
  2584. }
  2585. }
  2586. };
  2587. request.send(null);
  2588. };
  2589. var loadFromIndexedDB = function () {
  2590. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2591. };
  2592. if (url.indexOf("file:") !== -1) {
  2593. var fileName = url.substring(5);
  2594. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2595. }
  2596. else {
  2597. // Caching all files
  2598. if (database && database.enableSceneOffline) {
  2599. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2600. }
  2601. else {
  2602. noIndexedDB();
  2603. }
  2604. }
  2605. };
  2606. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2607. var reader = new FileReader();
  2608. reader.onload = function (e) {
  2609. callback(e.target.result);
  2610. };
  2611. reader.onprogress = progressCallback;
  2612. reader.readAsDataURL(fileToLoad);
  2613. };
  2614. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2615. var reader = new FileReader();
  2616. reader.onload = function (e) {
  2617. callback(e.target.result);
  2618. };
  2619. reader.onprogress = progressCallBack;
  2620. if (!useArrayBuffer) {
  2621. // Asynchronous read
  2622. reader.readAsText(fileToLoad);
  2623. }
  2624. else {
  2625. reader.readAsArrayBuffer(fileToLoad);
  2626. }
  2627. };
  2628. // Misc.
  2629. Tools.Clamp = function (value, min, max) {
  2630. if (min === void 0) { min = 0; }
  2631. if (max === void 0) { max = 1; }
  2632. return Math.min(max, Math.max(min, value));
  2633. };
  2634. // Returns -1 when value is a negative number and
  2635. // +1 when value is a positive number.
  2636. Tools.Sign = function (value) {
  2637. value = +value; // convert to a number
  2638. if (value === 0 || isNaN(value))
  2639. return value;
  2640. return value > 0 ? 1 : -1;
  2641. };
  2642. Tools.Format = function (value, decimals) {
  2643. if (decimals === void 0) { decimals = 2; }
  2644. return value.toFixed(decimals);
  2645. };
  2646. Tools.CheckExtends = function (v, min, max) {
  2647. if (v.x < min.x)
  2648. min.x = v.x;
  2649. if (v.y < min.y)
  2650. min.y = v.y;
  2651. if (v.z < min.z)
  2652. min.z = v.z;
  2653. if (v.x > max.x)
  2654. max.x = v.x;
  2655. if (v.y > max.y)
  2656. max.y = v.y;
  2657. if (v.z > max.z)
  2658. max.z = v.z;
  2659. };
  2660. Tools.WithinEpsilon = function (a, b, epsilon) {
  2661. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2662. var num = a - b;
  2663. return -epsilon <= num && num <= epsilon;
  2664. };
  2665. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2666. for (var prop in source) {
  2667. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2668. continue;
  2669. }
  2670. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2671. continue;
  2672. }
  2673. var sourceValue = source[prop];
  2674. var typeOfSourceValue = typeof sourceValue;
  2675. if (typeOfSourceValue == "function") {
  2676. continue;
  2677. }
  2678. if (typeOfSourceValue == "object") {
  2679. if (sourceValue instanceof Array) {
  2680. destination[prop] = [];
  2681. if (sourceValue.length > 0) {
  2682. if (typeof sourceValue[0] == "object") {
  2683. for (var index = 0; index < sourceValue.length; index++) {
  2684. var clonedValue = cloneValue(sourceValue[index], destination);
  2685. if (destination[prop].indexOf(clonedValue) === -1) {
  2686. destination[prop].push(clonedValue);
  2687. }
  2688. }
  2689. }
  2690. else {
  2691. destination[prop] = sourceValue.slice(0);
  2692. }
  2693. }
  2694. }
  2695. else {
  2696. destination[prop] = cloneValue(sourceValue, destination);
  2697. }
  2698. }
  2699. else {
  2700. destination[prop] = sourceValue;
  2701. }
  2702. }
  2703. };
  2704. Tools.IsEmpty = function (obj) {
  2705. for (var i in obj) {
  2706. return false;
  2707. }
  2708. return true;
  2709. };
  2710. Tools.RegisterTopRootEvents = function (events) {
  2711. for (var index = 0; index < events.length; index++) {
  2712. var event = events[index];
  2713. window.addEventListener(event.name, event.handler, false);
  2714. try {
  2715. if (window.parent) {
  2716. window.parent.addEventListener(event.name, event.handler, false);
  2717. }
  2718. }
  2719. catch (e) {
  2720. }
  2721. }
  2722. };
  2723. Tools.UnregisterTopRootEvents = function (events) {
  2724. for (var index = 0; index < events.length; index++) {
  2725. var event = events[index];
  2726. window.removeEventListener(event.name, event.handler);
  2727. try {
  2728. if (window.parent) {
  2729. window.parent.removeEventListener(event.name, event.handler);
  2730. }
  2731. }
  2732. catch (e) {
  2733. }
  2734. }
  2735. };
  2736. Tools.CreateScreenshot = function (engine, camera, size) {
  2737. var width;
  2738. var height;
  2739. var scene = camera.getScene();
  2740. var previousCamera = null;
  2741. if (scene.activeCamera !== camera) {
  2742. previousCamera = scene.activeCamera;
  2743. scene.activeCamera = camera;
  2744. }
  2745. //If a precision value is specified
  2746. if (size.precision) {
  2747. width = Math.round(engine.getRenderWidth() * size.precision);
  2748. height = Math.round(width / engine.getAspectRatio(camera));
  2749. size = { width: width, height: height };
  2750. }
  2751. else if (size.width && size.height) {
  2752. width = size.width;
  2753. height = size.height;
  2754. }
  2755. else if (size.width && !size.height) {
  2756. width = size.width;
  2757. height = Math.round(width / engine.getAspectRatio(camera));
  2758. size = { width: width, height: height };
  2759. }
  2760. else if (size.height && !size.width) {
  2761. height = size.height;
  2762. width = Math.round(height * engine.getAspectRatio(camera));
  2763. size = { width: width, height: height };
  2764. }
  2765. else if (!isNaN(size)) {
  2766. height = size;
  2767. width = size;
  2768. }
  2769. else {
  2770. Tools.Error("Invalid 'size' parameter !");
  2771. return;
  2772. }
  2773. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2774. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2775. texture.renderList = scene.meshes;
  2776. texture.onAfterRender = function () {
  2777. // Read the contents of the framebuffer
  2778. var numberOfChannelsByLine = width * 4;
  2779. var halfHeight = height / 2;
  2780. //Reading datas from WebGL
  2781. var data = engine.readPixels(0, 0, width, height);
  2782. for (var i = 0; i < halfHeight; i++) {
  2783. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2784. var currentCell = j + i * numberOfChannelsByLine;
  2785. var targetLine = height - i - 1;
  2786. var targetCell = j + targetLine * numberOfChannelsByLine;
  2787. var temp = data[currentCell];
  2788. data[currentCell] = data[targetCell];
  2789. data[targetCell] = temp;
  2790. }
  2791. }
  2792. // Create a 2D canvas to store the result
  2793. if (!screenshotCanvas) {
  2794. screenshotCanvas = document.createElement('canvas');
  2795. }
  2796. screenshotCanvas.width = width;
  2797. screenshotCanvas.height = height;
  2798. var context = screenshotCanvas.getContext('2d');
  2799. // Copy the pixels to a 2D canvas
  2800. var imageData = context.createImageData(width, height);
  2801. imageData.data.set(data);
  2802. context.putImageData(imageData, 0, 0);
  2803. var base64Image = screenshotCanvas.toDataURL();
  2804. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2805. if (("download" in document.createElement("a"))) {
  2806. var a = window.document.createElement("a");
  2807. a.href = base64Image;
  2808. var date = new Date();
  2809. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2810. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2811. window.document.body.appendChild(a);
  2812. a.addEventListener("click", function () {
  2813. a.parentElement.removeChild(a);
  2814. });
  2815. a.click();
  2816. }
  2817. else {
  2818. var newWindow = window.open("");
  2819. var img = newWindow.document.createElement("img");
  2820. img.src = base64Image;
  2821. newWindow.document.body.appendChild(img);
  2822. }
  2823. };
  2824. scene.incrementRenderId();
  2825. texture.render(true);
  2826. texture.dispose();
  2827. if (previousCamera) {
  2828. scene.activeCamera = previousCamera;
  2829. }
  2830. };
  2831. // XHR response validator for local file scenario
  2832. Tools.ValidateXHRData = function (xhr, dataType) {
  2833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2834. if (dataType === void 0) { dataType = 7; }
  2835. try {
  2836. if (dataType & 1) {
  2837. if (xhr.responseText && xhr.responseText.length > 0) {
  2838. return true;
  2839. }
  2840. else if (dataType === 1) {
  2841. return false;
  2842. }
  2843. }
  2844. if (dataType & 2) {
  2845. // Check header width and height since there is no "TGA" magic number
  2846. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2848. return true;
  2849. }
  2850. else if (dataType === 2) {
  2851. return false;
  2852. }
  2853. }
  2854. if (dataType & 4) {
  2855. // Check for the "DDS" magic number
  2856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2857. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2858. return true;
  2859. }
  2860. else {
  2861. return false;
  2862. }
  2863. }
  2864. }
  2865. catch (e) {
  2866. }
  2867. return false;
  2868. };
  2869. Object.defineProperty(Tools, "NoneLogLevel", {
  2870. get: function () {
  2871. return Tools._NoneLogLevel;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. Object.defineProperty(Tools, "MessageLogLevel", {
  2877. get: function () {
  2878. return Tools._MessageLogLevel;
  2879. },
  2880. enumerable: true,
  2881. configurable: true
  2882. });
  2883. Object.defineProperty(Tools, "WarningLogLevel", {
  2884. get: function () {
  2885. return Tools._WarningLogLevel;
  2886. },
  2887. enumerable: true,
  2888. configurable: true
  2889. });
  2890. Object.defineProperty(Tools, "ErrorLogLevel", {
  2891. get: function () {
  2892. return Tools._ErrorLogLevel;
  2893. },
  2894. enumerable: true,
  2895. configurable: true
  2896. });
  2897. Object.defineProperty(Tools, "AllLogLevel", {
  2898. get: function () {
  2899. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. Tools._AddLogEntry = function (entry) {
  2905. Tools._LogCache = entry + Tools._LogCache;
  2906. if (Tools.OnNewCacheEntry) {
  2907. Tools.OnNewCacheEntry(entry);
  2908. }
  2909. };
  2910. Tools._FormatMessage = function (message) {
  2911. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2912. var date = new Date();
  2913. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2914. };
  2915. Tools._LogDisabled = function (message) {
  2916. // nothing to do
  2917. };
  2918. Tools._LogEnabled = function (message) {
  2919. var formattedMessage = Tools._FormatMessage(message);
  2920. console.log("BJS - " + formattedMessage);
  2921. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2922. Tools._AddLogEntry(entry);
  2923. };
  2924. Tools._WarnDisabled = function (message) {
  2925. // nothing to do
  2926. };
  2927. Tools._WarnEnabled = function (message) {
  2928. var formattedMessage = Tools._FormatMessage(message);
  2929. console.warn("BJS - " + formattedMessage);
  2930. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2931. Tools._AddLogEntry(entry);
  2932. };
  2933. Tools._ErrorDisabled = function (message) {
  2934. // nothing to do
  2935. };
  2936. Tools._ErrorEnabled = function (message) {
  2937. var formattedMessage = Tools._FormatMessage(message);
  2938. console.error("BJS - " + formattedMessage);
  2939. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2940. Tools._AddLogEntry(entry);
  2941. };
  2942. Object.defineProperty(Tools, "LogCache", {
  2943. get: function () {
  2944. return Tools._LogCache;
  2945. },
  2946. enumerable: true,
  2947. configurable: true
  2948. });
  2949. Object.defineProperty(Tools, "LogLevels", {
  2950. set: function (level) {
  2951. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2952. Tools.Log = Tools._LogEnabled;
  2953. }
  2954. else {
  2955. Tools.Log = Tools._LogDisabled;
  2956. }
  2957. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2958. Tools.Warn = Tools._WarnEnabled;
  2959. }
  2960. else {
  2961. Tools.Warn = Tools._WarnDisabled;
  2962. }
  2963. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2964. Tools.Error = Tools._ErrorEnabled;
  2965. }
  2966. else {
  2967. Tools.Error = Tools._ErrorDisabled;
  2968. }
  2969. },
  2970. enumerable: true,
  2971. configurable: true
  2972. });
  2973. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2974. get: function () {
  2975. return Tools._PerformanceNoneLogLevel;
  2976. },
  2977. enumerable: true,
  2978. configurable: true
  2979. });
  2980. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2981. get: function () {
  2982. return Tools._PerformanceUserMarkLogLevel;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2988. get: function () {
  2989. return Tools._PerformanceConsoleLogLevel;
  2990. },
  2991. enumerable: true,
  2992. configurable: true
  2993. });
  2994. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2995. set: function (level) {
  2996. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2997. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2998. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2999. return;
  3000. }
  3001. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3002. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3003. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3004. return;
  3005. }
  3006. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3007. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3008. },
  3009. enumerable: true,
  3010. configurable: true
  3011. });
  3012. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3013. };
  3014. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3015. };
  3016. Tools._StartUserMark = function (counterName, condition) {
  3017. if (condition === void 0) { condition = true; }
  3018. if (!condition || !Tools._performance.mark) {
  3019. return;
  3020. }
  3021. Tools._performance.mark(counterName + "-Begin");
  3022. };
  3023. Tools._EndUserMark = function (counterName, condition) {
  3024. if (condition === void 0) { condition = true; }
  3025. if (!condition || !Tools._performance.mark) {
  3026. return;
  3027. }
  3028. Tools._performance.mark(counterName + "-End");
  3029. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3030. };
  3031. Tools._StartPerformanceConsole = function (counterName, condition) {
  3032. if (condition === void 0) { condition = true; }
  3033. if (!condition) {
  3034. return;
  3035. }
  3036. Tools._StartUserMark(counterName, condition);
  3037. if (console.time) {
  3038. console.time(counterName);
  3039. }
  3040. };
  3041. Tools._EndPerformanceConsole = function (counterName, condition) {
  3042. if (condition === void 0) { condition = true; }
  3043. if (!condition) {
  3044. return;
  3045. }
  3046. Tools._EndUserMark(counterName, condition);
  3047. if (console.time) {
  3048. console.timeEnd(counterName);
  3049. }
  3050. };
  3051. Object.defineProperty(Tools, "Now", {
  3052. get: function () {
  3053. if (window.performance && window.performance.now) {
  3054. return window.performance.now();
  3055. }
  3056. return new Date().getTime();
  3057. },
  3058. enumerable: true,
  3059. configurable: true
  3060. });
  3061. // Deprecated
  3062. Tools.GetFps = function () {
  3063. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3064. return 0;
  3065. };
  3066. Tools.BaseUrl = "";
  3067. Tools.GetExponantOfTwo = function (value, max) {
  3068. var count = 1;
  3069. do {
  3070. count *= 2;
  3071. } while (count < value);
  3072. if (count > max)
  3073. count = max;
  3074. return count;
  3075. };
  3076. // Logs
  3077. Tools._NoneLogLevel = 0;
  3078. Tools._MessageLogLevel = 1;
  3079. Tools._WarningLogLevel = 2;
  3080. Tools._ErrorLogLevel = 4;
  3081. Tools._LogCache = "";
  3082. Tools.Log = Tools._LogEnabled;
  3083. Tools.Warn = Tools._WarnEnabled;
  3084. Tools.Error = Tools._ErrorEnabled;
  3085. // Performances
  3086. Tools._PerformanceNoneLogLevel = 0;
  3087. Tools._PerformanceUserMarkLogLevel = 1;
  3088. Tools._PerformanceConsoleLogLevel = 2;
  3089. Tools._performance = window.performance;
  3090. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3091. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3092. return Tools;
  3093. })();
  3094. BABYLON.Tools = Tools;
  3095. /**
  3096. * An implementation of a loop for asynchronous functions.
  3097. */
  3098. var AsyncLoop = (function () {
  3099. /**
  3100. * Constroctor.
  3101. * @param iterations the number of iterations.
  3102. * @param _fn the function to run each iteration
  3103. * @param _successCallback the callback that will be called upon succesful execution
  3104. * @param offset starting offset.
  3105. */
  3106. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3107. if (offset === void 0) { offset = 0; }
  3108. this.iterations = iterations;
  3109. this._fn = _fn;
  3110. this._successCallback = _successCallback;
  3111. this.index = offset - 1;
  3112. this._done = false;
  3113. }
  3114. /**
  3115. * Execute the next iteration. Must be called after the last iteration was finished.
  3116. */
  3117. AsyncLoop.prototype.executeNext = function () {
  3118. if (!this._done) {
  3119. if (this.index + 1 < this.iterations) {
  3120. ++this.index;
  3121. this._fn(this);
  3122. }
  3123. else {
  3124. this.breakLoop();
  3125. }
  3126. }
  3127. };
  3128. /**
  3129. * Break the loop and run the success callback.
  3130. */
  3131. AsyncLoop.prototype.breakLoop = function () {
  3132. this._done = true;
  3133. this._successCallback();
  3134. };
  3135. /**
  3136. * Helper function
  3137. */
  3138. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3139. if (offset === void 0) { offset = 0; }
  3140. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3141. loop.executeNext();
  3142. return loop;
  3143. };
  3144. /**
  3145. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3146. * @param iterations total number of iterations
  3147. * @param syncedIterations number of synchronous iterations in each async iteration.
  3148. * @param fn the function to call each iteration.
  3149. * @param callback a success call back that will be called when iterating stops.
  3150. * @param breakFunction a break condition (optional)
  3151. * @param timeout timeout settings for the setTimeout function. default - 0.
  3152. * @constructor
  3153. */
  3154. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3155. if (timeout === void 0) { timeout = 0; }
  3156. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3157. if (breakFunction && breakFunction())
  3158. loop.breakLoop();
  3159. else {
  3160. setTimeout(function () {
  3161. for (var i = 0; i < syncedIterations; ++i) {
  3162. var iteration = (loop.index * syncedIterations) + i;
  3163. if (iteration >= iterations)
  3164. break;
  3165. fn(iteration);
  3166. if (breakFunction && breakFunction()) {
  3167. loop.breakLoop();
  3168. break;
  3169. }
  3170. }
  3171. loop.executeNext();
  3172. }, timeout);
  3173. }
  3174. }, callback);
  3175. };
  3176. return AsyncLoop;
  3177. })();
  3178. BABYLON.AsyncLoop = AsyncLoop;
  3179. })(BABYLON || (BABYLON = {}));
  3180. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3181. (function (BABYLON) {
  3182. var _DepthCullingState = (function () {
  3183. function _DepthCullingState() {
  3184. this._isDepthTestDirty = false;
  3185. this._isDepthMaskDirty = false;
  3186. this._isDepthFuncDirty = false;
  3187. this._isCullFaceDirty = false;
  3188. this._isCullDirty = false;
  3189. }
  3190. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3191. get: function () {
  3192. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3193. },
  3194. enumerable: true,
  3195. configurable: true
  3196. });
  3197. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3198. get: function () {
  3199. return this._cullFace;
  3200. },
  3201. set: function (value) {
  3202. if (this._cullFace === value) {
  3203. return;
  3204. }
  3205. this._cullFace = value;
  3206. this._isCullFaceDirty = true;
  3207. },
  3208. enumerable: true,
  3209. configurable: true
  3210. });
  3211. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3212. get: function () {
  3213. return this._cull;
  3214. },
  3215. set: function (value) {
  3216. if (this._cull === value) {
  3217. return;
  3218. }
  3219. this._cull = value;
  3220. this._isCullDirty = true;
  3221. },
  3222. enumerable: true,
  3223. configurable: true
  3224. });
  3225. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3226. get: function () {
  3227. return this._depthFunc;
  3228. },
  3229. set: function (value) {
  3230. if (this._depthFunc === value) {
  3231. return;
  3232. }
  3233. this._depthFunc = value;
  3234. this._isDepthFuncDirty = true;
  3235. },
  3236. enumerable: true,
  3237. configurable: true
  3238. });
  3239. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3240. get: function () {
  3241. return this._depthMask;
  3242. },
  3243. set: function (value) {
  3244. if (this._depthMask === value) {
  3245. return;
  3246. }
  3247. this._depthMask = value;
  3248. this._isDepthMaskDirty = true;
  3249. },
  3250. enumerable: true,
  3251. configurable: true
  3252. });
  3253. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3254. get: function () {
  3255. return this._depthTest;
  3256. },
  3257. set: function (value) {
  3258. if (this._depthTest === value) {
  3259. return;
  3260. }
  3261. this._depthTest = value;
  3262. this._isDepthTestDirty = true;
  3263. },
  3264. enumerable: true,
  3265. configurable: true
  3266. });
  3267. _DepthCullingState.prototype.reset = function () {
  3268. this._depthMask = true;
  3269. this._depthTest = true;
  3270. this._depthFunc = null;
  3271. this._cull = null;
  3272. this._cullFace = null;
  3273. this._isDepthTestDirty = true;
  3274. this._isDepthMaskDirty = true;
  3275. this._isDepthFuncDirty = false;
  3276. this._isCullFaceDirty = false;
  3277. this._isCullDirty = false;
  3278. };
  3279. _DepthCullingState.prototype.apply = function (gl) {
  3280. if (!this.isDirty) {
  3281. return;
  3282. }
  3283. // Cull
  3284. if (this._isCullDirty) {
  3285. if (this.cull) {
  3286. gl.enable(gl.CULL_FACE);
  3287. }
  3288. else {
  3289. gl.disable(gl.CULL_FACE);
  3290. }
  3291. this._isCullDirty = false;
  3292. }
  3293. // Cull face
  3294. if (this._isCullFaceDirty) {
  3295. gl.cullFace(this.cullFace);
  3296. this._isCullFaceDirty = false;
  3297. }
  3298. // Depth mask
  3299. if (this._isDepthMaskDirty) {
  3300. gl.depthMask(this.depthMask);
  3301. this._isDepthMaskDirty = false;
  3302. }
  3303. // Depth test
  3304. if (this._isDepthTestDirty) {
  3305. if (this.depthTest) {
  3306. gl.enable(gl.DEPTH_TEST);
  3307. }
  3308. else {
  3309. gl.disable(gl.DEPTH_TEST);
  3310. }
  3311. this._isDepthTestDirty = false;
  3312. }
  3313. // Depth func
  3314. if (this._isDepthFuncDirty) {
  3315. gl.depthFunc(this.depthFunc);
  3316. this._isDepthFuncDirty = false;
  3317. }
  3318. };
  3319. return _DepthCullingState;
  3320. })();
  3321. BABYLON._DepthCullingState = _DepthCullingState;
  3322. var _AlphaState = (function () {
  3323. function _AlphaState() {
  3324. this._isAlphaBlendDirty = false;
  3325. this._isBlendFunctionParametersDirty = false;
  3326. this._alphaBlend = false;
  3327. this._blendFunctionParameters = new Array(4);
  3328. }
  3329. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3330. get: function () {
  3331. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3332. },
  3333. enumerable: true,
  3334. configurable: true
  3335. });
  3336. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3337. get: function () {
  3338. return this._alphaBlend;
  3339. },
  3340. set: function (value) {
  3341. if (this._alphaBlend === value) {
  3342. return;
  3343. }
  3344. this._alphaBlend = value;
  3345. this._isAlphaBlendDirty = true;
  3346. },
  3347. enumerable: true,
  3348. configurable: true
  3349. });
  3350. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3351. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3352. return;
  3353. }
  3354. this._blendFunctionParameters[0] = value0;
  3355. this._blendFunctionParameters[1] = value1;
  3356. this._blendFunctionParameters[2] = value2;
  3357. this._blendFunctionParameters[3] = value3;
  3358. this._isBlendFunctionParametersDirty = true;
  3359. };
  3360. _AlphaState.prototype.reset = function () {
  3361. this._alphaBlend = false;
  3362. this._blendFunctionParameters[0] = null;
  3363. this._blendFunctionParameters[1] = null;
  3364. this._blendFunctionParameters[2] = null;
  3365. this._blendFunctionParameters[3] = null;
  3366. this._isAlphaBlendDirty = true;
  3367. this._isBlendFunctionParametersDirty = false;
  3368. };
  3369. _AlphaState.prototype.apply = function (gl) {
  3370. if (!this.isDirty) {
  3371. return;
  3372. }
  3373. // Alpha blend
  3374. if (this._isAlphaBlendDirty) {
  3375. if (this._alphaBlend) {
  3376. gl.enable(gl.BLEND);
  3377. }
  3378. else {
  3379. gl.disable(gl.BLEND);
  3380. }
  3381. this._isAlphaBlendDirty = false;
  3382. }
  3383. // Alpha function
  3384. if (this._isBlendFunctionParametersDirty) {
  3385. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3386. this._isBlendFunctionParametersDirty = false;
  3387. }
  3388. };
  3389. return _AlphaState;
  3390. })();
  3391. BABYLON._AlphaState = _AlphaState;
  3392. var compileShader = function (gl, source, type, defines) {
  3393. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3394. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3395. gl.compileShader(shader);
  3396. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3397. throw new Error(gl.getShaderInfoLog(shader));
  3398. }
  3399. return shader;
  3400. };
  3401. var getWebGLTextureType = function (gl, type) {
  3402. var textureType = gl.UNSIGNED_BYTE;
  3403. if (type === Engine.TEXTURETYPE_FLOAT)
  3404. textureType = gl.FLOAT;
  3405. return textureType;
  3406. };
  3407. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3408. var magFilter = gl.NEAREST;
  3409. var minFilter = gl.NEAREST;
  3410. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3411. magFilter = gl.LINEAR;
  3412. if (generateMipMaps) {
  3413. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3414. }
  3415. else {
  3416. minFilter = gl.LINEAR;
  3417. }
  3418. }
  3419. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3420. magFilter = gl.LINEAR;
  3421. if (generateMipMaps) {
  3422. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3423. }
  3424. else {
  3425. minFilter = gl.LINEAR;
  3426. }
  3427. }
  3428. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3429. magFilter = gl.NEAREST;
  3430. if (generateMipMaps) {
  3431. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3432. }
  3433. else {
  3434. minFilter = gl.NEAREST;
  3435. }
  3436. }
  3437. return {
  3438. min: minFilter,
  3439. mag: magFilter
  3440. };
  3441. };
  3442. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3444. var engine = scene.getEngine();
  3445. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3446. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3447. gl.bindTexture(gl.TEXTURE_2D, texture);
  3448. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3449. processFunction(potWidth, potHeight);
  3450. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3453. if (!noMipmap && !isCompressed) {
  3454. gl.generateMipmap(gl.TEXTURE_2D);
  3455. }
  3456. gl.bindTexture(gl.TEXTURE_2D, null);
  3457. engine._activeTexturesCache = [];
  3458. texture._baseWidth = width;
  3459. texture._baseHeight = height;
  3460. texture._width = potWidth;
  3461. texture._height = potHeight;
  3462. texture.isReady = true;
  3463. texture.samplingMode = samplingMode;
  3464. scene._removePendingData(texture);
  3465. };
  3466. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3467. var onload = function () {
  3468. loadedImages[index] = img;
  3469. loadedImages._internalCount++;
  3470. scene._removePendingData(img);
  3471. if (loadedImages._internalCount === 6) {
  3472. onfinish(loadedImages);
  3473. }
  3474. };
  3475. var onerror = function () {
  3476. scene._removePendingData(img);
  3477. };
  3478. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3479. scene._addPendingData(img);
  3480. };
  3481. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3482. var loadedImages = [];
  3483. loadedImages._internalCount = 0;
  3484. for (var index = 0; index < 6; index++) {
  3485. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3486. }
  3487. };
  3488. var EngineCapabilities = (function () {
  3489. function EngineCapabilities() {
  3490. }
  3491. return EngineCapabilities;
  3492. })();
  3493. BABYLON.EngineCapabilities = EngineCapabilities;
  3494. /**
  3495. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3496. */
  3497. var Engine = (function () {
  3498. /**
  3499. * @constructor
  3500. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3501. * @param {boolean} [antialias] - enable antialias
  3502. * @param options - further options to be sent to the getContext function
  3503. */
  3504. function Engine(canvas, antialias, options) {
  3505. var _this = this;
  3506. // Public members
  3507. this.isFullscreen = false;
  3508. this.isPointerLock = false;
  3509. this.cullBackFaces = true;
  3510. this.renderEvenInBackground = true;
  3511. this.scenes = new Array();
  3512. this._windowIsBackground = false;
  3513. this._loadingDivBackgroundColor = "black";
  3514. this._drawCalls = 0;
  3515. this._renderingQueueLaunched = false;
  3516. this._activeRenderLoops = [];
  3517. // FPS
  3518. this.fpsRange = 60;
  3519. this.previousFramesDuration = [];
  3520. this.fps = 60;
  3521. this.deltaTime = 0;
  3522. // States
  3523. this._depthCullingState = new _DepthCullingState();
  3524. this._alphaState = new _AlphaState();
  3525. this._alphaMode = Engine.ALPHA_DISABLE;
  3526. // Cache
  3527. this._loadedTexturesCache = new Array();
  3528. this._activeTexturesCache = new Array();
  3529. this._compiledEffects = {};
  3530. this._uintIndicesCurrentlySet = false;
  3531. this._renderingCanvas = canvas;
  3532. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3533. options = options || {};
  3534. options.antialias = antialias;
  3535. try {
  3536. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3537. }
  3538. catch (e) {
  3539. throw new Error("WebGL not supported");
  3540. }
  3541. if (!this._gl) {
  3542. throw new Error("WebGL not supported");
  3543. }
  3544. this._onBlur = function () {
  3545. _this._windowIsBackground = true;
  3546. };
  3547. this._onFocus = function () {
  3548. _this._windowIsBackground = false;
  3549. };
  3550. window.addEventListener("blur", this._onBlur);
  3551. window.addEventListener("focus", this._onFocus);
  3552. // Textures
  3553. this._workingCanvas = document.createElement("canvas");
  3554. this._workingContext = this._workingCanvas.getContext("2d");
  3555. // Viewport
  3556. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3557. this.resize();
  3558. // Caps
  3559. this._caps = new EngineCapabilities();
  3560. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3561. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3562. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3563. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3564. // Infos
  3565. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3566. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3567. if (rendererInfo != null) {
  3568. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3569. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3570. }
  3571. if (!this._glVendor) {
  3572. this._glVendor = "Unknown vendor";
  3573. }
  3574. if (!this._glRenderer) {
  3575. this._glRenderer = "Unknown renderer";
  3576. }
  3577. // Extensions
  3578. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3579. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3580. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3581. 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');
  3582. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3583. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3584. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3585. // Depth buffer
  3586. this.setDepthBuffer(true);
  3587. this.setDepthFunctionToLessOrEqual();
  3588. this.setDepthWrite(true);
  3589. // Fullscreen
  3590. this._onFullscreenChange = function () {
  3591. if (document.fullscreen !== undefined) {
  3592. _this.isFullscreen = document.fullscreen;
  3593. }
  3594. else if (document.mozFullScreen !== undefined) {
  3595. _this.isFullscreen = document.mozFullScreen;
  3596. }
  3597. else if (document.webkitIsFullScreen !== undefined) {
  3598. _this.isFullscreen = document.webkitIsFullScreen;
  3599. }
  3600. else if (document.msIsFullScreen !== undefined) {
  3601. _this.isFullscreen = document.msIsFullScreen;
  3602. }
  3603. // Pointer lock
  3604. if (_this.isFullscreen && _this._pointerLockRequested) {
  3605. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3606. if (canvas.requestPointerLock) {
  3607. canvas.requestPointerLock();
  3608. }
  3609. }
  3610. };
  3611. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3612. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3613. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3614. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3615. // Pointer lock
  3616. this._onPointerLockChange = function () {
  3617. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3618. };
  3619. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3620. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3621. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3622. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3623. if (!Engine.audioEngine) {
  3624. Engine.audioEngine = new BABYLON.AudioEngine();
  3625. }
  3626. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3627. }
  3628. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3629. get: function () {
  3630. return Engine._ALPHA_DISABLE;
  3631. },
  3632. enumerable: true,
  3633. configurable: true
  3634. });
  3635. Object.defineProperty(Engine, "ALPHA_ADD", {
  3636. get: function () {
  3637. return Engine._ALPHA_ADD;
  3638. },
  3639. enumerable: true,
  3640. configurable: true
  3641. });
  3642. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3643. get: function () {
  3644. return Engine._ALPHA_COMBINE;
  3645. },
  3646. enumerable: true,
  3647. configurable: true
  3648. });
  3649. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3650. get: function () {
  3651. return Engine._DELAYLOADSTATE_NONE;
  3652. },
  3653. enumerable: true,
  3654. configurable: true
  3655. });
  3656. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3657. get: function () {
  3658. return Engine._DELAYLOADSTATE_LOADED;
  3659. },
  3660. enumerable: true,
  3661. configurable: true
  3662. });
  3663. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3664. get: function () {
  3665. return Engine._DELAYLOADSTATE_LOADING;
  3666. },
  3667. enumerable: true,
  3668. configurable: true
  3669. });
  3670. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3671. get: function () {
  3672. return Engine._DELAYLOADSTATE_NOTLOADED;
  3673. },
  3674. enumerable: true,
  3675. configurable: true
  3676. });
  3677. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3678. get: function () {
  3679. return Engine._TEXTUREFORMAT_ALPHA;
  3680. },
  3681. enumerable: true,
  3682. configurable: true
  3683. });
  3684. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3685. get: function () {
  3686. return Engine._TEXTUREFORMAT_LUMINANCE;
  3687. },
  3688. enumerable: true,
  3689. configurable: true
  3690. });
  3691. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3692. get: function () {
  3693. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3694. },
  3695. enumerable: true,
  3696. configurable: true
  3697. });
  3698. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3699. get: function () {
  3700. return Engine._TEXTUREFORMAT_RGB;
  3701. },
  3702. enumerable: true,
  3703. configurable: true
  3704. });
  3705. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3706. get: function () {
  3707. return Engine._TEXTUREFORMAT_RGBA;
  3708. },
  3709. enumerable: true,
  3710. configurable: true
  3711. });
  3712. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3713. get: function () {
  3714. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3715. },
  3716. enumerable: true,
  3717. configurable: true
  3718. });
  3719. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3720. get: function () {
  3721. return Engine._TEXTURETYPE_FLOAT;
  3722. },
  3723. enumerable: true,
  3724. configurable: true
  3725. });
  3726. Object.defineProperty(Engine, "Version", {
  3727. get: function () {
  3728. return "2.0.0";
  3729. },
  3730. enumerable: true,
  3731. configurable: true
  3732. });
  3733. Engine.prototype.getGlInfo = function () {
  3734. return {
  3735. vendor: this._glVendor,
  3736. renderer: this._glRenderer,
  3737. version: this._glVersion
  3738. };
  3739. };
  3740. Engine.prototype.getAspectRatio = function (camera) {
  3741. var viewport = camera.viewport;
  3742. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3743. };
  3744. Engine.prototype.getRenderWidth = function () {
  3745. if (this._currentRenderTarget) {
  3746. return this._currentRenderTarget._width;
  3747. }
  3748. return this._renderingCanvas.width;
  3749. };
  3750. Engine.prototype.getRenderHeight = function () {
  3751. if (this._currentRenderTarget) {
  3752. return this._currentRenderTarget._height;
  3753. }
  3754. return this._renderingCanvas.height;
  3755. };
  3756. Engine.prototype.getRenderingCanvas = function () {
  3757. return this._renderingCanvas;
  3758. };
  3759. Engine.prototype.getRenderingCanvasClientRect = function () {
  3760. return this._renderingCanvas.getBoundingClientRect();
  3761. };
  3762. Engine.prototype.setHardwareScalingLevel = function (level) {
  3763. this._hardwareScalingLevel = level;
  3764. this.resize();
  3765. };
  3766. Engine.prototype.getHardwareScalingLevel = function () {
  3767. return this._hardwareScalingLevel;
  3768. };
  3769. Engine.prototype.getLoadedTexturesCache = function () {
  3770. return this._loadedTexturesCache;
  3771. };
  3772. Engine.prototype.getCaps = function () {
  3773. return this._caps;
  3774. };
  3775. Object.defineProperty(Engine.prototype, "drawCalls", {
  3776. get: function () {
  3777. return this._drawCalls;
  3778. },
  3779. enumerable: true,
  3780. configurable: true
  3781. });
  3782. // Methods
  3783. Engine.prototype.resetDrawCalls = function () {
  3784. this._drawCalls = 0;
  3785. };
  3786. Engine.prototype.setDepthFunctionToGreater = function () {
  3787. this._depthCullingState.depthFunc = this._gl.GREATER;
  3788. };
  3789. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3790. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3791. };
  3792. Engine.prototype.setDepthFunctionToLess = function () {
  3793. this._depthCullingState.depthFunc = this._gl.LESS;
  3794. };
  3795. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3796. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3797. };
  3798. /**
  3799. * stop executing a render loop function and remove it from the execution array
  3800. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3801. */
  3802. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3803. if (!renderFunction) {
  3804. this._activeRenderLoops = [];
  3805. return;
  3806. }
  3807. var index = this._activeRenderLoops.indexOf(renderFunction);
  3808. if (index >= 0) {
  3809. this._activeRenderLoops.splice(index, 1);
  3810. }
  3811. };
  3812. Engine.prototype._renderLoop = function () {
  3813. var _this = this;
  3814. var shouldRender = true;
  3815. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3816. shouldRender = false;
  3817. }
  3818. if (shouldRender) {
  3819. // Start new frame
  3820. this.beginFrame();
  3821. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3822. var renderFunction = this._activeRenderLoops[index];
  3823. renderFunction();
  3824. }
  3825. // Present
  3826. this.endFrame();
  3827. }
  3828. if (this._activeRenderLoops.length > 0) {
  3829. // Register new frame
  3830. BABYLON.Tools.QueueNewFrame(function () {
  3831. _this._renderLoop();
  3832. });
  3833. }
  3834. else {
  3835. this._renderingQueueLaunched = false;
  3836. }
  3837. };
  3838. /**
  3839. * Register and execute a render loop. The engine can have more than one render function.
  3840. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3841. * @example
  3842. * engine.runRenderLoop(function () {
  3843. * scene.render()
  3844. * })
  3845. */
  3846. Engine.prototype.runRenderLoop = function (renderFunction) {
  3847. var _this = this;
  3848. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3849. return;
  3850. }
  3851. this._activeRenderLoops.push(renderFunction);
  3852. if (!this._renderingQueueLaunched) {
  3853. this._renderingQueueLaunched = true;
  3854. BABYLON.Tools.QueueNewFrame(function () {
  3855. _this._renderLoop();
  3856. });
  3857. }
  3858. };
  3859. /**
  3860. * Toggle full screen mode.
  3861. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3862. */
  3863. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3864. if (this.isFullscreen) {
  3865. BABYLON.Tools.ExitFullscreen();
  3866. }
  3867. else {
  3868. this._pointerLockRequested = requestPointerLock;
  3869. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3870. }
  3871. };
  3872. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3873. this.applyStates();
  3874. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3875. if (this._depthCullingState.depthMask) {
  3876. this._gl.clearDepth(1.0);
  3877. }
  3878. var mode = 0;
  3879. if (backBuffer)
  3880. mode |= this._gl.COLOR_BUFFER_BIT;
  3881. if (depthStencil && this._depthCullingState.depthMask)
  3882. mode |= this._gl.DEPTH_BUFFER_BIT;
  3883. this._gl.clear(mode);
  3884. };
  3885. /**
  3886. * Set the WebGL's viewport
  3887. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3888. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3889. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3890. */
  3891. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3892. var width = requiredWidth || this._renderingCanvas.width;
  3893. var height = requiredHeight || this._renderingCanvas.height;
  3894. var x = viewport.x || 0;
  3895. var y = viewport.y || 0;
  3896. this._cachedViewport = viewport;
  3897. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3898. };
  3899. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3900. this._cachedViewport = null;
  3901. this._gl.viewport(x, y, width, height);
  3902. };
  3903. Engine.prototype.beginFrame = function () {
  3904. this._measureFps();
  3905. };
  3906. Engine.prototype.endFrame = function () {
  3907. this.flushFramebuffer();
  3908. };
  3909. /**
  3910. * resize the view according to the canvas' size.
  3911. * @example
  3912. * window.addEventListener("resize", function () {
  3913. * engine.resize();
  3914. * });
  3915. */
  3916. Engine.prototype.resize = function () {
  3917. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3918. };
  3919. /**
  3920. * force a specific size of the canvas
  3921. * @param {number} width - the new canvas' width
  3922. * @param {number} height - the new canvas' height
  3923. */
  3924. Engine.prototype.setSize = function (width, height) {
  3925. this._renderingCanvas.width = width;
  3926. this._renderingCanvas.height = height;
  3927. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3928. };
  3929. Engine.prototype.bindFramebuffer = function (texture) {
  3930. this._currentRenderTarget = texture;
  3931. var gl = this._gl;
  3932. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3933. this._gl.viewport(0, 0, texture._width, texture._height);
  3934. this.wipeCaches();
  3935. };
  3936. Engine.prototype.unBindFramebuffer = function (texture) {
  3937. this._currentRenderTarget = null;
  3938. if (texture.generateMipMaps) {
  3939. var gl = this._gl;
  3940. gl.bindTexture(gl.TEXTURE_2D, texture);
  3941. gl.generateMipmap(gl.TEXTURE_2D);
  3942. gl.bindTexture(gl.TEXTURE_2D, null);
  3943. }
  3944. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3945. };
  3946. Engine.prototype.flushFramebuffer = function () {
  3947. // this._gl.flush();
  3948. };
  3949. Engine.prototype.restoreDefaultFramebuffer = function () {
  3950. this._currentRenderTarget = null;
  3951. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3952. this.setViewport(this._cachedViewport);
  3953. this.wipeCaches();
  3954. };
  3955. // VBOs
  3956. Engine.prototype._resetVertexBufferBinding = function () {
  3957. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3958. this._cachedVertexBuffers = null;
  3959. };
  3960. Engine.prototype.createVertexBuffer = function (vertices) {
  3961. var vbo = this._gl.createBuffer();
  3962. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3963. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3964. this._resetVertexBufferBinding();
  3965. vbo.references = 1;
  3966. return vbo;
  3967. };
  3968. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3969. var vbo = this._gl.createBuffer();
  3970. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3971. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3972. this._resetVertexBufferBinding();
  3973. vbo.references = 1;
  3974. return vbo;
  3975. };
  3976. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3977. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3978. if (offset === undefined) {
  3979. offset = 0;
  3980. }
  3981. if (vertices instanceof Float32Array) {
  3982. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3983. }
  3984. else {
  3985. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3986. }
  3987. this._resetVertexBufferBinding();
  3988. };
  3989. Engine.prototype._resetIndexBufferBinding = function () {
  3990. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3991. this._cachedIndexBuffer = null;
  3992. };
  3993. Engine.prototype.createIndexBuffer = function (indices) {
  3994. var vbo = this._gl.createBuffer();
  3995. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3996. // Check for 32 bits indices
  3997. var arrayBuffer;
  3998. var need32Bits = false;
  3999. if (this._caps.uintIndices) {
  4000. for (var index = 0; index < indices.length; index++) {
  4001. if (indices[index] > 65535) {
  4002. need32Bits = true;
  4003. break;
  4004. }
  4005. }
  4006. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4007. }
  4008. else {
  4009. arrayBuffer = new Uint16Array(indices);
  4010. }
  4011. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4012. this._resetIndexBufferBinding();
  4013. vbo.references = 1;
  4014. vbo.is32Bits = need32Bits;
  4015. return vbo;
  4016. };
  4017. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4018. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4019. this._cachedVertexBuffers = vertexBuffer;
  4020. this._cachedEffectForVertexBuffers = effect;
  4021. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4022. var offset = 0;
  4023. for (var index = 0; index < vertexDeclaration.length; index++) {
  4024. var order = effect.getAttributeLocation(index);
  4025. if (order >= 0) {
  4026. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4027. }
  4028. offset += vertexDeclaration[index] * 4;
  4029. }
  4030. }
  4031. if (this._cachedIndexBuffer !== indexBuffer) {
  4032. this._cachedIndexBuffer = indexBuffer;
  4033. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4034. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4035. }
  4036. };
  4037. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4038. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4039. this._cachedVertexBuffers = vertexBuffers;
  4040. this._cachedEffectForVertexBuffers = effect;
  4041. var attributes = effect.getAttributesNames();
  4042. for (var index = 0; index < attributes.length; index++) {
  4043. var order = effect.getAttributeLocation(index);
  4044. if (order >= 0) {
  4045. var vertexBuffer = vertexBuffers[attributes[index]];
  4046. if (!vertexBuffer) {
  4047. continue;
  4048. }
  4049. var stride = vertexBuffer.getStrideSize();
  4050. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4051. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4052. }
  4053. }
  4054. }
  4055. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4056. this._cachedIndexBuffer = indexBuffer;
  4057. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4058. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4059. }
  4060. };
  4061. Engine.prototype._releaseBuffer = function (buffer) {
  4062. buffer.references--;
  4063. if (buffer.references === 0) {
  4064. this._gl.deleteBuffer(buffer);
  4065. return true;
  4066. }
  4067. return false;
  4068. };
  4069. Engine.prototype.createInstancesBuffer = function (capacity) {
  4070. var buffer = this._gl.createBuffer();
  4071. buffer.capacity = capacity;
  4072. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4073. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4074. return buffer;
  4075. };
  4076. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4077. this._gl.deleteBuffer(buffer);
  4078. };
  4079. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4081. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4082. for (var index = 0; index < 4; index++) {
  4083. var offsetLocation = offsetLocations[index];
  4084. this._gl.enableVertexAttribArray(offsetLocation);
  4085. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4086. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4087. }
  4088. };
  4089. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4090. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4091. for (var index = 0; index < 4; index++) {
  4092. var offsetLocation = offsetLocations[index];
  4093. this._gl.disableVertexAttribArray(offsetLocation);
  4094. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4095. }
  4096. };
  4097. Engine.prototype.applyStates = function () {
  4098. this._depthCullingState.apply(this._gl);
  4099. this._alphaState.apply(this._gl);
  4100. };
  4101. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4102. // Apply states
  4103. this.applyStates();
  4104. this._drawCalls++;
  4105. // Render
  4106. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4107. if (instancesCount) {
  4108. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4109. return;
  4110. }
  4111. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4112. };
  4113. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4114. // Apply states
  4115. this.applyStates();
  4116. this._drawCalls++;
  4117. if (instancesCount) {
  4118. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4119. return;
  4120. }
  4121. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4122. };
  4123. // Shaders
  4124. Engine.prototype._releaseEffect = function (effect) {
  4125. if (this._compiledEffects[effect._key]) {
  4126. delete this._compiledEffects[effect._key];
  4127. if (effect.getProgram()) {
  4128. this._gl.deleteProgram(effect.getProgram());
  4129. }
  4130. }
  4131. };
  4132. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4133. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4134. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4135. var name = vertex + "+" + fragment + "@" + defines;
  4136. if (this._compiledEffects[name]) {
  4137. return this._compiledEffects[name];
  4138. }
  4139. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4140. effect._key = name;
  4141. this._compiledEffects[name] = effect;
  4142. return effect;
  4143. };
  4144. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4145. if (uniformsNames === void 0) { uniformsNames = []; }
  4146. if (samplers === void 0) { samplers = []; }
  4147. if (defines === void 0) { defines = ""; }
  4148. return this.createEffect({
  4149. vertex: "particles",
  4150. fragmentElement: fragmentName
  4151. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4152. };
  4153. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4154. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4155. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4156. var shaderProgram = this._gl.createProgram();
  4157. this._gl.attachShader(shaderProgram, vertexShader);
  4158. this._gl.attachShader(shaderProgram, fragmentShader);
  4159. this._gl.linkProgram(shaderProgram);
  4160. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4161. if (!linked) {
  4162. var error = this._gl.getProgramInfoLog(shaderProgram);
  4163. if (error) {
  4164. throw new Error(error);
  4165. }
  4166. }
  4167. this._gl.deleteShader(vertexShader);
  4168. this._gl.deleteShader(fragmentShader);
  4169. return shaderProgram;
  4170. };
  4171. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4172. var results = [];
  4173. for (var index = 0; index < uniformsNames.length; index++) {
  4174. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4175. }
  4176. return results;
  4177. };
  4178. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4179. var results = [];
  4180. for (var index = 0; index < attributesNames.length; index++) {
  4181. try {
  4182. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4183. }
  4184. catch (e) {
  4185. results.push(-1);
  4186. }
  4187. }
  4188. return results;
  4189. };
  4190. Engine.prototype.enableEffect = function (effect) {
  4191. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4192. if (effect && effect.onBind) {
  4193. effect.onBind(effect);
  4194. }
  4195. return;
  4196. }
  4197. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4198. // Use program
  4199. this._gl.useProgram(effect.getProgram());
  4200. for (var i in this._vertexAttribArrays) {
  4201. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4202. continue;
  4203. }
  4204. this._vertexAttribArrays[i] = false;
  4205. this._gl.disableVertexAttribArray(i);
  4206. }
  4207. var attributesCount = effect.getAttributesCount();
  4208. for (var index = 0; index < attributesCount; index++) {
  4209. // Attributes
  4210. var order = effect.getAttributeLocation(index);
  4211. if (order >= 0) {
  4212. this._vertexAttribArrays[order] = true;
  4213. this._gl.enableVertexAttribArray(order);
  4214. }
  4215. }
  4216. this._currentEffect = effect;
  4217. if (effect.onBind) {
  4218. effect.onBind(effect);
  4219. }
  4220. };
  4221. Engine.prototype.setArray = function (uniform, array) {
  4222. if (!uniform)
  4223. return;
  4224. this._gl.uniform1fv(uniform, array);
  4225. };
  4226. Engine.prototype.setArray2 = function (uniform, array) {
  4227. if (!uniform || array.length % 2 !== 0)
  4228. return;
  4229. this._gl.uniform2fv(uniform, array);
  4230. };
  4231. Engine.prototype.setArray3 = function (uniform, array) {
  4232. if (!uniform || array.length % 3 !== 0)
  4233. return;
  4234. this._gl.uniform3fv(uniform, array);
  4235. };
  4236. Engine.prototype.setArray4 = function (uniform, array) {
  4237. if (!uniform || array.length % 4 !== 0)
  4238. return;
  4239. this._gl.uniform4fv(uniform, array);
  4240. };
  4241. Engine.prototype.setMatrices = function (uniform, matrices) {
  4242. if (!uniform)
  4243. return;
  4244. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4245. };
  4246. Engine.prototype.setMatrix = function (uniform, matrix) {
  4247. if (!uniform)
  4248. return;
  4249. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4250. };
  4251. Engine.prototype.setFloat = function (uniform, value) {
  4252. if (!uniform)
  4253. return;
  4254. this._gl.uniform1f(uniform, value);
  4255. };
  4256. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4257. if (!uniform)
  4258. return;
  4259. this._gl.uniform2f(uniform, x, y);
  4260. };
  4261. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4262. if (!uniform)
  4263. return;
  4264. this._gl.uniform3f(uniform, x, y, z);
  4265. };
  4266. Engine.prototype.setBool = function (uniform, bool) {
  4267. if (!uniform)
  4268. return;
  4269. this._gl.uniform1i(uniform, bool);
  4270. };
  4271. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4272. if (!uniform)
  4273. return;
  4274. this._gl.uniform4f(uniform, x, y, z, w);
  4275. };
  4276. Engine.prototype.setColor3 = function (uniform, color3) {
  4277. if (!uniform)
  4278. return;
  4279. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4280. };
  4281. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4282. if (!uniform)
  4283. return;
  4284. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4285. };
  4286. // States
  4287. Engine.prototype.setState = function (culling, force) {
  4288. // Culling
  4289. if (this._depthCullingState.cull !== culling || force) {
  4290. if (culling) {
  4291. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4292. this._depthCullingState.cull = true;
  4293. }
  4294. else {
  4295. this._depthCullingState.cull = false;
  4296. }
  4297. }
  4298. };
  4299. Engine.prototype.setDepthBuffer = function (enable) {
  4300. this._depthCullingState.depthTest = enable;
  4301. };
  4302. Engine.prototype.getDepthWrite = function () {
  4303. return this._depthCullingState.depthMask;
  4304. };
  4305. Engine.prototype.setDepthWrite = function (enable) {
  4306. this._depthCullingState.depthMask = enable;
  4307. };
  4308. Engine.prototype.setColorWrite = function (enable) {
  4309. this._gl.colorMask(enable, enable, enable, enable);
  4310. };
  4311. Engine.prototype.setAlphaMode = function (mode) {
  4312. switch (mode) {
  4313. case Engine.ALPHA_DISABLE:
  4314. this.setDepthWrite(true);
  4315. this._alphaState.alphaBlend = false;
  4316. break;
  4317. case Engine.ALPHA_COMBINE:
  4318. this.setDepthWrite(false);
  4319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4320. this._alphaState.alphaBlend = true;
  4321. break;
  4322. case Engine.ALPHA_ADD:
  4323. this.setDepthWrite(false);
  4324. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4325. this._alphaState.alphaBlend = true;
  4326. break;
  4327. }
  4328. this._alphaMode = mode;
  4329. };
  4330. Engine.prototype.getAlphaMode = function () {
  4331. return this._alphaMode;
  4332. };
  4333. Engine.prototype.setAlphaTesting = function (enable) {
  4334. this._alphaTest = enable;
  4335. };
  4336. Engine.prototype.getAlphaTesting = function () {
  4337. return this._alphaTest;
  4338. };
  4339. // Textures
  4340. Engine.prototype.wipeCaches = function () {
  4341. this._activeTexturesCache = [];
  4342. this._currentEffect = null;
  4343. this._depthCullingState.reset();
  4344. this._alphaState.reset();
  4345. this._cachedVertexBuffers = null;
  4346. this._cachedIndexBuffer = null;
  4347. this._cachedEffectForVertexBuffers = null;
  4348. };
  4349. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4350. var gl = this._gl;
  4351. gl.bindTexture(gl.TEXTURE_2D, texture);
  4352. var magFilter = gl.NEAREST;
  4353. var minFilter = gl.NEAREST;
  4354. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4355. magFilter = gl.LINEAR;
  4356. minFilter = gl.LINEAR;
  4357. }
  4358. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4359. magFilter = gl.LINEAR;
  4360. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4361. }
  4362. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4364. gl.bindTexture(gl.TEXTURE_2D, null);
  4365. texture.samplingMode = samplingMode;
  4366. };
  4367. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4368. var _this = this;
  4369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4370. if (onLoad === void 0) { onLoad = null; }
  4371. if (onError === void 0) { onError = null; }
  4372. if (buffer === void 0) { buffer = null; }
  4373. var texture = this._gl.createTexture();
  4374. var extension;
  4375. var fromData = false;
  4376. if (url.substr(0, 5) === "data:") {
  4377. fromData = true;
  4378. }
  4379. if (!fromData)
  4380. extension = url.substr(url.length - 4, 4).toLowerCase();
  4381. else {
  4382. var oldUrl = url;
  4383. fromData = oldUrl.split(':');
  4384. url = oldUrl;
  4385. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4386. }
  4387. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4388. var isTGA = (extension === ".tga");
  4389. scene._addPendingData(texture);
  4390. texture.url = url;
  4391. texture.noMipmap = noMipmap;
  4392. texture.references = 1;
  4393. this._loadedTexturesCache.push(texture);
  4394. var onerror = function () {
  4395. scene._removePendingData(texture);
  4396. if (onError) {
  4397. onError();
  4398. }
  4399. };
  4400. if (isTGA) {
  4401. var callback = function (arrayBuffer) {
  4402. var data = new Uint8Array(arrayBuffer);
  4403. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4404. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4405. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4406. if (onLoad) {
  4407. onLoad();
  4408. }
  4409. }, samplingMode);
  4410. };
  4411. if (!(fromData instanceof Array))
  4412. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4413. callback(arrayBuffer);
  4414. }, onerror, scene.database, true);
  4415. else
  4416. callback(buffer);
  4417. }
  4418. else if (isDDS) {
  4419. callback = function (data) {
  4420. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4421. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4422. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4423. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4424. if (onLoad) {
  4425. onLoad();
  4426. }
  4427. }, samplingMode);
  4428. };
  4429. if (!(fromData instanceof Array))
  4430. BABYLON.Tools.LoadFile(url, function (data) {
  4431. callback(data);
  4432. }, onerror, scene.database, true);
  4433. else
  4434. callback(buffer);
  4435. }
  4436. else {
  4437. var onload = function (img) {
  4438. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4439. var isPot = (img.width === potWidth && img.height === potHeight);
  4440. if (!isPot) {
  4441. _this._workingCanvas.width = potWidth;
  4442. _this._workingCanvas.height = potHeight;
  4443. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4444. _this._workingContext.imageSmoothingEnabled = false;
  4445. _this._workingContext.mozImageSmoothingEnabled = false;
  4446. _this._workingContext.oImageSmoothingEnabled = false;
  4447. _this._workingContext.webkitImageSmoothingEnabled = false;
  4448. _this._workingContext.msImageSmoothingEnabled = false;
  4449. }
  4450. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4451. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4452. _this._workingContext.imageSmoothingEnabled = true;
  4453. _this._workingContext.mozImageSmoothingEnabled = true;
  4454. _this._workingContext.oImageSmoothingEnabled = true;
  4455. _this._workingContext.webkitImageSmoothingEnabled = true;
  4456. _this._workingContext.msImageSmoothingEnabled = true;
  4457. }
  4458. }
  4459. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4460. if (onLoad) {
  4461. onLoad();
  4462. }
  4463. }, samplingMode);
  4464. };
  4465. if (!(fromData instanceof Array))
  4466. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4467. else
  4468. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4469. }
  4470. return texture;
  4471. };
  4472. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4473. var texture = this._gl.createTexture();
  4474. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4475. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4476. // Format
  4477. var internalFormat = this._gl.RGBA;
  4478. switch (format) {
  4479. case Engine.TEXTUREFORMAT_ALPHA:
  4480. internalFormat = this._gl.ALPHA;
  4481. break;
  4482. case Engine.TEXTUREFORMAT_LUMINANCE:
  4483. internalFormat = this._gl.LUMINANCE;
  4484. break;
  4485. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4486. internalFormat = this._gl.LUMINANCE_ALPHA;
  4487. break;
  4488. case Engine.TEXTUREFORMAT_RGB:
  4489. internalFormat = this._gl.RGB;
  4490. break;
  4491. case Engine.TEXTUREFORMAT_RGBA:
  4492. internalFormat = this._gl.RGBA;
  4493. break;
  4494. }
  4495. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4496. if (generateMipMaps) {
  4497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4498. }
  4499. // Filters
  4500. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4501. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4503. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4504. this._activeTexturesCache = [];
  4505. texture._baseWidth = width;
  4506. texture._baseHeight = height;
  4507. texture._width = width;
  4508. texture._height = height;
  4509. texture.isReady = true;
  4510. texture.references = 1;
  4511. texture.samplingMode = samplingMode;
  4512. this._loadedTexturesCache.push(texture);
  4513. return texture;
  4514. };
  4515. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4516. var texture = this._gl.createTexture();
  4517. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4518. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4519. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4520. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4521. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4523. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4524. this._activeTexturesCache = [];
  4525. texture._baseWidth = width;
  4526. texture._baseHeight = height;
  4527. texture._width = width;
  4528. texture._height = height;
  4529. texture.isReady = false;
  4530. texture.generateMipMaps = generateMipMaps;
  4531. texture.references = 1;
  4532. texture.samplingMode = samplingMode;
  4533. this._loadedTexturesCache.push(texture);
  4534. return texture;
  4535. };
  4536. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4537. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4538. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4539. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4540. if (texture.generateMipMaps) {
  4541. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4542. }
  4543. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4544. this._activeTexturesCache = [];
  4545. texture.isReady = true;
  4546. };
  4547. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4548. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4549. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4550. // Scale the video if it is a NPOT using the current working canvas
  4551. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4552. if (!texture._workingCanvas) {
  4553. texture._workingCanvas = document.createElement("canvas");
  4554. texture._workingContext = texture._workingCanvas.getContext("2d");
  4555. texture._workingCanvas.width = texture._width;
  4556. texture._workingCanvas.height = texture._height;
  4557. }
  4558. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4559. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4560. }
  4561. else {
  4562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4563. }
  4564. if (texture.generateMipMaps) {
  4565. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4566. }
  4567. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4568. this._activeTexturesCache = [];
  4569. texture.isReady = true;
  4570. };
  4571. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4572. // old version had a "generateMipMaps" arg instead of options.
  4573. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4574. // in the same way, generateDepthBuffer is defaulted to true
  4575. var generateMipMaps = false;
  4576. var generateDepthBuffer = true;
  4577. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4578. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4579. if (options !== undefined) {
  4580. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4581. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4582. type = options.type === undefined ? type : options.type;
  4583. if (options.samplingMode !== undefined) {
  4584. samplingMode = options.samplingMode;
  4585. }
  4586. if (type === Engine.TEXTURETYPE_FLOAT) {
  4587. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4588. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4589. }
  4590. }
  4591. var gl = this._gl;
  4592. var texture = gl.createTexture();
  4593. gl.bindTexture(gl.TEXTURE_2D, texture);
  4594. var width = size.width || size;
  4595. var height = size.height || size;
  4596. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4597. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4598. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4599. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4600. }
  4601. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4602. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4605. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4606. var depthBuffer;
  4607. // Create the depth buffer
  4608. if (generateDepthBuffer) {
  4609. depthBuffer = gl.createRenderbuffer();
  4610. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4611. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4612. }
  4613. // Create the framebuffer
  4614. var framebuffer = gl.createFramebuffer();
  4615. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4616. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4617. if (generateDepthBuffer) {
  4618. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4619. }
  4620. // Unbind
  4621. gl.bindTexture(gl.TEXTURE_2D, null);
  4622. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4623. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4624. texture._framebuffer = framebuffer;
  4625. if (generateDepthBuffer) {
  4626. texture._depthBuffer = depthBuffer;
  4627. }
  4628. texture._width = width;
  4629. texture._height = height;
  4630. texture.isReady = true;
  4631. texture.generateMipMaps = generateMipMaps;
  4632. texture.references = 1;
  4633. texture.samplingMode = samplingMode;
  4634. this._activeTexturesCache = [];
  4635. this._loadedTexturesCache.push(texture);
  4636. return texture;
  4637. };
  4638. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4639. var _this = this;
  4640. var gl = this._gl;
  4641. var texture = gl.createTexture();
  4642. texture.isCube = true;
  4643. texture.url = rootUrl;
  4644. texture.references = 1;
  4645. this._loadedTexturesCache.push(texture);
  4646. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4647. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4648. if (isDDS) {
  4649. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4650. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4651. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4652. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4653. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4654. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4655. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4657. }
  4658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4661. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4662. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4663. _this._activeTexturesCache = [];
  4664. texture._width = info.width;
  4665. texture._height = info.height;
  4666. texture.isReady = true;
  4667. }, null, null, true);
  4668. }
  4669. else {
  4670. cascadeLoad(rootUrl, scene, function (imgs) {
  4671. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4672. var height = width;
  4673. _this._workingCanvas.width = width;
  4674. _this._workingCanvas.height = height;
  4675. var faces = [
  4676. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4677. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4678. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4679. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4680. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4681. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4682. ];
  4683. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4684. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4685. for (var index = 0; index < faces.length; index++) {
  4686. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4687. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4688. }
  4689. if (!noMipmap) {
  4690. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4691. }
  4692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4696. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4697. _this._activeTexturesCache = [];
  4698. texture._width = width;
  4699. texture._height = height;
  4700. texture.isReady = true;
  4701. }, extensions);
  4702. }
  4703. return texture;
  4704. };
  4705. Engine.prototype._releaseTexture = function (texture) {
  4706. var gl = this._gl;
  4707. if (texture._framebuffer) {
  4708. gl.deleteFramebuffer(texture._framebuffer);
  4709. }
  4710. if (texture._depthBuffer) {
  4711. gl.deleteRenderbuffer(texture._depthBuffer);
  4712. }
  4713. gl.deleteTexture(texture);
  4714. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4715. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4716. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4717. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4718. this._activeTexturesCache[channel] = null;
  4719. }
  4720. var index = this._loadedTexturesCache.indexOf(texture);
  4721. if (index !== -1) {
  4722. this._loadedTexturesCache.splice(index, 1);
  4723. }
  4724. };
  4725. Engine.prototype.bindSamplers = function (effect) {
  4726. this._gl.useProgram(effect.getProgram());
  4727. var samplers = effect.getSamplers();
  4728. for (var index = 0; index < samplers.length; index++) {
  4729. var uniform = effect.getUniform(samplers[index]);
  4730. this._gl.uniform1i(uniform, index);
  4731. }
  4732. this._currentEffect = null;
  4733. };
  4734. Engine.prototype._bindTexture = function (channel, texture) {
  4735. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4736. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4737. this._activeTexturesCache[channel] = null;
  4738. };
  4739. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4740. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4741. };
  4742. Engine.prototype.setTexture = function (channel, texture) {
  4743. if (channel < 0) {
  4744. return;
  4745. }
  4746. // Not ready?
  4747. if (!texture || !texture.isReady()) {
  4748. if (this._activeTexturesCache[channel] != null) {
  4749. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4750. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4751. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4752. this._activeTexturesCache[channel] = null;
  4753. }
  4754. return;
  4755. }
  4756. // Video
  4757. if (texture instanceof BABYLON.VideoTexture) {
  4758. if (texture.update()) {
  4759. this._activeTexturesCache[channel] = null;
  4760. }
  4761. }
  4762. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4763. texture.delayLoad();
  4764. return;
  4765. }
  4766. if (this._activeTexturesCache[channel] === texture) {
  4767. return;
  4768. }
  4769. this._activeTexturesCache[channel] = texture;
  4770. var internalTexture = texture.getInternalTexture();
  4771. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4772. if (internalTexture.isCube) {
  4773. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4774. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4775. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4776. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4777. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4778. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4779. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4780. }
  4781. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4782. }
  4783. else {
  4784. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4785. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4786. internalTexture._cachedWrapU = texture.wrapU;
  4787. switch (texture.wrapU) {
  4788. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4790. break;
  4791. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4792. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4793. break;
  4794. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4796. break;
  4797. }
  4798. }
  4799. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4800. internalTexture._cachedWrapV = texture.wrapV;
  4801. switch (texture.wrapV) {
  4802. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4803. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4804. break;
  4805. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4806. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4807. break;
  4808. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4809. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4810. break;
  4811. }
  4812. }
  4813. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4814. }
  4815. };
  4816. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4817. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4818. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4819. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4820. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4821. }
  4822. };
  4823. Engine.prototype.readPixels = function (x, y, width, height) {
  4824. var data = new Uint8Array(height * width * 4);
  4825. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4826. return data;
  4827. };
  4828. // Dispose
  4829. Engine.prototype.dispose = function () {
  4830. this.hideLoadingUI();
  4831. this.stopRenderLoop();
  4832. while (this.scenes.length) {
  4833. this.scenes[0].dispose();
  4834. }
  4835. // Release audio engine
  4836. Engine.audioEngine.dispose();
  4837. for (var name in this._compiledEffects) {
  4838. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4839. }
  4840. for (var i in this._vertexAttribArrays) {
  4841. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4842. continue;
  4843. }
  4844. this._gl.disableVertexAttribArray(i);
  4845. }
  4846. // Events
  4847. window.removeEventListener("blur", this._onBlur);
  4848. window.removeEventListener("focus", this._onFocus);
  4849. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4850. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4851. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4852. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4853. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4854. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4855. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4856. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4857. };
  4858. // Loading screen
  4859. Engine.prototype.displayLoadingUI = function () {
  4860. var _this = this;
  4861. this._loadingDiv = document.createElement("div");
  4862. this._loadingDiv.style.opacity = "0";
  4863. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4864. // Loading text
  4865. this._loadingTextDiv = document.createElement("div");
  4866. this._loadingTextDiv.style.position = "absolute";
  4867. this._loadingTextDiv.style.left = "0";
  4868. this._loadingTextDiv.style.top = "50%";
  4869. this._loadingTextDiv.style.marginTop = "80px";
  4870. this._loadingTextDiv.style.width = "100%";
  4871. this._loadingTextDiv.style.height = "20px";
  4872. this._loadingTextDiv.style.fontFamily = "Arial";
  4873. this._loadingTextDiv.style.fontSize = "14px";
  4874. this._loadingTextDiv.style.color = "white";
  4875. this._loadingTextDiv.style.textAlign = "center";
  4876. this._loadingTextDiv.innerHTML = "Loading";
  4877. this._loadingDiv.appendChild(this._loadingTextDiv);
  4878. // Loading img
  4879. var imgBack = new Image();
  4880. 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==";
  4881. imgBack.style.position = "absolute";
  4882. imgBack.style.left = "50%";
  4883. imgBack.style.top = "50%";
  4884. imgBack.style.marginLeft = "-50px";
  4885. imgBack.style.marginTop = "-50px";
  4886. imgBack.style.transition = "transform 1.0s ease";
  4887. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4888. var deg = 360;
  4889. var onTransitionEnd = function () {
  4890. deg += 360;
  4891. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4892. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4893. };
  4894. imgBack.addEventListener("transitionend", onTransitionEnd);
  4895. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4896. this._loadingDiv.appendChild(imgBack);
  4897. // front image
  4898. var imgFront = new Image();
  4899. 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=";
  4900. imgFront.style.position = "absolute";
  4901. imgFront.style.left = "50%";
  4902. imgFront.style.top = "50%";
  4903. imgFront.style.marginLeft = "-50px";
  4904. imgFront.style.marginTop = "-50px";
  4905. this._loadingDiv.appendChild(imgFront);
  4906. // Resize
  4907. this._resizeLoadingUI = function () {
  4908. var canvasRect = _this.getRenderingCanvasClientRect();
  4909. _this._loadingDiv.style.position = "absolute";
  4910. _this._loadingDiv.style.left = canvasRect.left + "px";
  4911. _this._loadingDiv.style.top = canvasRect.top + "px";
  4912. _this._loadingDiv.style.width = canvasRect.width + "px";
  4913. _this._loadingDiv.style.height = canvasRect.height + "px";
  4914. };
  4915. this._resizeLoadingUI();
  4916. window.addEventListener("resize", this._resizeLoadingUI);
  4917. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4918. document.body.appendChild(this._loadingDiv);
  4919. setTimeout(function () {
  4920. _this._loadingDiv.style.opacity = "1";
  4921. imgBack.style.transform = "rotateZ(360deg)";
  4922. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4923. }, 0);
  4924. };
  4925. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4926. set: function (text) {
  4927. if (!this._loadingDiv) {
  4928. return;
  4929. }
  4930. this._loadingTextDiv.innerHTML = text;
  4931. },
  4932. enumerable: true,
  4933. configurable: true
  4934. });
  4935. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4936. get: function () {
  4937. return this._loadingDivBackgroundColor;
  4938. },
  4939. set: function (color) {
  4940. this._loadingDivBackgroundColor = color;
  4941. if (!this._loadingDiv) {
  4942. return;
  4943. }
  4944. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Engine.prototype.hideLoadingUI = function () {
  4950. var _this = this;
  4951. if (!this._loadingDiv) {
  4952. return;
  4953. }
  4954. var onTransitionEnd = function () {
  4955. if (!_this._loadingDiv) {
  4956. return;
  4957. }
  4958. document.body.removeChild(_this._loadingDiv);
  4959. window.removeEventListener("resize", _this._resizeLoadingUI);
  4960. _this._loadingDiv = null;
  4961. };
  4962. this._loadingDiv.style.opacity = "0";
  4963. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4964. };
  4965. // FPS
  4966. Engine.prototype.getFps = function () {
  4967. return this.fps;
  4968. };
  4969. Engine.prototype.getDeltaTime = function () {
  4970. return this.deltaTime;
  4971. };
  4972. Engine.prototype._measureFps = function () {
  4973. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4974. var length = this.previousFramesDuration.length;
  4975. if (length >= 2) {
  4976. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4977. }
  4978. if (length >= this.fpsRange) {
  4979. if (length > this.fpsRange) {
  4980. this.previousFramesDuration.splice(0, 1);
  4981. length = this.previousFramesDuration.length;
  4982. }
  4983. var sum = 0;
  4984. for (var id = 0; id < length - 1; id++) {
  4985. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4986. }
  4987. this.fps = 1000.0 / (sum / (length - 1));
  4988. }
  4989. };
  4990. // Statics
  4991. Engine.isSupported = function () {
  4992. try {
  4993. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4994. if (navigator.isCocoonJS) {
  4995. return true;
  4996. }
  4997. var tempcanvas = document.createElement("canvas");
  4998. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4999. return gl != null && !!window.WebGLRenderingContext;
  5000. }
  5001. catch (e) {
  5002. return false;
  5003. }
  5004. };
  5005. // Const statics
  5006. Engine._ALPHA_DISABLE = 0;
  5007. Engine._ALPHA_ADD = 1;
  5008. Engine._ALPHA_COMBINE = 2;
  5009. Engine._DELAYLOADSTATE_NONE = 0;
  5010. Engine._DELAYLOADSTATE_LOADED = 1;
  5011. Engine._DELAYLOADSTATE_LOADING = 2;
  5012. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5013. Engine._TEXTUREFORMAT_ALPHA = 0;
  5014. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5015. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5016. Engine._TEXTUREFORMAT_RGB = 4;
  5017. Engine._TEXTUREFORMAT_RGBA = 4;
  5018. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5019. Engine._TEXTURETYPE_FLOAT = 1;
  5020. // Updatable statics so stick with vars here
  5021. Engine.Epsilon = 0.001;
  5022. Engine.CollisionsEpsilon = 0.001;
  5023. Engine.ShadersRepository = "Babylon/Shaders/";
  5024. return Engine;
  5025. })();
  5026. BABYLON.Engine = Engine;
  5027. })(BABYLON || (BABYLON = {}));
  5028. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5029. (function (BABYLON) {
  5030. /**
  5031. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5032. */
  5033. var Node = (function () {
  5034. /**
  5035. * @constructor
  5036. * @param {string} name - the name and id to be given to this node
  5037. * @param {BABYLON.Scene} the scene this node will be added to
  5038. */
  5039. function Node(name, scene) {
  5040. this.state = "";
  5041. this.animations = new Array();
  5042. this._childrenFlag = -1;
  5043. this._isEnabled = true;
  5044. this._isReady = true;
  5045. this._currentRenderId = -1;
  5046. this.name = name;
  5047. this.id = name;
  5048. this._scene = scene;
  5049. this._initCache();
  5050. }
  5051. Node.prototype.getScene = function () {
  5052. return this._scene;
  5053. };
  5054. Node.prototype.getEngine = function () {
  5055. return this._scene.getEngine();
  5056. };
  5057. // override it in derived class
  5058. Node.prototype.getWorldMatrix = function () {
  5059. return BABYLON.Matrix.Identity();
  5060. };
  5061. // override it in derived class if you add new variables to the cache
  5062. // and call the parent class method
  5063. Node.prototype._initCache = function () {
  5064. this._cache = {};
  5065. this._cache.parent = undefined;
  5066. };
  5067. Node.prototype.updateCache = function (force) {
  5068. if (!force && this.isSynchronized())
  5069. return;
  5070. this._cache.parent = this.parent;
  5071. this._updateCache();
  5072. };
  5073. // override it in derived class if you add new variables to the cache
  5074. // and call the parent class method if !ignoreParentClass
  5075. Node.prototype._updateCache = function (ignoreParentClass) {
  5076. };
  5077. // override it in derived class if you add new variables to the cache
  5078. Node.prototype._isSynchronized = function () {
  5079. return true;
  5080. };
  5081. Node.prototype.isSynchronizedWithParent = function () {
  5082. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5083. };
  5084. Node.prototype.isSynchronized = function (updateCache) {
  5085. var check = this.hasNewParent();
  5086. check = check || !this.isSynchronizedWithParent();
  5087. check = check || !this._isSynchronized();
  5088. if (updateCache)
  5089. this.updateCache(true);
  5090. return !check;
  5091. };
  5092. Node.prototype.hasNewParent = function (update) {
  5093. if (this._cache.parent === this.parent)
  5094. return false;
  5095. if (update)
  5096. this._cache.parent = this.parent;
  5097. return true;
  5098. };
  5099. /**
  5100. * Is this node ready to be used/rendered
  5101. * @return {boolean} is it ready
  5102. */
  5103. Node.prototype.isReady = function () {
  5104. return this._isReady;
  5105. };
  5106. /**
  5107. * Is this node enabled.
  5108. * If the node has a parent and is enabled, the parent will be inspected as well.
  5109. * @return {boolean} whether this node (and its parent) is enabled.
  5110. * @see setEnabled
  5111. */
  5112. Node.prototype.isEnabled = function () {
  5113. if (!this._isEnabled) {
  5114. return false;
  5115. }
  5116. if (this.parent) {
  5117. return this.parent.isEnabled();
  5118. }
  5119. return true;
  5120. };
  5121. /**
  5122. * Set the enabled state of this node.
  5123. * @param {boolean} value - the new enabled state
  5124. * @see isEnabled
  5125. */
  5126. Node.prototype.setEnabled = function (value) {
  5127. this._isEnabled = value;
  5128. };
  5129. /**
  5130. * Is this node a descendant of the given node.
  5131. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5132. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5133. * @see parent
  5134. */
  5135. Node.prototype.isDescendantOf = function (ancestor) {
  5136. if (this.parent) {
  5137. if (this.parent === ancestor) {
  5138. return true;
  5139. }
  5140. return this.parent.isDescendantOf(ancestor);
  5141. }
  5142. return false;
  5143. };
  5144. Node.prototype._getDescendants = function (list, results) {
  5145. for (var index = 0; index < list.length; index++) {
  5146. var item = list[index];
  5147. if (item.isDescendantOf(this)) {
  5148. results.push(item);
  5149. }
  5150. }
  5151. };
  5152. /**
  5153. * Will return all nodes that have this node as parent.
  5154. * @return {BABYLON.Node[]} all children nodes of all types.
  5155. */
  5156. Node.prototype.getDescendants = function () {
  5157. var results = [];
  5158. this._getDescendants(this._scene.meshes, results);
  5159. this._getDescendants(this._scene.lights, results);
  5160. this._getDescendants(this._scene.cameras, results);
  5161. return results;
  5162. };
  5163. Node.prototype._setReady = function (state) {
  5164. if (state == this._isReady) {
  5165. return;
  5166. }
  5167. if (!state) {
  5168. this._isReady = false;
  5169. return;
  5170. }
  5171. this._isReady = true;
  5172. if (this.onReady) {
  5173. this.onReady(this);
  5174. }
  5175. };
  5176. return Node;
  5177. })();
  5178. BABYLON.Node = Node;
  5179. })(BABYLON || (BABYLON = {}));
  5180. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5181. (function (BABYLON) {
  5182. var BoundingSphere = (function () {
  5183. function BoundingSphere(minimum, maximum) {
  5184. this.minimum = minimum;
  5185. this.maximum = maximum;
  5186. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5187. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5188. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5189. this.radius = distance * 0.5;
  5190. this.centerWorld = BABYLON.Vector3.Zero();
  5191. this._update(BABYLON.Matrix.Identity());
  5192. }
  5193. // Methods
  5194. BoundingSphere.prototype._update = function (world) {
  5195. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5196. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5197. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5198. };
  5199. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5200. for (var i = 0; i < 6; i++) {
  5201. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5202. return false;
  5203. }
  5204. return true;
  5205. };
  5206. BoundingSphere.prototype.intersectsPoint = function (point) {
  5207. var x = this.centerWorld.x - point.x;
  5208. var y = this.centerWorld.y - point.y;
  5209. var z = this.centerWorld.z - point.z;
  5210. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5211. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5212. return false;
  5213. return true;
  5214. };
  5215. // Statics
  5216. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5217. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5218. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5219. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5220. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5221. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5222. return false;
  5223. return true;
  5224. };
  5225. return BoundingSphere;
  5226. })();
  5227. BABYLON.BoundingSphere = BoundingSphere;
  5228. })(BABYLON || (BABYLON = {}));
  5229. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5230. (function (BABYLON) {
  5231. var BoundingBox = (function () {
  5232. function BoundingBox(minimum, maximum) {
  5233. this.minimum = minimum;
  5234. this.maximum = maximum;
  5235. this.vectors = new Array();
  5236. this.vectorsWorld = new Array();
  5237. // Bounding vectors
  5238. this.vectors.push(this.minimum.clone());
  5239. this.vectors.push(this.maximum.clone());
  5240. this.vectors.push(this.minimum.clone());
  5241. this.vectors[2].x = this.maximum.x;
  5242. this.vectors.push(this.minimum.clone());
  5243. this.vectors[3].y = this.maximum.y;
  5244. this.vectors.push(this.minimum.clone());
  5245. this.vectors[4].z = this.maximum.z;
  5246. this.vectors.push(this.maximum.clone());
  5247. this.vectors[5].z = this.minimum.z;
  5248. this.vectors.push(this.maximum.clone());
  5249. this.vectors[6].x = this.minimum.x;
  5250. this.vectors.push(this.maximum.clone());
  5251. this.vectors[7].y = this.minimum.y;
  5252. // OBB
  5253. this.center = this.maximum.add(this.minimum).scale(0.5);
  5254. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5255. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5256. for (var index = 0; index < this.vectors.length; index++) {
  5257. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5258. }
  5259. this.minimumWorld = BABYLON.Vector3.Zero();
  5260. this.maximumWorld = BABYLON.Vector3.Zero();
  5261. this._update(BABYLON.Matrix.Identity());
  5262. }
  5263. // Methods
  5264. BoundingBox.prototype.getWorldMatrix = function () {
  5265. return this._worldMatrix;
  5266. };
  5267. BoundingBox.prototype._update = function (world) {
  5268. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5269. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5270. for (var index = 0; index < this.vectors.length; index++) {
  5271. var v = this.vectorsWorld[index];
  5272. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5273. if (v.x < this.minimumWorld.x)
  5274. this.minimumWorld.x = v.x;
  5275. if (v.y < this.minimumWorld.y)
  5276. this.minimumWorld.y = v.y;
  5277. if (v.z < this.minimumWorld.z)
  5278. this.minimumWorld.z = v.z;
  5279. if (v.x > this.maximumWorld.x)
  5280. this.maximumWorld.x = v.x;
  5281. if (v.y > this.maximumWorld.y)
  5282. this.maximumWorld.y = v.y;
  5283. if (v.z > this.maximumWorld.z)
  5284. this.maximumWorld.z = v.z;
  5285. }
  5286. // OBB
  5287. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5288. this.center.scaleInPlace(0.5);
  5289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5290. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5291. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5292. this._worldMatrix = world;
  5293. };
  5294. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5295. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5296. };
  5297. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5298. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5299. };
  5300. BoundingBox.prototype.intersectsPoint = function (point) {
  5301. var delta = BABYLON.Engine.Epsilon;
  5302. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5303. return false;
  5304. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5305. return false;
  5306. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5307. return false;
  5308. return true;
  5309. };
  5310. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5311. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5312. };
  5313. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5314. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5315. return false;
  5316. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5317. return false;
  5318. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5319. return false;
  5320. return true;
  5321. };
  5322. // Statics
  5323. BoundingBox.Intersects = function (box0, box1) {
  5324. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5325. return false;
  5326. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5327. return false;
  5328. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5329. return false;
  5330. return true;
  5331. };
  5332. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5333. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5334. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5335. return (num <= (sphereRadius * sphereRadius));
  5336. };
  5337. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5338. for (var p = 0; p < 6; p++) {
  5339. for (var i = 0; i < 8; i++) {
  5340. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5341. return false;
  5342. }
  5343. }
  5344. }
  5345. return true;
  5346. };
  5347. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5348. for (var p = 0; p < 6; p++) {
  5349. var inCount = 8;
  5350. for (var i = 0; i < 8; i++) {
  5351. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5352. --inCount;
  5353. }
  5354. else {
  5355. break;
  5356. }
  5357. }
  5358. if (inCount == 0)
  5359. return false;
  5360. }
  5361. return true;
  5362. };
  5363. return BoundingBox;
  5364. })();
  5365. BABYLON.BoundingBox = BoundingBox;
  5366. })(BABYLON || (BABYLON = {}));
  5367. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5368. (function (BABYLON) {
  5369. var computeBoxExtents = function (axis, box) {
  5370. var p = BABYLON.Vector3.Dot(box.center, axis);
  5371. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5372. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5373. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5374. var r = r0 + r1 + r2;
  5375. return {
  5376. min: p - r,
  5377. max: p + r
  5378. };
  5379. };
  5380. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5381. var axisOverlap = function (axis, box0, box1) {
  5382. var result0 = computeBoxExtents(axis, box0);
  5383. var result1 = computeBoxExtents(axis, box1);
  5384. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5385. };
  5386. var BoundingInfo = (function () {
  5387. function BoundingInfo(minimum, maximum) {
  5388. this.minimum = minimum;
  5389. this.maximum = maximum;
  5390. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5391. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5392. }
  5393. // Methods
  5394. BoundingInfo.prototype._update = function (world) {
  5395. this.boundingBox._update(world);
  5396. this.boundingSphere._update(world);
  5397. };
  5398. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5399. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5400. return false;
  5401. return this.boundingBox.isInFrustum(frustumPlanes);
  5402. };
  5403. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5404. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5405. };
  5406. BoundingInfo.prototype._checkCollision = function (collider) {
  5407. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5408. };
  5409. BoundingInfo.prototype.intersectsPoint = function (point) {
  5410. if (!this.boundingSphere.centerWorld) {
  5411. return false;
  5412. }
  5413. if (!this.boundingSphere.intersectsPoint(point)) {
  5414. return false;
  5415. }
  5416. if (!this.boundingBox.intersectsPoint(point)) {
  5417. return false;
  5418. }
  5419. return true;
  5420. };
  5421. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5422. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5423. return false;
  5424. }
  5425. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5426. return false;
  5427. }
  5428. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5429. return false;
  5430. }
  5431. if (!precise) {
  5432. return true;
  5433. }
  5434. var box0 = this.boundingBox;
  5435. var box1 = boundingInfo.boundingBox;
  5436. if (!axisOverlap(box0.directions[0], box0, box1))
  5437. return false;
  5438. if (!axisOverlap(box0.directions[1], box0, box1))
  5439. return false;
  5440. if (!axisOverlap(box0.directions[2], box0, box1))
  5441. return false;
  5442. if (!axisOverlap(box1.directions[0], box0, box1))
  5443. return false;
  5444. if (!axisOverlap(box1.directions[1], box0, box1))
  5445. return false;
  5446. if (!axisOverlap(box1.directions[2], box0, box1))
  5447. return false;
  5448. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5449. return false;
  5450. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5451. return false;
  5452. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5453. return false;
  5454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5455. return false;
  5456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5457. return false;
  5458. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5459. return false;
  5460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5461. return false;
  5462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5463. return false;
  5464. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5465. return false;
  5466. return true;
  5467. };
  5468. return BoundingInfo;
  5469. })();
  5470. BABYLON.BoundingInfo = BoundingInfo;
  5471. })(BABYLON || (BABYLON = {}));
  5472. //# sourceMappingURL=babylon.boundingInfo.js.map
  5473. var BABYLON;
  5474. (function (BABYLON) {
  5475. var Light = (function (_super) {
  5476. __extends(Light, _super);
  5477. function Light(name, scene) {
  5478. _super.call(this, name, scene);
  5479. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5480. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5481. this.intensity = 1.0;
  5482. this.range = Number.MAX_VALUE;
  5483. this.includedOnlyMeshes = new Array();
  5484. this.excludedMeshes = new Array();
  5485. this._excludedMeshesIds = new Array();
  5486. this._includedOnlyMeshesIds = new Array();
  5487. scene.lights.push(this);
  5488. }
  5489. Light.prototype.getShadowGenerator = function () {
  5490. return this._shadowGenerator;
  5491. };
  5492. Light.prototype.getAbsolutePosition = function () {
  5493. return BABYLON.Vector3.Zero();
  5494. };
  5495. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5496. };
  5497. Light.prototype._getWorldMatrix = function () {
  5498. return BABYLON.Matrix.Identity();
  5499. };
  5500. Light.prototype.canAffectMesh = function (mesh) {
  5501. if (!mesh) {
  5502. return true;
  5503. }
  5504. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5505. return false;
  5506. }
  5507. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5508. return false;
  5509. }
  5510. return true;
  5511. };
  5512. Light.prototype.getWorldMatrix = function () {
  5513. this._currentRenderId = this.getScene().getRenderId();
  5514. var worldMatrix = this._getWorldMatrix();
  5515. if (this.parent && this.parent.getWorldMatrix) {
  5516. if (!this._parentedWorldMatrix) {
  5517. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5518. }
  5519. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5520. return this._parentedWorldMatrix;
  5521. }
  5522. return worldMatrix;
  5523. };
  5524. Light.prototype.dispose = function () {
  5525. if (this._shadowGenerator) {
  5526. this._shadowGenerator.dispose();
  5527. this._shadowGenerator = null;
  5528. }
  5529. // Remove from scene
  5530. var index = this.getScene().lights.indexOf(this);
  5531. this.getScene().lights.splice(index, 1);
  5532. };
  5533. return Light;
  5534. })(BABYLON.Node);
  5535. BABYLON.Light = Light;
  5536. })(BABYLON || (BABYLON = {}));
  5537. //# sourceMappingURL=babylon.light.js.map
  5538. var BABYLON;
  5539. (function (BABYLON) {
  5540. var PointLight = (function (_super) {
  5541. __extends(PointLight, _super);
  5542. function PointLight(name, position, scene) {
  5543. _super.call(this, name, scene);
  5544. this.position = position;
  5545. }
  5546. PointLight.prototype.getAbsolutePosition = function () {
  5547. return this._transformedPosition ? this._transformedPosition : this.position;
  5548. };
  5549. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5550. if (this.parent && this.parent.getWorldMatrix) {
  5551. if (!this._transformedPosition) {
  5552. this._transformedPosition = BABYLON.Vector3.Zero();
  5553. }
  5554. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5555. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5556. return;
  5557. }
  5558. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5559. };
  5560. PointLight.prototype.getShadowGenerator = function () {
  5561. return null;
  5562. };
  5563. PointLight.prototype._getWorldMatrix = function () {
  5564. if (!this._worldMatrix) {
  5565. this._worldMatrix = BABYLON.Matrix.Identity();
  5566. }
  5567. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5568. return this._worldMatrix;
  5569. };
  5570. return PointLight;
  5571. })(BABYLON.Light);
  5572. BABYLON.PointLight = PointLight;
  5573. })(BABYLON || (BABYLON = {}));
  5574. //# sourceMappingURL=babylon.pointLight.js.map
  5575. var BABYLON;
  5576. (function (BABYLON) {
  5577. var SpotLight = (function (_super) {
  5578. __extends(SpotLight, _super);
  5579. function SpotLight(name, position, direction, angle, exponent, scene) {
  5580. _super.call(this, name, scene);
  5581. this.position = position;
  5582. this.direction = direction;
  5583. this.angle = angle;
  5584. this.exponent = exponent;
  5585. }
  5586. SpotLight.prototype.getAbsolutePosition = function () {
  5587. return this.transformedPosition ? this.transformedPosition : this.position;
  5588. };
  5589. SpotLight.prototype.setDirectionToTarget = function (target) {
  5590. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5591. return this.direction;
  5592. };
  5593. SpotLight.prototype.computeTransformedPosition = function () {
  5594. if (this.parent && this.parent.getWorldMatrix) {
  5595. if (!this.transformedPosition) {
  5596. this.transformedPosition = BABYLON.Vector3.Zero();
  5597. }
  5598. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5599. return true;
  5600. }
  5601. return false;
  5602. };
  5603. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5604. var normalizeDirection;
  5605. if (this.parent && this.parent.getWorldMatrix) {
  5606. if (!this._transformedDirection) {
  5607. this._transformedDirection = BABYLON.Vector3.Zero();
  5608. }
  5609. this.computeTransformedPosition();
  5610. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5611. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5612. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5613. }
  5614. else {
  5615. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5616. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5617. }
  5618. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5619. };
  5620. SpotLight.prototype._getWorldMatrix = function () {
  5621. if (!this._worldMatrix) {
  5622. this._worldMatrix = BABYLON.Matrix.Identity();
  5623. }
  5624. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5625. return this._worldMatrix;
  5626. };
  5627. return SpotLight;
  5628. })(BABYLON.Light);
  5629. BABYLON.SpotLight = SpotLight;
  5630. })(BABYLON || (BABYLON = {}));
  5631. //# sourceMappingURL=babylon.spotLight.js.map
  5632. var BABYLON;
  5633. (function (BABYLON) {
  5634. var DirectionalLight = (function (_super) {
  5635. __extends(DirectionalLight, _super);
  5636. function DirectionalLight(name, direction, scene) {
  5637. _super.call(this, name, scene);
  5638. this.direction = direction;
  5639. this.position = direction.scale(-1);
  5640. }
  5641. DirectionalLight.prototype.getAbsolutePosition = function () {
  5642. return this.transformedPosition ? this.transformedPosition : this.position;
  5643. };
  5644. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5645. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5646. return this.direction;
  5647. };
  5648. DirectionalLight.prototype.computeTransformedPosition = function () {
  5649. if (this.parent && this.parent.getWorldMatrix) {
  5650. if (!this.transformedPosition) {
  5651. this.transformedPosition = BABYLON.Vector3.Zero();
  5652. }
  5653. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5654. return true;
  5655. }
  5656. return false;
  5657. };
  5658. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5659. if (this.parent && this.parent.getWorldMatrix) {
  5660. if (!this._transformedDirection) {
  5661. this._transformedDirection = BABYLON.Vector3.Zero();
  5662. }
  5663. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5664. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5665. return;
  5666. }
  5667. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5668. };
  5669. DirectionalLight.prototype._getWorldMatrix = function () {
  5670. if (!this._worldMatrix) {
  5671. this._worldMatrix = BABYLON.Matrix.Identity();
  5672. }
  5673. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5674. return this._worldMatrix;
  5675. };
  5676. return DirectionalLight;
  5677. })(BABYLON.Light);
  5678. BABYLON.DirectionalLight = DirectionalLight;
  5679. })(BABYLON || (BABYLON = {}));
  5680. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5681. (function (BABYLON) {
  5682. var ShadowGenerator = (function () {
  5683. function ShadowGenerator(mapSize, light) {
  5684. var _this = this;
  5685. // Members
  5686. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5687. this._darkness = 0;
  5688. this._transparencyShadow = false;
  5689. this._viewMatrix = BABYLON.Matrix.Zero();
  5690. this._projectionMatrix = BABYLON.Matrix.Zero();
  5691. this._transformMatrix = BABYLON.Matrix.Zero();
  5692. this._worldViewProjection = BABYLON.Matrix.Zero();
  5693. this._light = light;
  5694. this._scene = light.getScene();
  5695. light._shadowGenerator = this;
  5696. // Render target
  5697. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5698. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5699. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5700. this._shadowMap.renderParticles = false;
  5701. // Custom render function
  5702. var renderSubMesh = function (subMesh) {
  5703. var mesh = subMesh.getRenderingMesh();
  5704. var scene = _this._scene;
  5705. var engine = scene.getEngine();
  5706. // Culling
  5707. engine.setState(subMesh.getMaterial().backFaceCulling);
  5708. // Managing instances
  5709. var batch = mesh._getInstancesRenderList(subMesh._id);
  5710. if (batch.mustReturn) {
  5711. return;
  5712. }
  5713. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5714. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5715. engine.enableEffect(_this._effect);
  5716. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5717. var material = subMesh.getMaterial();
  5718. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5719. // Alpha test
  5720. if (material && material.needAlphaTesting()) {
  5721. var alphaTexture = material.getAlphaTestTexture();
  5722. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5723. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5724. }
  5725. // Bones
  5726. if (mesh.useBones) {
  5727. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5728. }
  5729. // Draw
  5730. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5731. }
  5732. else {
  5733. // Need to reset refresh rate of the shadowMap
  5734. _this._shadowMap.resetRefreshCounter();
  5735. }
  5736. };
  5737. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5738. var index;
  5739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5740. renderSubMesh(opaqueSubMeshes.data[index]);
  5741. }
  5742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5743. renderSubMesh(alphaTestSubMeshes.data[index]);
  5744. }
  5745. if (_this._transparencyShadow) {
  5746. for (index = 0; index < transparentSubMeshes.length; index++) {
  5747. renderSubMesh(transparentSubMeshes.data[index]);
  5748. }
  5749. }
  5750. };
  5751. }
  5752. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5753. // Static
  5754. get: function () {
  5755. return ShadowGenerator._FILTER_NONE;
  5756. },
  5757. enumerable: true,
  5758. configurable: true
  5759. });
  5760. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5761. get: function () {
  5762. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5768. get: function () {
  5769. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5770. },
  5771. enumerable: true,
  5772. configurable: true
  5773. });
  5774. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5775. get: function () {
  5776. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5777. },
  5778. set: function (value) {
  5779. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5780. },
  5781. enumerable: true,
  5782. configurable: true
  5783. });
  5784. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5785. get: function () {
  5786. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5787. },
  5788. set: function (value) {
  5789. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5790. },
  5791. enumerable: true,
  5792. configurable: true
  5793. });
  5794. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5795. var defines = [];
  5796. if (this.useVarianceShadowMap) {
  5797. defines.push("#define VSM");
  5798. }
  5799. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5800. var mesh = subMesh.getMesh();
  5801. var material = subMesh.getMaterial();
  5802. // Alpha test
  5803. if (material && material.needAlphaTesting()) {
  5804. defines.push("#define ALPHATEST");
  5805. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5806. attribs.push(BABYLON.VertexBuffer.UVKind);
  5807. defines.push("#define UV1");
  5808. }
  5809. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5810. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5811. defines.push("#define UV2");
  5812. }
  5813. }
  5814. // Bones
  5815. if (mesh.useBones) {
  5816. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5817. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5818. defines.push("#define BONES");
  5819. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5820. }
  5821. // Instances
  5822. if (useInstances) {
  5823. defines.push("#define INSTANCES");
  5824. attribs.push("world0");
  5825. attribs.push("world1");
  5826. attribs.push("world2");
  5827. attribs.push("world3");
  5828. }
  5829. // Get correct effect
  5830. var join = defines.join("\n");
  5831. if (this._cachedDefines !== join) {
  5832. this._cachedDefines = join;
  5833. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5834. }
  5835. return this._effect.isReady();
  5836. };
  5837. ShadowGenerator.prototype.getShadowMap = function () {
  5838. return this._shadowMap;
  5839. };
  5840. ShadowGenerator.prototype.getLight = function () {
  5841. return this._light;
  5842. };
  5843. // Methods
  5844. ShadowGenerator.prototype.getTransformMatrix = function () {
  5845. var lightPosition = this._light.position;
  5846. var lightDirection = this._light.direction;
  5847. if (this._light.computeTransformedPosition()) {
  5848. lightPosition = this._light.transformedPosition;
  5849. }
  5850. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5851. this._cachedPosition = lightPosition.clone();
  5852. this._cachedDirection = lightDirection.clone();
  5853. var activeCamera = this._scene.activeCamera;
  5854. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5855. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5856. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5857. }
  5858. return this._transformMatrix;
  5859. };
  5860. ShadowGenerator.prototype.getDarkness = function () {
  5861. return this._darkness;
  5862. };
  5863. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5864. if (darkness >= 1.0)
  5865. this._darkness = 1.0;
  5866. else if (darkness <= 0.0)
  5867. this._darkness = 0.0;
  5868. else
  5869. this._darkness = darkness;
  5870. };
  5871. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5872. this._transparencyShadow = hasShadow;
  5873. };
  5874. ShadowGenerator.prototype.dispose = function () {
  5875. this._shadowMap.dispose();
  5876. };
  5877. ShadowGenerator._FILTER_NONE = 0;
  5878. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5879. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5880. return ShadowGenerator;
  5881. })();
  5882. BABYLON.ShadowGenerator = ShadowGenerator;
  5883. })(BABYLON || (BABYLON = {}));
  5884. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5885. var BABYLON;
  5886. (function (BABYLON) {
  5887. var HemisphericLight = (function (_super) {
  5888. __extends(HemisphericLight, _super);
  5889. function HemisphericLight(name, direction, scene) {
  5890. _super.call(this, name, scene);
  5891. this.direction = direction;
  5892. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5893. }
  5894. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5895. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5896. return this.direction;
  5897. };
  5898. HemisphericLight.prototype.getShadowGenerator = function () {
  5899. return null;
  5900. };
  5901. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5902. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5903. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5904. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5905. };
  5906. HemisphericLight.prototype._getWorldMatrix = function () {
  5907. if (!this._worldMatrix) {
  5908. this._worldMatrix = BABYLON.Matrix.Identity();
  5909. }
  5910. return this._worldMatrix;
  5911. };
  5912. return HemisphericLight;
  5913. })(BABYLON.Light);
  5914. BABYLON.HemisphericLight = HemisphericLight;
  5915. })(BABYLON || (BABYLON = {}));
  5916. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5917. (function (BABYLON) {
  5918. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5919. if (boxMin.x > sphereCenter.x + sphereRadius)
  5920. return false;
  5921. if (sphereCenter.x - sphereRadius > boxMax.x)
  5922. return false;
  5923. if (boxMin.y > sphereCenter.y + sphereRadius)
  5924. return false;
  5925. if (sphereCenter.y - sphereRadius > boxMax.y)
  5926. return false;
  5927. if (boxMin.z > sphereCenter.z + sphereRadius)
  5928. return false;
  5929. if (sphereCenter.z - sphereRadius > boxMax.z)
  5930. return false;
  5931. return true;
  5932. };
  5933. var getLowestRoot = function (a, b, c, maxR) {
  5934. var determinant = b * b - 4.0 * a * c;
  5935. var result = { root: 0, found: false };
  5936. if (determinant < 0)
  5937. return result;
  5938. var sqrtD = Math.sqrt(determinant);
  5939. var r1 = (-b - sqrtD) / (2.0 * a);
  5940. var r2 = (-b + sqrtD) / (2.0 * a);
  5941. if (r1 > r2) {
  5942. var temp = r2;
  5943. r2 = r1;
  5944. r1 = temp;
  5945. }
  5946. if (r1 > 0 && r1 < maxR) {
  5947. result.root = r1;
  5948. result.found = true;
  5949. return result;
  5950. }
  5951. if (r2 > 0 && r2 < maxR) {
  5952. result.root = r2;
  5953. result.found = true;
  5954. return result;
  5955. }
  5956. return result;
  5957. };
  5958. var Collider = (function () {
  5959. function Collider() {
  5960. this.radius = new BABYLON.Vector3(1, 1, 1);
  5961. this.retry = 0;
  5962. this.basePointWorld = BABYLON.Vector3.Zero();
  5963. this.velocityWorld = BABYLON.Vector3.Zero();
  5964. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5965. this._collisionPoint = BABYLON.Vector3.Zero();
  5966. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5967. this._tempVector = BABYLON.Vector3.Zero();
  5968. this._tempVector2 = BABYLON.Vector3.Zero();
  5969. this._tempVector3 = BABYLON.Vector3.Zero();
  5970. this._tempVector4 = BABYLON.Vector3.Zero();
  5971. this._edge = BABYLON.Vector3.Zero();
  5972. this._baseToVertex = BABYLON.Vector3.Zero();
  5973. this._destinationPoint = BABYLON.Vector3.Zero();
  5974. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5975. this._displacementVector = BABYLON.Vector3.Zero();
  5976. }
  5977. // Methods
  5978. Collider.prototype._initialize = function (source, dir, e) {
  5979. this.velocity = dir;
  5980. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5981. this.basePoint = source;
  5982. source.multiplyToRef(this.radius, this.basePointWorld);
  5983. dir.multiplyToRef(this.radius, this.velocityWorld);
  5984. this.velocityWorldLength = this.velocityWorld.length();
  5985. this.epsilon = e;
  5986. this.collisionFound = false;
  5987. };
  5988. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5989. pa.subtractToRef(point, this._tempVector);
  5990. pb.subtractToRef(point, this._tempVector2);
  5991. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5992. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5993. if (d < 0)
  5994. return false;
  5995. pc.subtractToRef(point, this._tempVector3);
  5996. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5997. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5998. if (d < 0)
  5999. return false;
  6000. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6001. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6002. return d >= 0;
  6003. };
  6004. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6005. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6006. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6007. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6008. return false;
  6009. }
  6010. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6011. return false;
  6012. return true;
  6013. };
  6014. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6015. var t0;
  6016. var embeddedInPlane = false;
  6017. if (!subMesh._trianglePlanes) {
  6018. subMesh._trianglePlanes = [];
  6019. }
  6020. if (!subMesh._trianglePlanes[faceIndex]) {
  6021. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6022. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6023. }
  6024. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6025. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6026. return;
  6027. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6028. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6029. if (normalDotVelocity == 0) {
  6030. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6031. return;
  6032. embeddedInPlane = true;
  6033. t0 = 0;
  6034. }
  6035. else {
  6036. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6037. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6038. if (t0 > t1) {
  6039. var temp = t1;
  6040. t1 = t0;
  6041. t0 = temp;
  6042. }
  6043. if (t0 > 1.0 || t1 < 0.0)
  6044. return;
  6045. if (t0 < 0)
  6046. t0 = 0;
  6047. if (t0 > 1.0)
  6048. t0 = 1.0;
  6049. }
  6050. this._collisionPoint.copyFromFloats(0, 0, 0);
  6051. var found = false;
  6052. var t = 1.0;
  6053. if (!embeddedInPlane) {
  6054. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6055. this.velocity.scaleToRef(t0, this._tempVector);
  6056. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6057. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6058. found = true;
  6059. t = t0;
  6060. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6061. }
  6062. }
  6063. if (!found) {
  6064. var velocitySquaredLength = this.velocity.lengthSquared();
  6065. var a = velocitySquaredLength;
  6066. this.basePoint.subtractToRef(p1, this._tempVector);
  6067. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6068. var c = this._tempVector.lengthSquared() - 1.0;
  6069. var lowestRoot = getLowestRoot(a, b, c, t);
  6070. if (lowestRoot.found) {
  6071. t = lowestRoot.root;
  6072. found = true;
  6073. this._collisionPoint.copyFrom(p1);
  6074. }
  6075. this.basePoint.subtractToRef(p2, this._tempVector);
  6076. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6077. c = this._tempVector.lengthSquared() - 1.0;
  6078. lowestRoot = getLowestRoot(a, b, c, t);
  6079. if (lowestRoot.found) {
  6080. t = lowestRoot.root;
  6081. found = true;
  6082. this._collisionPoint.copyFrom(p2);
  6083. }
  6084. this.basePoint.subtractToRef(p3, this._tempVector);
  6085. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6086. c = this._tempVector.lengthSquared() - 1.0;
  6087. lowestRoot = getLowestRoot(a, b, c, t);
  6088. if (lowestRoot.found) {
  6089. t = lowestRoot.root;
  6090. found = true;
  6091. this._collisionPoint.copyFrom(p3);
  6092. }
  6093. p2.subtractToRef(p1, this._edge);
  6094. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6095. var edgeSquaredLength = this._edge.lengthSquared();
  6096. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6097. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6098. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6099. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6100. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6101. lowestRoot = getLowestRoot(a, b, c, t);
  6102. if (lowestRoot.found) {
  6103. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6104. if (f >= 0.0 && f <= 1.0) {
  6105. t = lowestRoot.root;
  6106. found = true;
  6107. this._edge.scaleInPlace(f);
  6108. p1.addToRef(this._edge, this._collisionPoint);
  6109. }
  6110. }
  6111. p3.subtractToRef(p2, this._edge);
  6112. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6113. edgeSquaredLength = this._edge.lengthSquared();
  6114. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6115. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6116. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6117. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6118. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6119. lowestRoot = getLowestRoot(a, b, c, t);
  6120. if (lowestRoot.found) {
  6121. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6122. if (f >= 0.0 && f <= 1.0) {
  6123. t = lowestRoot.root;
  6124. found = true;
  6125. this._edge.scaleInPlace(f);
  6126. p2.addToRef(this._edge, this._collisionPoint);
  6127. }
  6128. }
  6129. p1.subtractToRef(p3, this._edge);
  6130. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6131. edgeSquaredLength = this._edge.lengthSquared();
  6132. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6133. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6134. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6135. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6136. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6137. lowestRoot = getLowestRoot(a, b, c, t);
  6138. if (lowestRoot.found) {
  6139. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6140. if (f >= 0.0 && f <= 1.0) {
  6141. t = lowestRoot.root;
  6142. found = true;
  6143. this._edge.scaleInPlace(f);
  6144. p3.addToRef(this._edge, this._collisionPoint);
  6145. }
  6146. }
  6147. }
  6148. if (found) {
  6149. var distToCollision = t * this.velocity.length();
  6150. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6151. if (!this.intersectionPoint) {
  6152. this.intersectionPoint = this._collisionPoint.clone();
  6153. }
  6154. else {
  6155. this.intersectionPoint.copyFrom(this._collisionPoint);
  6156. }
  6157. this.nearestDistance = distToCollision;
  6158. this.collisionFound = true;
  6159. this.collidedMesh = subMesh.getMesh();
  6160. }
  6161. }
  6162. };
  6163. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6164. for (var i = indexStart; i < indexEnd; i += 3) {
  6165. var p1 = pts[indices[i] - decal];
  6166. var p2 = pts[indices[i + 1] - decal];
  6167. var p3 = pts[indices[i + 2] - decal];
  6168. this._testTriangle(i, subMesh, p3, p2, p1);
  6169. }
  6170. };
  6171. Collider.prototype._getResponse = function (pos, vel) {
  6172. pos.addToRef(vel, this._destinationPoint);
  6173. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6174. this.basePoint.addToRef(vel, pos);
  6175. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6176. this._slidePlaneNormal.normalize();
  6177. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6178. pos.addInPlace(this._displacementVector);
  6179. this.intersectionPoint.addInPlace(this._displacementVector);
  6180. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6181. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6182. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6183. };
  6184. return Collider;
  6185. })();
  6186. BABYLON.Collider = Collider;
  6187. })(BABYLON || (BABYLON = {}));
  6188. //# sourceMappingURL=babylon.collider.js.map
  6189. var BABYLON;
  6190. (function (BABYLON) {
  6191. var Camera = (function (_super) {
  6192. __extends(Camera, _super);
  6193. function Camera(name, position, scene) {
  6194. _super.call(this, name, scene);
  6195. this.position = position;
  6196. // Members
  6197. this.upVector = BABYLON.Vector3.Up();
  6198. this.orthoLeft = null;
  6199. this.orthoRight = null;
  6200. this.orthoBottom = null;
  6201. this.orthoTop = null;
  6202. this.fov = 0.8;
  6203. this.minZ = 1.0;
  6204. this.maxZ = 10000.0;
  6205. this.inertia = 0.9;
  6206. this.mode = Camera.PERSPECTIVE_CAMERA;
  6207. this.isIntermediate = false;
  6208. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6209. this.subCameras = [];
  6210. this.layerMask = 0xFFFFFFFF;
  6211. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6212. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6213. this._projectionMatrix = new BABYLON.Matrix();
  6214. this._postProcesses = new Array();
  6215. this._postProcessesTakenIndices = [];
  6216. scene.cameras.push(this);
  6217. if (!scene.activeCamera) {
  6218. scene.activeCamera = this;
  6219. }
  6220. }
  6221. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6222. get: function () {
  6223. return Camera._PERSPECTIVE_CAMERA;
  6224. },
  6225. enumerable: true,
  6226. configurable: true
  6227. });
  6228. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6229. get: function () {
  6230. return Camera._ORTHOGRAPHIC_CAMERA;
  6231. },
  6232. enumerable: true,
  6233. configurable: true
  6234. });
  6235. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6236. get: function () {
  6237. return Camera._FOVMODE_VERTICAL_FIXED;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6243. get: function () {
  6244. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6245. },
  6246. enumerable: true,
  6247. configurable: true
  6248. });
  6249. //Cache
  6250. Camera.prototype._initCache = function () {
  6251. _super.prototype._initCache.call(this);
  6252. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6253. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6254. this._cache.mode = undefined;
  6255. this._cache.minZ = undefined;
  6256. this._cache.maxZ = undefined;
  6257. this._cache.fov = undefined;
  6258. this._cache.aspectRatio = undefined;
  6259. this._cache.orthoLeft = undefined;
  6260. this._cache.orthoRight = undefined;
  6261. this._cache.orthoBottom = undefined;
  6262. this._cache.orthoTop = undefined;
  6263. this._cache.renderWidth = undefined;
  6264. this._cache.renderHeight = undefined;
  6265. };
  6266. Camera.prototype._updateCache = function (ignoreParentClass) {
  6267. if (!ignoreParentClass) {
  6268. _super.prototype._updateCache.call(this);
  6269. }
  6270. var engine = this.getEngine();
  6271. this._cache.position.copyFrom(this.position);
  6272. this._cache.upVector.copyFrom(this.upVector);
  6273. this._cache.mode = this.mode;
  6274. this._cache.minZ = this.minZ;
  6275. this._cache.maxZ = this.maxZ;
  6276. this._cache.fov = this.fov;
  6277. this._cache.aspectRatio = engine.getAspectRatio(this);
  6278. this._cache.orthoLeft = this.orthoLeft;
  6279. this._cache.orthoRight = this.orthoRight;
  6280. this._cache.orthoBottom = this.orthoBottom;
  6281. this._cache.orthoTop = this.orthoTop;
  6282. this._cache.renderWidth = engine.getRenderWidth();
  6283. this._cache.renderHeight = engine.getRenderHeight();
  6284. };
  6285. Camera.prototype._updateFromScene = function () {
  6286. this.updateCache();
  6287. this._update();
  6288. };
  6289. // Synchronized
  6290. Camera.prototype._isSynchronized = function () {
  6291. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6292. };
  6293. Camera.prototype._isSynchronizedViewMatrix = function () {
  6294. if (!_super.prototype._isSynchronized.call(this))
  6295. return false;
  6296. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6297. };
  6298. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6299. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6300. if (!check) {
  6301. return false;
  6302. }
  6303. var engine = this.getEngine();
  6304. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6305. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6306. }
  6307. else {
  6308. 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();
  6309. }
  6310. return check;
  6311. };
  6312. // Controls
  6313. Camera.prototype.attachControl = function (element) {
  6314. };
  6315. Camera.prototype.detachControl = function (element) {
  6316. };
  6317. Camera.prototype._update = function () {
  6318. };
  6319. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6320. if (insertAt === void 0) { insertAt = null; }
  6321. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6322. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6323. return 0;
  6324. }
  6325. if (insertAt == null || insertAt < 0) {
  6326. this._postProcesses.push(postProcess);
  6327. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6328. return this._postProcesses.length - 1;
  6329. }
  6330. var add = 0;
  6331. if (this._postProcesses[insertAt]) {
  6332. var start = this._postProcesses.length - 1;
  6333. for (var i = start; i >= insertAt + 1; --i) {
  6334. this._postProcesses[i + 1] = this._postProcesses[i];
  6335. }
  6336. add = 1;
  6337. }
  6338. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6339. if (this._postProcessesTakenIndices[i] < insertAt) {
  6340. continue;
  6341. }
  6342. start = this._postProcessesTakenIndices.length - 1;
  6343. for (var j = start; j >= i; --j) {
  6344. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6345. }
  6346. this._postProcessesTakenIndices[i] = insertAt;
  6347. break;
  6348. }
  6349. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6350. this._postProcessesTakenIndices.push(insertAt);
  6351. }
  6352. var result = insertAt + add;
  6353. this._postProcesses[result] = postProcess;
  6354. return result;
  6355. };
  6356. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6357. if (atIndices === void 0) { atIndices = null; }
  6358. var result = [];
  6359. if (!atIndices) {
  6360. var length = this._postProcesses.length;
  6361. for (var i = 0; i < length; i++) {
  6362. if (this._postProcesses[i] !== postProcess) {
  6363. continue;
  6364. }
  6365. delete this._postProcesses[i];
  6366. var index = this._postProcessesTakenIndices.indexOf(i);
  6367. this._postProcessesTakenIndices.splice(index, 1);
  6368. }
  6369. }
  6370. else {
  6371. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6372. for (i = 0; i < atIndices.length; i++) {
  6373. var foundPostProcess = this._postProcesses[atIndices[i]];
  6374. if (foundPostProcess !== postProcess) {
  6375. result.push(i);
  6376. continue;
  6377. }
  6378. delete this._postProcesses[atIndices[i]];
  6379. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6380. this._postProcessesTakenIndices.splice(index, 1);
  6381. }
  6382. }
  6383. return result;
  6384. };
  6385. Camera.prototype.getWorldMatrix = function () {
  6386. if (!this._worldMatrix) {
  6387. this._worldMatrix = BABYLON.Matrix.Identity();
  6388. }
  6389. var viewMatrix = this.getViewMatrix();
  6390. viewMatrix.invertToRef(this._worldMatrix);
  6391. return this._worldMatrix;
  6392. };
  6393. Camera.prototype._getViewMatrix = function () {
  6394. return BABYLON.Matrix.Identity();
  6395. };
  6396. Camera.prototype.getViewMatrix = function () {
  6397. this._computedViewMatrix = this._computeViewMatrix();
  6398. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6399. return this._computedViewMatrix;
  6400. }
  6401. if (!this._worldMatrix) {
  6402. this._worldMatrix = BABYLON.Matrix.Identity();
  6403. }
  6404. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6405. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6406. this._computedViewMatrix.invert();
  6407. this._currentRenderId = this.getScene().getRenderId();
  6408. return this._computedViewMatrix;
  6409. };
  6410. Camera.prototype._computeViewMatrix = function (force) {
  6411. if (!force && this._isSynchronizedViewMatrix()) {
  6412. return this._computedViewMatrix;
  6413. }
  6414. this._computedViewMatrix = this._getViewMatrix();
  6415. if (!this.parent || !this.parent.getWorldMatrix) {
  6416. this._currentRenderId = this.getScene().getRenderId();
  6417. }
  6418. return this._computedViewMatrix;
  6419. };
  6420. Camera.prototype.getProjectionMatrix = function (force) {
  6421. if (!force && this._isSynchronizedProjectionMatrix()) {
  6422. return this._projectionMatrix;
  6423. }
  6424. var engine = this.getEngine();
  6425. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6426. if (this.minZ <= 0) {
  6427. this.minZ = 0.1;
  6428. }
  6429. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6430. return this._projectionMatrix;
  6431. }
  6432. var halfWidth = engine.getRenderWidth() / 2.0;
  6433. var halfHeight = engine.getRenderHeight() / 2.0;
  6434. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6435. return this._projectionMatrix;
  6436. };
  6437. Camera.prototype.dispose = function () {
  6438. // Remove from scene
  6439. var index = this.getScene().cameras.indexOf(this);
  6440. this.getScene().cameras.splice(index, 1);
  6441. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6442. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6443. }
  6444. };
  6445. // Statics
  6446. Camera._PERSPECTIVE_CAMERA = 0;
  6447. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6448. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6449. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6450. return Camera;
  6451. })(BABYLON.Node);
  6452. BABYLON.Camera = Camera;
  6453. })(BABYLON || (BABYLON = {}));
  6454. //# sourceMappingURL=babylon.camera.js.map
  6455. var BABYLON;
  6456. (function (BABYLON) {
  6457. var TargetCamera = (function (_super) {
  6458. __extends(TargetCamera, _super);
  6459. function TargetCamera(name, position, scene) {
  6460. _super.call(this, name, position, scene);
  6461. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6462. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6463. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6464. this.speed = 2.0;
  6465. this.noRotationConstraint = false;
  6466. this.lockedTarget = null;
  6467. this._currentTarget = BABYLON.Vector3.Zero();
  6468. this._viewMatrix = BABYLON.Matrix.Zero();
  6469. this._camMatrix = BABYLON.Matrix.Zero();
  6470. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6471. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6472. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6473. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6474. this._lookAtTemp = BABYLON.Matrix.Zero();
  6475. this._tempMatrix = BABYLON.Matrix.Zero();
  6476. }
  6477. TargetCamera.prototype._getLockedTargetPosition = function () {
  6478. if (!this.lockedTarget) {
  6479. return null;
  6480. }
  6481. return this.lockedTarget.position || this.lockedTarget;
  6482. };
  6483. // Cache
  6484. TargetCamera.prototype._initCache = function () {
  6485. _super.prototype._initCache.call(this);
  6486. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6487. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6488. };
  6489. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6490. if (!ignoreParentClass) {
  6491. _super.prototype._updateCache.call(this);
  6492. }
  6493. var lockedTargetPosition = this._getLockedTargetPosition();
  6494. if (!lockedTargetPosition) {
  6495. this._cache.lockedTarget = null;
  6496. }
  6497. else {
  6498. if (!this._cache.lockedTarget) {
  6499. this._cache.lockedTarget = lockedTargetPosition.clone();
  6500. }
  6501. else {
  6502. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6503. }
  6504. }
  6505. this._cache.rotation.copyFrom(this.rotation);
  6506. };
  6507. // Synchronized
  6508. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6509. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6510. return false;
  6511. }
  6512. var lockedTargetPosition = this._getLockedTargetPosition();
  6513. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6514. };
  6515. // Methods
  6516. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6517. var engine = this.getEngine();
  6518. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6519. };
  6520. // Target
  6521. TargetCamera.prototype.setTarget = function (target) {
  6522. this.upVector.normalize();
  6523. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6524. this._camMatrix.invert();
  6525. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6526. var vDir = target.subtract(this.position);
  6527. if (vDir.x >= 0.0) {
  6528. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6529. }
  6530. else {
  6531. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6532. }
  6533. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6534. if (isNaN(this.rotation.x)) {
  6535. this.rotation.x = 0;
  6536. }
  6537. if (isNaN(this.rotation.y)) {
  6538. this.rotation.y = 0;
  6539. }
  6540. if (isNaN(this.rotation.z)) {
  6541. this.rotation.z = 0;
  6542. }
  6543. };
  6544. TargetCamera.prototype.getTarget = function () {
  6545. return this._currentTarget;
  6546. };
  6547. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6548. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6549. };
  6550. TargetCamera.prototype._updatePosition = function () {
  6551. this.position.addInPlace(this.cameraDirection);
  6552. };
  6553. TargetCamera.prototype._update = function () {
  6554. var needToMove = this._decideIfNeedsToMove();
  6555. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6556. // Move
  6557. if (needToMove) {
  6558. this._updatePosition();
  6559. }
  6560. // Rotate
  6561. if (needToRotate) {
  6562. this.rotation.x += this.cameraRotation.x;
  6563. this.rotation.y += this.cameraRotation.y;
  6564. if (!this.noRotationConstraint) {
  6565. var limit = (Math.PI / 2) * 0.95;
  6566. if (this.rotation.x > limit)
  6567. this.rotation.x = limit;
  6568. if (this.rotation.x < -limit)
  6569. this.rotation.x = -limit;
  6570. }
  6571. }
  6572. // Inertia
  6573. if (needToMove) {
  6574. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6575. this.cameraDirection.x = 0;
  6576. }
  6577. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6578. this.cameraDirection.y = 0;
  6579. }
  6580. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6581. this.cameraDirection.z = 0;
  6582. }
  6583. this.cameraDirection.scaleInPlace(this.inertia);
  6584. }
  6585. if (needToRotate) {
  6586. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6587. this.cameraRotation.x = 0;
  6588. }
  6589. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6590. this.cameraRotation.y = 0;
  6591. }
  6592. this.cameraRotation.scaleInPlace(this.inertia);
  6593. }
  6594. };
  6595. TargetCamera.prototype._getViewMatrix = function () {
  6596. if (!this.lockedTarget) {
  6597. // Compute
  6598. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6599. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6600. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6601. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6602. this._lookAtTemp.invert();
  6603. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6604. }
  6605. else {
  6606. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6607. }
  6608. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6609. // Computing target and final matrix
  6610. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6611. }
  6612. else {
  6613. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6614. }
  6615. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6616. return this._viewMatrix;
  6617. };
  6618. return TargetCamera;
  6619. })(BABYLON.Camera);
  6620. BABYLON.TargetCamera = TargetCamera;
  6621. })(BABYLON || (BABYLON = {}));
  6622. //# sourceMappingURL=babylon.targetCamera.js.map
  6623. var BABYLON;
  6624. (function (BABYLON) {
  6625. var FollowCamera = (function (_super) {
  6626. __extends(FollowCamera, _super);
  6627. function FollowCamera(name, position, scene) {
  6628. _super.call(this, name, position, scene);
  6629. this.radius = 12;
  6630. this.rotationOffset = 0;
  6631. this.heightOffset = 4;
  6632. this.cameraAcceleration = 0.05;
  6633. this.maxCameraSpeed = 20;
  6634. }
  6635. FollowCamera.prototype.getRadians = function (degrees) {
  6636. return degrees * Math.PI / 180;
  6637. };
  6638. FollowCamera.prototype.follow = function (cameraTarget) {
  6639. if (!cameraTarget)
  6640. return;
  6641. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6642. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6643. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6644. var dx = targetX - this.position.x;
  6645. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6646. var dz = (targetZ) - this.position.z;
  6647. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6648. var vy = dy * this.cameraAcceleration;
  6649. var vz = dz * this.cameraAcceleration * 2;
  6650. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6651. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6652. }
  6653. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6654. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6655. }
  6656. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6657. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6658. }
  6659. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6660. this.setTarget(cameraTarget.position);
  6661. };
  6662. FollowCamera.prototype._update = function () {
  6663. _super.prototype._update.call(this);
  6664. this.follow(this.target);
  6665. };
  6666. return FollowCamera;
  6667. })(BABYLON.TargetCamera);
  6668. BABYLON.FollowCamera = FollowCamera;
  6669. })(BABYLON || (BABYLON = {}));
  6670. //# sourceMappingURL=babylon.followCamera.js.map
  6671. var BABYLON;
  6672. (function (BABYLON) {
  6673. var FreeCamera = (function (_super) {
  6674. __extends(FreeCamera, _super);
  6675. function FreeCamera(name, position, scene) {
  6676. _super.call(this, name, position, scene);
  6677. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6678. this.keysUp = [38];
  6679. this.keysDown = [40];
  6680. this.keysLeft = [37];
  6681. this.keysRight = [39];
  6682. this.checkCollisions = false;
  6683. this.applyGravity = false;
  6684. this.angularSensibility = 2000.0;
  6685. this._keys = [];
  6686. this._collider = new BABYLON.Collider();
  6687. this._needMoveForGravity = true;
  6688. this._oldPosition = BABYLON.Vector3.Zero();
  6689. this._diffPosition = BABYLON.Vector3.Zero();
  6690. this._newPosition = BABYLON.Vector3.Zero();
  6691. }
  6692. // Controls
  6693. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6694. var _this = this;
  6695. var previousPosition;
  6696. var engine = this.getEngine();
  6697. if (this._attachedElement) {
  6698. return;
  6699. }
  6700. this._attachedElement = element;
  6701. if (this._onMouseDown === undefined) {
  6702. this._onMouseDown = function (evt) {
  6703. previousPosition = {
  6704. x: evt.clientX,
  6705. y: evt.clientY
  6706. };
  6707. if (!noPreventDefault) {
  6708. evt.preventDefault();
  6709. }
  6710. };
  6711. this._onMouseUp = function (evt) {
  6712. previousPosition = null;
  6713. if (!noPreventDefault) {
  6714. evt.preventDefault();
  6715. }
  6716. };
  6717. this._onMouseOut = function (evt) {
  6718. previousPosition = null;
  6719. _this._keys = [];
  6720. if (!noPreventDefault) {
  6721. evt.preventDefault();
  6722. }
  6723. };
  6724. this._onMouseMove = function (evt) {
  6725. if (!previousPosition && !engine.isPointerLock) {
  6726. return;
  6727. }
  6728. var offsetX;
  6729. var offsetY;
  6730. if (!engine.isPointerLock) {
  6731. offsetX = evt.clientX - previousPosition.x;
  6732. offsetY = evt.clientY - previousPosition.y;
  6733. }
  6734. else {
  6735. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6736. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6737. }
  6738. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6739. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6740. previousPosition = {
  6741. x: evt.clientX,
  6742. y: evt.clientY
  6743. };
  6744. if (!noPreventDefault) {
  6745. evt.preventDefault();
  6746. }
  6747. };
  6748. this._onKeyDown = function (evt) {
  6749. 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) {
  6750. var index = _this._keys.indexOf(evt.keyCode);
  6751. if (index === -1) {
  6752. _this._keys.push(evt.keyCode);
  6753. }
  6754. if (!noPreventDefault) {
  6755. evt.preventDefault();
  6756. }
  6757. }
  6758. };
  6759. this._onKeyUp = function (evt) {
  6760. 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) {
  6761. var index = _this._keys.indexOf(evt.keyCode);
  6762. if (index >= 0) {
  6763. _this._keys.splice(index, 1);
  6764. }
  6765. if (!noPreventDefault) {
  6766. evt.preventDefault();
  6767. }
  6768. }
  6769. };
  6770. this._onLostFocus = function () {
  6771. _this._keys = [];
  6772. };
  6773. this._reset = function () {
  6774. _this._keys = [];
  6775. previousPosition = null;
  6776. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6777. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6778. };
  6779. }
  6780. element.addEventListener("mousedown", this._onMouseDown, false);
  6781. element.addEventListener("mouseup", this._onMouseUp, false);
  6782. element.addEventListener("mouseout", this._onMouseOut, false);
  6783. element.addEventListener("mousemove", this._onMouseMove, false);
  6784. BABYLON.Tools.RegisterTopRootEvents([
  6785. { name: "keydown", handler: this._onKeyDown },
  6786. { name: "keyup", handler: this._onKeyUp },
  6787. { name: "blur", handler: this._onLostFocus }
  6788. ]);
  6789. };
  6790. FreeCamera.prototype.detachControl = function (element) {
  6791. if (this._attachedElement != element) {
  6792. return;
  6793. }
  6794. element.removeEventListener("mousedown", this._onMouseDown);
  6795. element.removeEventListener("mouseup", this._onMouseUp);
  6796. element.removeEventListener("mouseout", this._onMouseOut);
  6797. element.removeEventListener("mousemove", this._onMouseMove);
  6798. BABYLON.Tools.UnregisterTopRootEvents([
  6799. { name: "keydown", handler: this._onKeyDown },
  6800. { name: "keyup", handler: this._onKeyUp },
  6801. { name: "blur", handler: this._onLostFocus }
  6802. ]);
  6803. this._attachedElement = null;
  6804. if (this._reset) {
  6805. this._reset();
  6806. }
  6807. };
  6808. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6809. var globalPosition;
  6810. if (this.parent) {
  6811. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6812. }
  6813. else {
  6814. globalPosition = this.position;
  6815. }
  6816. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6817. this._collider.radius = this.ellipsoid;
  6818. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6819. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6820. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6821. this.position.addInPlace(this._diffPosition);
  6822. if (this.onCollide) {
  6823. this.onCollide(this._collider.collidedMesh);
  6824. }
  6825. }
  6826. };
  6827. FreeCamera.prototype._checkInputs = function () {
  6828. if (!this._localDirection) {
  6829. this._localDirection = BABYLON.Vector3.Zero();
  6830. this._transformedDirection = BABYLON.Vector3.Zero();
  6831. }
  6832. for (var index = 0; index < this._keys.length; index++) {
  6833. var keyCode = this._keys[index];
  6834. var speed = this._computeLocalCameraSpeed();
  6835. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6836. this._localDirection.copyFromFloats(-speed, 0, 0);
  6837. }
  6838. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6839. this._localDirection.copyFromFloats(0, 0, speed);
  6840. }
  6841. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6842. this._localDirection.copyFromFloats(speed, 0, 0);
  6843. }
  6844. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6845. this._localDirection.copyFromFloats(0, 0, -speed);
  6846. }
  6847. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6848. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6849. this.cameraDirection.addInPlace(this._transformedDirection);
  6850. }
  6851. };
  6852. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6853. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6854. };
  6855. FreeCamera.prototype._updatePosition = function () {
  6856. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6857. this._collideWithWorld(this.cameraDirection);
  6858. if (this.applyGravity) {
  6859. var oldPosition = this.position;
  6860. this._collideWithWorld(this.getScene().gravity);
  6861. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6862. }
  6863. }
  6864. else {
  6865. this.position.addInPlace(this.cameraDirection);
  6866. }
  6867. };
  6868. FreeCamera.prototype._update = function () {
  6869. this._checkInputs();
  6870. _super.prototype._update.call(this);
  6871. };
  6872. return FreeCamera;
  6873. })(BABYLON.TargetCamera);
  6874. BABYLON.FreeCamera = FreeCamera;
  6875. })(BABYLON || (BABYLON = {}));
  6876. //# sourceMappingURL=babylon.freeCamera.js.map
  6877. var BABYLON;
  6878. (function (BABYLON) {
  6879. // We're mainly based on the logic defined into the FreeCamera code
  6880. var TouchCamera = (function (_super) {
  6881. __extends(TouchCamera, _super);
  6882. function TouchCamera(name, position, scene) {
  6883. _super.call(this, name, position, scene);
  6884. this._offsetX = null;
  6885. this._offsetY = null;
  6886. this._pointerCount = 0;
  6887. this._pointerPressed = [];
  6888. this.angularSensibility = 200000.0;
  6889. this.moveSensibility = 500.0;
  6890. }
  6891. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6892. var _this = this;
  6893. var previousPosition;
  6894. if (this._attachedCanvas) {
  6895. return;
  6896. }
  6897. this._attachedCanvas = canvas;
  6898. if (this._onPointerDown === undefined) {
  6899. this._onPointerDown = function (evt) {
  6900. if (!noPreventDefault) {
  6901. evt.preventDefault();
  6902. }
  6903. _this._pointerPressed.push(evt.pointerId);
  6904. if (_this._pointerPressed.length !== 1) {
  6905. return;
  6906. }
  6907. previousPosition = {
  6908. x: evt.clientX,
  6909. y: evt.clientY
  6910. };
  6911. };
  6912. this._onPointerUp = function (evt) {
  6913. if (!noPreventDefault) {
  6914. evt.preventDefault();
  6915. }
  6916. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6917. if (index === -1) {
  6918. return;
  6919. }
  6920. _this._pointerPressed.splice(index, 1);
  6921. if (index != 0) {
  6922. return;
  6923. }
  6924. previousPosition = null;
  6925. _this._offsetX = null;
  6926. _this._offsetY = null;
  6927. };
  6928. this._onPointerMove = function (evt) {
  6929. if (!noPreventDefault) {
  6930. evt.preventDefault();
  6931. }
  6932. if (!previousPosition) {
  6933. return;
  6934. }
  6935. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6936. if (index != 0) {
  6937. return;
  6938. }
  6939. _this._offsetX = evt.clientX - previousPosition.x;
  6940. _this._offsetY = -(evt.clientY - previousPosition.y);
  6941. };
  6942. this._onLostFocus = function () {
  6943. _this._offsetX = null;
  6944. _this._offsetY = null;
  6945. };
  6946. }
  6947. canvas.addEventListener("pointerdown", this._onPointerDown);
  6948. canvas.addEventListener("pointerup", this._onPointerUp);
  6949. canvas.addEventListener("pointerout", this._onPointerUp);
  6950. canvas.addEventListener("pointermove", this._onPointerMove);
  6951. BABYLON.Tools.RegisterTopRootEvents([
  6952. { name: "blur", handler: this._onLostFocus }
  6953. ]);
  6954. };
  6955. TouchCamera.prototype.detachControl = function (canvas) {
  6956. if (this._attachedCanvas != canvas) {
  6957. return;
  6958. }
  6959. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6960. canvas.removeEventListener("pointerup", this._onPointerUp);
  6961. canvas.removeEventListener("pointerout", this._onPointerUp);
  6962. canvas.removeEventListener("pointermove", this._onPointerMove);
  6963. BABYLON.Tools.UnregisterTopRootEvents([
  6964. { name: "blur", handler: this._onLostFocus }
  6965. ]);
  6966. this._attachedCanvas = null;
  6967. };
  6968. TouchCamera.prototype._checkInputs = function () {
  6969. if (!this._offsetX) {
  6970. return;
  6971. }
  6972. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6973. if (this._pointerPressed.length > 1) {
  6974. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6975. }
  6976. else {
  6977. var speed = this._computeLocalCameraSpeed();
  6978. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6979. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6980. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6981. }
  6982. };
  6983. return TouchCamera;
  6984. })(BABYLON.FreeCamera);
  6985. BABYLON.TouchCamera = TouchCamera;
  6986. })(BABYLON || (BABYLON = {}));
  6987. //# sourceMappingURL=babylon.touchCamera.js.map
  6988. var BABYLON;
  6989. (function (BABYLON) {
  6990. // We're mainly based on the logic defined into the FreeCamera code
  6991. var DeviceOrientationCamera = (function (_super) {
  6992. __extends(DeviceOrientationCamera, _super);
  6993. function DeviceOrientationCamera(name, position, scene) {
  6994. var _this = this;
  6995. _super.call(this, name, position, scene);
  6996. this._offsetX = null;
  6997. this._offsetY = null;
  6998. this._orientationGamma = 0;
  6999. this._orientationBeta = 0;
  7000. this._initialOrientationGamma = 0;
  7001. this._initialOrientationBeta = 0;
  7002. this.angularSensibility = 10000.0;
  7003. this.moveSensibility = 50.0;
  7004. window.addEventListener("resize", function () {
  7005. _this._initialOrientationGamma = null;
  7006. }, false);
  7007. }
  7008. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7009. var _this = this;
  7010. if (this._attachedCanvas) {
  7011. return;
  7012. }
  7013. this._attachedCanvas = canvas;
  7014. if (!this._orientationChanged) {
  7015. this._orientationChanged = function (evt) {
  7016. if (!_this._initialOrientationGamma) {
  7017. _this._initialOrientationGamma = evt.gamma;
  7018. _this._initialOrientationBeta = evt.beta;
  7019. }
  7020. _this._orientationGamma = evt.gamma;
  7021. _this._orientationBeta = evt.beta;
  7022. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7023. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7024. };
  7025. }
  7026. window.addEventListener("deviceorientation", this._orientationChanged);
  7027. };
  7028. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7029. if (this._attachedCanvas != canvas) {
  7030. return;
  7031. }
  7032. window.removeEventListener("deviceorientation", this._orientationChanged);
  7033. this._attachedCanvas = null;
  7034. this._orientationGamma = 0;
  7035. this._orientationBeta = 0;
  7036. this._initialOrientationGamma = 0;
  7037. this._initialOrientationBeta = 0;
  7038. };
  7039. DeviceOrientationCamera.prototype._checkInputs = function () {
  7040. if (!this._offsetX) {
  7041. return;
  7042. }
  7043. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7044. var speed = this._computeLocalCameraSpeed();
  7045. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7046. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7047. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7048. };
  7049. return DeviceOrientationCamera;
  7050. })(BABYLON.FreeCamera);
  7051. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7052. })(BABYLON || (BABYLON = {}));
  7053. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7054. var BABYLON;
  7055. (function (BABYLON) {
  7056. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7057. var ArcRotateCamera = (function (_super) {
  7058. __extends(ArcRotateCamera, _super);
  7059. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7060. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7061. this.alpha = alpha;
  7062. this.beta = beta;
  7063. this.radius = radius;
  7064. this.target = target;
  7065. this.inertialAlphaOffset = 0;
  7066. this.inertialBetaOffset = 0;
  7067. this.inertialRadiusOffset = 0;
  7068. this.lowerAlphaLimit = null;
  7069. this.upperAlphaLimit = null;
  7070. this.lowerBetaLimit = 0.01;
  7071. this.upperBetaLimit = Math.PI;
  7072. this.lowerRadiusLimit = null;
  7073. this.upperRadiusLimit = null;
  7074. this.angularSensibility = 1000.0;
  7075. this.wheelPrecision = 3.0;
  7076. this.keysUp = [38];
  7077. this.keysDown = [40];
  7078. this.keysLeft = [37];
  7079. this.keysRight = [39];
  7080. this.zoomOnFactor = 1;
  7081. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7082. this._keys = [];
  7083. this._viewMatrix = new BABYLON.Matrix();
  7084. this.checkCollisions = false;
  7085. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7086. this._collider = new BABYLON.Collider();
  7087. this._previousPosition = BABYLON.Vector3.Zero();
  7088. this._collisionVelocity = BABYLON.Vector3.Zero();
  7089. this._newPosition = BABYLON.Vector3.Zero();
  7090. // Pinch
  7091. // value for pinch step scaling
  7092. // set to 20 by default
  7093. this.pinchPrecision = 20;
  7094. this.getViewMatrix();
  7095. }
  7096. ArcRotateCamera.prototype._getTargetPosition = function () {
  7097. return this.target.position || this.target;
  7098. };
  7099. // Cache
  7100. ArcRotateCamera.prototype._initCache = function () {
  7101. _super.prototype._initCache.call(this);
  7102. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7103. this._cache.alpha = undefined;
  7104. this._cache.beta = undefined;
  7105. this._cache.radius = undefined;
  7106. this._cache.targetScreenOffset = undefined;
  7107. };
  7108. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7109. if (!ignoreParentClass) {
  7110. _super.prototype._updateCache.call(this);
  7111. }
  7112. this._cache.target.copyFrom(this._getTargetPosition());
  7113. this._cache.alpha = this.alpha;
  7114. this._cache.beta = this.beta;
  7115. this._cache.radius = this.radius;
  7116. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7117. };
  7118. // Synchronized
  7119. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7120. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7121. return false;
  7122. 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);
  7123. };
  7124. // Methods
  7125. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7126. var _this = this;
  7127. var previousPosition;
  7128. var pointerId;
  7129. // to know if pinch started
  7130. var pinchStarted = false;
  7131. // two pinch point on X
  7132. // that will use for find if user action is pinch open or pinch close
  7133. var pinchPointX1, pinchPointX2;
  7134. if (this._attachedElement) {
  7135. return;
  7136. }
  7137. this._attachedElement = element;
  7138. var engine = this.getEngine();
  7139. if (this._onPointerDown === undefined) {
  7140. this._onPointerDown = function (evt) {
  7141. if (pointerId) {
  7142. return;
  7143. }
  7144. pointerId = evt.pointerId;
  7145. previousPosition = {
  7146. x: evt.clientX,
  7147. y: evt.clientY
  7148. };
  7149. if (!noPreventDefault) {
  7150. evt.preventDefault();
  7151. }
  7152. };
  7153. this._onPointerUp = function (evt) {
  7154. previousPosition = null;
  7155. pointerId = null;
  7156. if (!noPreventDefault) {
  7157. evt.preventDefault();
  7158. }
  7159. };
  7160. this._onPointerMove = function (evt) {
  7161. if (!previousPosition) {
  7162. return;
  7163. }
  7164. if (pointerId !== evt.pointerId) {
  7165. return;
  7166. }
  7167. // return pinch is started
  7168. if (pinchStarted) {
  7169. return;
  7170. }
  7171. var offsetX = evt.clientX - previousPosition.x;
  7172. var offsetY = evt.clientY - previousPosition.y;
  7173. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7174. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7175. previousPosition = {
  7176. x: evt.clientX,
  7177. y: evt.clientY
  7178. };
  7179. if (!noPreventDefault) {
  7180. evt.preventDefault();
  7181. }
  7182. };
  7183. this._onMouseMove = function (evt) {
  7184. if (!engine.isPointerLock) {
  7185. return;
  7186. }
  7187. // return pinch is started
  7188. if (pinchStarted) {
  7189. return;
  7190. }
  7191. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7192. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7193. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7194. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7195. if (!noPreventDefault) {
  7196. evt.preventDefault();
  7197. }
  7198. };
  7199. this._wheel = function (event) {
  7200. var delta = 0;
  7201. if (event.wheelDelta) {
  7202. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7203. }
  7204. else if (event.detail) {
  7205. delta = -event.detail / _this.wheelPrecision;
  7206. }
  7207. if (delta)
  7208. _this.inertialRadiusOffset += delta;
  7209. if (event.preventDefault) {
  7210. if (!noPreventDefault) {
  7211. event.preventDefault();
  7212. }
  7213. }
  7214. };
  7215. this._onKeyDown = function (evt) {
  7216. 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) {
  7217. var index = _this._keys.indexOf(evt.keyCode);
  7218. if (index === -1) {
  7219. _this._keys.push(evt.keyCode);
  7220. }
  7221. if (evt.preventDefault) {
  7222. if (!noPreventDefault) {
  7223. evt.preventDefault();
  7224. }
  7225. }
  7226. }
  7227. };
  7228. this._onKeyUp = function (evt) {
  7229. 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) {
  7230. var index = _this._keys.indexOf(evt.keyCode);
  7231. if (index >= 0) {
  7232. _this._keys.splice(index, 1);
  7233. }
  7234. if (evt.preventDefault) {
  7235. if (!noPreventDefault) {
  7236. evt.preventDefault();
  7237. }
  7238. }
  7239. }
  7240. };
  7241. this._onLostFocus = function () {
  7242. _this._keys = [];
  7243. pointerId = null;
  7244. };
  7245. this._onGestureStart = function (e) {
  7246. if (window.MSGesture === undefined) {
  7247. return;
  7248. }
  7249. if (!_this._MSGestureHandler) {
  7250. _this._MSGestureHandler = new MSGesture();
  7251. _this._MSGestureHandler.target = element;
  7252. }
  7253. _this._MSGestureHandler.addPointer(e.pointerId);
  7254. };
  7255. this._onGesture = function (e) {
  7256. _this.radius *= e.scale;
  7257. if (e.preventDefault) {
  7258. if (!noPreventDefault) {
  7259. e.stopPropagation();
  7260. e.preventDefault();
  7261. }
  7262. }
  7263. };
  7264. this._reset = function () {
  7265. _this._keys = [];
  7266. _this.inertialAlphaOffset = 0;
  7267. _this.inertialBetaOffset = 0;
  7268. _this.inertialRadiusOffset = 0;
  7269. previousPosition = null;
  7270. pointerId = null;
  7271. };
  7272. this._touchStart = function (event) {
  7273. if (event.touches.length === 2) {
  7274. //-- start pinch if two fingers on the screen
  7275. pinchStarted = true;
  7276. _this._pinchStart(event);
  7277. }
  7278. };
  7279. this._touchMove = function (event) {
  7280. if (pinchStarted) {
  7281. //-- make scaling
  7282. _this._pinchMove(event);
  7283. }
  7284. };
  7285. this._touchEnd = function (event) {
  7286. if (pinchStarted) {
  7287. //-- end of pinch
  7288. _this._pinchEnd(event);
  7289. }
  7290. };
  7291. this._pinchStart = function (event) {
  7292. // save origin touch point
  7293. pinchPointX1 = event.touches[0].clientX;
  7294. pinchPointX2 = event.touches[1].clientX;
  7295. // block the camera
  7296. // if not it rotate around target during pinch
  7297. pinchStarted = true;
  7298. };
  7299. this._pinchMove = function (event) {
  7300. // variable for new camera's radius
  7301. var delta = 0;
  7302. // variables to know if pinch open or pinch close
  7303. var direction = 1;
  7304. var distanceXOrigine, distanceXNow;
  7305. if (event.touches.length !== 2)
  7306. return;
  7307. // calculate absolute distances of the two fingers
  7308. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7309. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7310. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7311. if (distanceXNow < distanceXOrigine) {
  7312. direction = -1;
  7313. }
  7314. // calculate new radius
  7315. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7316. // set new radius
  7317. _this.inertialRadiusOffset -= delta;
  7318. // save origin touch point
  7319. pinchPointX1 = event.touches[0].clientX;
  7320. pinchPointX2 = event.touches[1].clientX;
  7321. };
  7322. this._pinchEnd = function (event) {
  7323. // cancel pinch and deblock camera rotation
  7324. pinchStarted = false;
  7325. };
  7326. }
  7327. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7328. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7329. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7330. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7331. element.addEventListener("mousemove", this._onMouseMove, false);
  7332. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7333. element.addEventListener("MSGestureChange", this._onGesture, false);
  7334. element.addEventListener('mousewheel', this._wheel, false);
  7335. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7336. // pinch
  7337. element.addEventListener('touchstart', this._touchStart, false);
  7338. element.addEventListener('touchmove', this._touchMove, false);
  7339. element.addEventListener('touchend', this._touchEnd, false);
  7340. BABYLON.Tools.RegisterTopRootEvents([
  7341. { name: "keydown", handler: this._onKeyDown },
  7342. { name: "keyup", handler: this._onKeyUp },
  7343. { name: "blur", handler: this._onLostFocus }
  7344. ]);
  7345. };
  7346. ArcRotateCamera.prototype.detachControl = function (element) {
  7347. if (this._attachedElement != element) {
  7348. return;
  7349. }
  7350. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7351. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7352. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7353. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7354. element.removeEventListener("mousemove", this._onMouseMove);
  7355. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7356. element.removeEventListener("MSGestureChange", this._onGesture);
  7357. element.removeEventListener('mousewheel', this._wheel);
  7358. element.removeEventListener('DOMMouseScroll', this._wheel);
  7359. // pinch
  7360. element.removeEventListener('touchstart', this._touchStart);
  7361. element.removeEventListener('touchmove', this._touchMove);
  7362. element.removeEventListener('touchend', this._touchEnd);
  7363. BABYLON.Tools.UnregisterTopRootEvents([
  7364. { name: "keydown", handler: this._onKeyDown },
  7365. { name: "keyup", handler: this._onKeyUp },
  7366. { name: "blur", handler: this._onLostFocus }
  7367. ]);
  7368. this._MSGestureHandler = null;
  7369. this._attachedElement = null;
  7370. if (this._reset) {
  7371. this._reset();
  7372. }
  7373. };
  7374. ArcRotateCamera.prototype._update = function () {
  7375. for (var index = 0; index < this._keys.length; index++) {
  7376. var keyCode = this._keys[index];
  7377. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7378. this.inertialAlphaOffset -= 0.01;
  7379. }
  7380. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7381. this.inertialBetaOffset -= 0.01;
  7382. }
  7383. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7384. this.inertialAlphaOffset += 0.01;
  7385. }
  7386. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7387. this.inertialBetaOffset += 0.01;
  7388. }
  7389. }
  7390. // Inertia
  7391. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7392. this.alpha += this.inertialAlphaOffset;
  7393. this.beta += this.inertialBetaOffset;
  7394. this.radius -= this.inertialRadiusOffset;
  7395. this.inertialAlphaOffset *= this.inertia;
  7396. this.inertialBetaOffset *= this.inertia;
  7397. this.inertialRadiusOffset *= this.inertia;
  7398. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7399. this.inertialAlphaOffset = 0;
  7400. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7401. this.inertialBetaOffset = 0;
  7402. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7403. this.inertialRadiusOffset = 0;
  7404. }
  7405. // Limits
  7406. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7407. this.alpha = this.lowerAlphaLimit;
  7408. }
  7409. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7410. this.alpha = this.upperAlphaLimit;
  7411. }
  7412. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7413. this.beta = this.lowerBetaLimit;
  7414. }
  7415. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7416. this.beta = this.upperBetaLimit;
  7417. }
  7418. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7419. this.radius = this.lowerRadiusLimit;
  7420. }
  7421. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7422. this.radius = this.upperRadiusLimit;
  7423. }
  7424. };
  7425. ArcRotateCamera.prototype.setPosition = function (position) {
  7426. var radiusv3 = position.subtract(this._getTargetPosition());
  7427. this.radius = radiusv3.length();
  7428. // Alpha
  7429. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7430. if (radiusv3.z < 0) {
  7431. this.alpha = 2 * Math.PI - this.alpha;
  7432. }
  7433. // Beta
  7434. this.beta = Math.acos(radiusv3.y / this.radius);
  7435. };
  7436. ArcRotateCamera.prototype._getViewMatrix = function () {
  7437. // Compute
  7438. var cosa = Math.cos(this.alpha);
  7439. var sina = Math.sin(this.alpha);
  7440. var cosb = Math.cos(this.beta);
  7441. var sinb = Math.sin(this.beta);
  7442. var target = this._getTargetPosition();
  7443. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7444. if (this.checkCollisions) {
  7445. this._collider.radius = this.collisionRadius;
  7446. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7447. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7448. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7449. this.position.copyFrom(this._previousPosition);
  7450. this.alpha = this._previousAlpha;
  7451. this.beta = this._previousBeta;
  7452. this.radius = this._previousRadius;
  7453. if (this.onCollide) {
  7454. this.onCollide(this._collider.collidedMesh);
  7455. }
  7456. }
  7457. }
  7458. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7459. this._previousAlpha = this.alpha;
  7460. this._previousBeta = this.beta;
  7461. this._previousRadius = this.radius;
  7462. this._previousPosition.copyFrom(this.position);
  7463. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7464. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7465. return this._viewMatrix;
  7466. };
  7467. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7468. meshes = meshes || this.getScene().meshes;
  7469. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7470. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7471. this.radius = distance * this.zoomOnFactor;
  7472. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7473. };
  7474. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7475. var meshesOrMinMaxVector;
  7476. var distance;
  7477. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7478. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7479. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7480. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7481. }
  7482. else {
  7483. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7484. distance = meshesOrMinMaxVectorAndDistance.distance;
  7485. }
  7486. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7487. this.maxZ = distance * 2;
  7488. };
  7489. return ArcRotateCamera;
  7490. })(BABYLON.Camera);
  7491. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7492. })(BABYLON || (BABYLON = {}));
  7493. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7494. (function (BABYLON) {
  7495. /**
  7496. * Represents a scene to be rendered by the engine.
  7497. * @see http://doc.babylonjs.com/page.php?p=21911
  7498. */
  7499. var Scene = (function () {
  7500. /**
  7501. * @constructor
  7502. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7503. */
  7504. function Scene(engine) {
  7505. // Members
  7506. this.autoClear = true;
  7507. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7508. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7509. this.forceWireframe = false;
  7510. this.forcePointsCloud = false;
  7511. this.forceShowBoundingBoxes = false;
  7512. this.animationsEnabled = true;
  7513. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7514. // Fog
  7515. /**
  7516. * is fog enabled on this scene.
  7517. * @type {boolean}
  7518. */
  7519. this.fogEnabled = true;
  7520. this.fogMode = Scene.FOGMODE_NONE;
  7521. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7522. this.fogDensity = 0.1;
  7523. this.fogStart = 0;
  7524. this.fogEnd = 1000.0;
  7525. // Lights
  7526. /**
  7527. * is shadow enabled on this scene.
  7528. * @type {boolean}
  7529. */
  7530. this.shadowsEnabled = true;
  7531. /**
  7532. * is light enabled on this scene.
  7533. * @type {boolean}
  7534. */
  7535. this.lightsEnabled = true;
  7536. /**
  7537. * All of the lights added to this scene.
  7538. * @see BABYLON.Light
  7539. * @type {BABYLON.Light[]}
  7540. */
  7541. this.lights = new Array();
  7542. // Cameras
  7543. /**
  7544. * All of the cameras added to this scene.
  7545. * @see BABYLON.Camera
  7546. * @type {BABYLON.Camera[]}
  7547. */
  7548. this.cameras = new Array();
  7549. this.activeCameras = new Array();
  7550. // Meshes
  7551. /**
  7552. * All of the (abstract) meshes added to this scene.
  7553. * @see BABYLON.AbstractMesh
  7554. * @type {BABYLON.AbstractMesh[]}
  7555. */
  7556. this.meshes = new Array();
  7557. // Geometries
  7558. this._geometries = new Array();
  7559. this.materials = new Array();
  7560. this.multiMaterials = new Array();
  7561. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7562. // Textures
  7563. this.texturesEnabled = true;
  7564. this.textures = new Array();
  7565. // Particles
  7566. this.particlesEnabled = true;
  7567. this.particleSystems = new Array();
  7568. // Sprites
  7569. this.spriteManagers = new Array();
  7570. // Layers
  7571. this.layers = new Array();
  7572. // Skeletons
  7573. this.skeletonsEnabled = true;
  7574. this.skeletons = new Array();
  7575. // Lens flares
  7576. this.lensFlaresEnabled = true;
  7577. this.lensFlareSystems = new Array();
  7578. // Collisions
  7579. this.collisionsEnabled = true;
  7580. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7581. // Postprocesses
  7582. this.postProcessesEnabled = true;
  7583. // Customs render targets
  7584. this.renderTargetsEnabled = true;
  7585. this.customRenderTargets = new Array();
  7586. // Imported meshes
  7587. this.importedMeshesFiles = new Array();
  7588. this._actionManagers = new Array();
  7589. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7590. // Procedural textures
  7591. this.proceduralTexturesEnabled = true;
  7592. this._proceduralTextures = new Array();
  7593. this.soundTracks = new Array();
  7594. this._totalVertices = 0;
  7595. this._activeVertices = 0;
  7596. this._activeParticles = 0;
  7597. this._lastFrameDuration = 0;
  7598. this._evaluateActiveMeshesDuration = 0;
  7599. this._renderTargetsDuration = 0;
  7600. this._particlesDuration = 0;
  7601. this._renderDuration = 0;
  7602. this._spritesDuration = 0;
  7603. this._animationRatio = 0;
  7604. this._renderId = 0;
  7605. this._executeWhenReadyTimeoutId = -1;
  7606. this._toBeDisposed = new BABYLON.SmartArray(256);
  7607. this._onReadyCallbacks = new Array();
  7608. this._pendingData = []; //ANY
  7609. this._onBeforeRenderCallbacks = new Array();
  7610. this._onAfterRenderCallbacks = new Array();
  7611. this._activeMeshes = new BABYLON.SmartArray(256);
  7612. this._processedMaterials = new BABYLON.SmartArray(256);
  7613. this._renderTargets = new BABYLON.SmartArray(256);
  7614. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7615. this._activeSkeletons = new BABYLON.SmartArray(32);
  7616. this._activeBones = 0;
  7617. this._activeAnimatables = new Array();
  7618. this._transformMatrix = BABYLON.Matrix.Zero();
  7619. this._scaledPosition = BABYLON.Vector3.Zero();
  7620. this._scaledVelocity = BABYLON.Vector3.Zero();
  7621. this._engine = engine;
  7622. engine.scenes.push(this);
  7623. this._renderingManager = new BABYLON.RenderingManager(this);
  7624. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7625. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7626. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7627. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7628. this.attachControl();
  7629. this._debugLayer = new BABYLON.DebugLayer(this);
  7630. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7631. }
  7632. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7633. get: function () {
  7634. return Scene._FOGMODE_NONE;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7640. get: function () {
  7641. return Scene._FOGMODE_EXP;
  7642. },
  7643. enumerable: true,
  7644. configurable: true
  7645. });
  7646. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7647. get: function () {
  7648. return Scene._FOGMODE_EXP2;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7654. get: function () {
  7655. return Scene._FOGMODE_LINEAR;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. Object.defineProperty(Scene.prototype, "debugLayer", {
  7661. // Properties
  7662. get: function () {
  7663. return this._debugLayer;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7669. /**
  7670. * The mesh that is currently under the pointer.
  7671. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7672. */
  7673. get: function () {
  7674. return this._meshUnderPointer;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Scene.prototype, "pointerX", {
  7680. /**
  7681. * Current on-screen X position of the pointer
  7682. * @return {number} X position of the pointer
  7683. */
  7684. get: function () {
  7685. return this._pointerX;
  7686. },
  7687. enumerable: true,
  7688. configurable: true
  7689. });
  7690. Object.defineProperty(Scene.prototype, "pointerY", {
  7691. /**
  7692. * Current on-screen Y position of the pointer
  7693. * @return {number} Y position of the pointer
  7694. */
  7695. get: function () {
  7696. return this._pointerY;
  7697. },
  7698. enumerable: true,
  7699. configurable: true
  7700. });
  7701. Scene.prototype.getCachedMaterial = function () {
  7702. return this._cachedMaterial;
  7703. };
  7704. Scene.prototype.getBoundingBoxRenderer = function () {
  7705. return this._boundingBoxRenderer;
  7706. };
  7707. Scene.prototype.getOutlineRenderer = function () {
  7708. return this._outlineRenderer;
  7709. };
  7710. Scene.prototype.getEngine = function () {
  7711. return this._engine;
  7712. };
  7713. Scene.prototype.getTotalVertices = function () {
  7714. return this._totalVertices;
  7715. };
  7716. Scene.prototype.getActiveVertices = function () {
  7717. return this._activeVertices;
  7718. };
  7719. Scene.prototype.getActiveParticles = function () {
  7720. return this._activeParticles;
  7721. };
  7722. Scene.prototype.getActiveBones = function () {
  7723. return this._activeBones;
  7724. };
  7725. // Stats
  7726. Scene.prototype.getLastFrameDuration = function () {
  7727. return this._lastFrameDuration;
  7728. };
  7729. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7730. return this._evaluateActiveMeshesDuration;
  7731. };
  7732. Scene.prototype.getActiveMeshes = function () {
  7733. return this._activeMeshes;
  7734. };
  7735. Scene.prototype.getRenderTargetsDuration = function () {
  7736. return this._renderTargetsDuration;
  7737. };
  7738. Scene.prototype.getRenderDuration = function () {
  7739. return this._renderDuration;
  7740. };
  7741. Scene.prototype.getParticlesDuration = function () {
  7742. return this._particlesDuration;
  7743. };
  7744. Scene.prototype.getSpritesDuration = function () {
  7745. return this._spritesDuration;
  7746. };
  7747. Scene.prototype.getAnimationRatio = function () {
  7748. return this._animationRatio;
  7749. };
  7750. Scene.prototype.getRenderId = function () {
  7751. return this._renderId;
  7752. };
  7753. Scene.prototype.incrementRenderId = function () {
  7754. this._renderId++;
  7755. };
  7756. Scene.prototype._updatePointerPosition = function (evt) {
  7757. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7758. this._pointerX = evt.clientX - canvasRect.left;
  7759. this._pointerY = evt.clientY - canvasRect.top;
  7760. if (this.cameraToUseForPointers) {
  7761. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7762. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7763. }
  7764. };
  7765. // Pointers handling
  7766. Scene.prototype.attachControl = function () {
  7767. var _this = this;
  7768. this._onPointerMove = function (evt) {
  7769. var canvas = _this._engine.getRenderingCanvas();
  7770. _this._updatePointerPosition(evt);
  7771. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7772. if (pickResult.hit) {
  7773. _this._meshUnderPointer = pickResult.pickedMesh;
  7774. _this.setPointerOverMesh(pickResult.pickedMesh);
  7775. canvas.style.cursor = "pointer";
  7776. }
  7777. else {
  7778. _this.setPointerOverMesh(null);
  7779. canvas.style.cursor = "";
  7780. _this._meshUnderPointer = null;
  7781. }
  7782. };
  7783. this._onPointerDown = function (evt) {
  7784. var predicate = null;
  7785. if (!_this.onPointerDown) {
  7786. predicate = function (mesh) {
  7787. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7788. };
  7789. }
  7790. _this._updatePointerPosition(evt);
  7791. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7792. if (pickResult.hit) {
  7793. if (pickResult.pickedMesh.actionManager) {
  7794. switch (evt.button) {
  7795. case 0:
  7796. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7797. break;
  7798. case 1:
  7799. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7800. break;
  7801. case 2:
  7802. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7803. break;
  7804. }
  7805. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7806. }
  7807. }
  7808. if (_this.onPointerDown) {
  7809. _this.onPointerDown(evt, pickResult);
  7810. }
  7811. };
  7812. this._onKeyDown = function (evt) {
  7813. if (_this.actionManager) {
  7814. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7815. }
  7816. };
  7817. this._onKeyUp = function (evt) {
  7818. if (_this.actionManager) {
  7819. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7820. }
  7821. };
  7822. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7823. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7824. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7825. BABYLON.Tools.RegisterTopRootEvents([
  7826. { name: "keydown", handler: this._onKeyDown },
  7827. { name: "keyup", handler: this._onKeyUp }
  7828. ]);
  7829. };
  7830. Scene.prototype.detachControl = function () {
  7831. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7832. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7833. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7834. BABYLON.Tools.UnregisterTopRootEvents([
  7835. { name: "keydown", handler: this._onKeyDown },
  7836. { name: "keyup", handler: this._onKeyUp }
  7837. ]);
  7838. };
  7839. // Ready
  7840. Scene.prototype.isReady = function () {
  7841. if (this._pendingData.length > 0) {
  7842. return false;
  7843. }
  7844. for (var index = 0; index < this._geometries.length; index++) {
  7845. var geometry = this._geometries[index];
  7846. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7847. return false;
  7848. }
  7849. }
  7850. for (index = 0; index < this.meshes.length; index++) {
  7851. var mesh = this.meshes[index];
  7852. if (!mesh.isReady()) {
  7853. return false;
  7854. }
  7855. var mat = mesh.material;
  7856. if (mat) {
  7857. if (!mat.isReady(mesh)) {
  7858. return false;
  7859. }
  7860. }
  7861. }
  7862. return true;
  7863. };
  7864. Scene.prototype.resetCachedMaterial = function () {
  7865. this._cachedMaterial = null;
  7866. };
  7867. Scene.prototype.registerBeforeRender = function (func) {
  7868. this._onBeforeRenderCallbacks.push(func);
  7869. };
  7870. Scene.prototype.unregisterBeforeRender = function (func) {
  7871. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7872. if (index > -1) {
  7873. this._onBeforeRenderCallbacks.splice(index, 1);
  7874. }
  7875. };
  7876. Scene.prototype.registerAfterRender = function (func) {
  7877. this._onAfterRenderCallbacks.push(func);
  7878. };
  7879. Scene.prototype.unregisterAfterRender = function (func) {
  7880. var index = this._onAfterRenderCallbacks.indexOf(func);
  7881. if (index > -1) {
  7882. this._onAfterRenderCallbacks.splice(index, 1);
  7883. }
  7884. };
  7885. Scene.prototype._addPendingData = function (data) {
  7886. this._pendingData.push(data);
  7887. };
  7888. Scene.prototype._removePendingData = function (data) {
  7889. var index = this._pendingData.indexOf(data);
  7890. if (index !== -1) {
  7891. this._pendingData.splice(index, 1);
  7892. }
  7893. };
  7894. Scene.prototype.getWaitingItemsCount = function () {
  7895. return this._pendingData.length;
  7896. };
  7897. /**
  7898. * Registers a function to be executed when the scene is ready.
  7899. * @param {Function} func - the function to be executed.
  7900. */
  7901. Scene.prototype.executeWhenReady = function (func) {
  7902. var _this = this;
  7903. this._onReadyCallbacks.push(func);
  7904. if (this._executeWhenReadyTimeoutId !== -1) {
  7905. return;
  7906. }
  7907. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7908. _this._checkIsReady();
  7909. }, 150);
  7910. };
  7911. Scene.prototype._checkIsReady = function () {
  7912. var _this = this;
  7913. if (this.isReady()) {
  7914. this._onReadyCallbacks.forEach(function (func) {
  7915. func();
  7916. });
  7917. this._onReadyCallbacks = [];
  7918. this._executeWhenReadyTimeoutId = -1;
  7919. return;
  7920. }
  7921. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7922. _this._checkIsReady();
  7923. }, 150);
  7924. };
  7925. // Animations
  7926. /**
  7927. * Will start the animation sequence of a given target
  7928. * @param target - the target
  7929. * @param {number} from - from which frame should animation start
  7930. * @param {number} to - till which frame should animation run.
  7931. * @param {boolean} [loop] - should the animation loop
  7932. * @param {number} [speedRatio] - the speed in which to run the animation
  7933. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7934. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7935. * @return {BABYLON.Animatable} the animatable object created for this animation
  7936. * @see BABYLON.Animatable
  7937. * @see http://doc.babylonjs.com/page.php?p=22081
  7938. */
  7939. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7940. if (speedRatio === undefined) {
  7941. speedRatio = 1.0;
  7942. }
  7943. this.stopAnimation(target);
  7944. if (!animatable) {
  7945. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7946. }
  7947. // Local animations
  7948. if (target.animations) {
  7949. animatable.appendAnimations(target, target.animations);
  7950. }
  7951. // Children animations
  7952. if (target.getAnimatables) {
  7953. var animatables = target.getAnimatables();
  7954. for (var index = 0; index < animatables.length; index++) {
  7955. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7956. }
  7957. }
  7958. return animatable;
  7959. };
  7960. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7961. if (speedRatio === undefined) {
  7962. speedRatio = 1.0;
  7963. }
  7964. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7965. return animatable;
  7966. };
  7967. Scene.prototype.getAnimatableByTarget = function (target) {
  7968. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7969. if (this._activeAnimatables[index].target === target) {
  7970. return this._activeAnimatables[index];
  7971. }
  7972. }
  7973. return null;
  7974. };
  7975. /**
  7976. * Will stop the animation of the given target
  7977. * @param target - the target
  7978. * @see beginAnimation
  7979. */
  7980. Scene.prototype.stopAnimation = function (target) {
  7981. var animatable = this.getAnimatableByTarget(target);
  7982. if (animatable) {
  7983. animatable.stop();
  7984. }
  7985. };
  7986. Scene.prototype._animate = function () {
  7987. if (!this.animationsEnabled) {
  7988. return;
  7989. }
  7990. if (!this._animationStartDate) {
  7991. this._animationStartDate = BABYLON.Tools.Now;
  7992. }
  7993. // Getting time
  7994. var now = BABYLON.Tools.Now;
  7995. var delay = now - this._animationStartDate;
  7996. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7997. if (!this._activeAnimatables[index]._animate(delay)) {
  7998. this._activeAnimatables.splice(index, 1);
  7999. index--;
  8000. }
  8001. }
  8002. };
  8003. // Matrix
  8004. Scene.prototype.getViewMatrix = function () {
  8005. return this._viewMatrix;
  8006. };
  8007. Scene.prototype.getProjectionMatrix = function () {
  8008. return this._projectionMatrix;
  8009. };
  8010. Scene.prototype.getTransformMatrix = function () {
  8011. return this._transformMatrix;
  8012. };
  8013. Scene.prototype.setTransformMatrix = function (view, projection) {
  8014. this._viewMatrix = view;
  8015. this._projectionMatrix = projection;
  8016. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8017. };
  8018. // Methods
  8019. /**
  8020. * sets the active camera of the scene using its ID
  8021. * @param {string} id - the camera's ID
  8022. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8023. * @see activeCamera
  8024. */
  8025. Scene.prototype.setActiveCameraByID = function (id) {
  8026. var camera = this.getCameraByID(id);
  8027. if (camera) {
  8028. this.activeCamera = camera;
  8029. return camera;
  8030. }
  8031. return null;
  8032. };
  8033. /**
  8034. * sets the active camera of the scene using its name
  8035. * @param {string} name - the camera's name
  8036. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8037. * @see activeCamera
  8038. */
  8039. Scene.prototype.setActiveCameraByName = function (name) {
  8040. var camera = this.getCameraByName(name);
  8041. if (camera) {
  8042. this.activeCamera = camera;
  8043. return camera;
  8044. }
  8045. return null;
  8046. };
  8047. /**
  8048. * get a material using its id
  8049. * @param {string} the material's ID
  8050. * @return {BABYLON.Material|null} the material or null if none found.
  8051. */
  8052. Scene.prototype.getMaterialByID = function (id) {
  8053. for (var index = 0; index < this.materials.length; index++) {
  8054. if (this.materials[index].id === id) {
  8055. return this.materials[index];
  8056. }
  8057. }
  8058. return null;
  8059. };
  8060. /**
  8061. * get a material using its name
  8062. * @param {string} the material's name
  8063. * @return {BABYLON.Material|null} the material or null if none found.
  8064. */
  8065. Scene.prototype.getMaterialByName = function (name) {
  8066. for (var index = 0; index < this.materials.length; index++) {
  8067. if (this.materials[index].name === name) {
  8068. return this.materials[index];
  8069. }
  8070. }
  8071. return null;
  8072. };
  8073. Scene.prototype.getCameraByID = function (id) {
  8074. for (var index = 0; index < this.cameras.length; index++) {
  8075. if (this.cameras[index].id === id) {
  8076. return this.cameras[index];
  8077. }
  8078. }
  8079. return null;
  8080. };
  8081. /**
  8082. * get a camera using its name
  8083. * @param {string} the camera's name
  8084. * @return {BABYLON.Camera|null} the camera or null if none found.
  8085. */
  8086. Scene.prototype.getCameraByName = function (name) {
  8087. for (var index = 0; index < this.cameras.length; index++) {
  8088. if (this.cameras[index].name === name) {
  8089. return this.cameras[index];
  8090. }
  8091. }
  8092. return null;
  8093. };
  8094. /**
  8095. * get a light node using its name
  8096. * @param {string} the light's name
  8097. * @return {BABYLON.Light|null} the light or null if none found.
  8098. */
  8099. Scene.prototype.getLightByName = function (name) {
  8100. for (var index = 0; index < this.lights.length; index++) {
  8101. if (this.lights[index].name === name) {
  8102. return this.lights[index];
  8103. }
  8104. }
  8105. return null;
  8106. };
  8107. /**
  8108. * get a light node using its ID
  8109. * @param {string} the light's id
  8110. * @return {BABYLON.Light|null} the light or null if none found.
  8111. */
  8112. Scene.prototype.getLightByID = function (id) {
  8113. for (var index = 0; index < this.lights.length; index++) {
  8114. if (this.lights[index].id === id) {
  8115. return this.lights[index];
  8116. }
  8117. }
  8118. return null;
  8119. };
  8120. /**
  8121. * get a geometry using its ID
  8122. * @param {string} the geometry's id
  8123. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8124. */
  8125. Scene.prototype.getGeometryByID = function (id) {
  8126. for (var index = 0; index < this._geometries.length; index++) {
  8127. if (this._geometries[index].id === id) {
  8128. return this._geometries[index];
  8129. }
  8130. }
  8131. return null;
  8132. };
  8133. /**
  8134. * add a new geometry to this scene.
  8135. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8136. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8137. * @return {boolean} was the geometry added or not
  8138. */
  8139. Scene.prototype.pushGeometry = function (geometry, force) {
  8140. if (!force && this.getGeometryByID(geometry.id)) {
  8141. return false;
  8142. }
  8143. this._geometries.push(geometry);
  8144. return true;
  8145. };
  8146. Scene.prototype.getGeometries = function () {
  8147. return this._geometries;
  8148. };
  8149. /**
  8150. * Get a the first added mesh found of a given ID
  8151. * @param {string} id - the id to search for
  8152. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8153. */
  8154. Scene.prototype.getMeshByID = function (id) {
  8155. for (var index = 0; index < this.meshes.length; index++) {
  8156. if (this.meshes[index].id === id) {
  8157. return this.meshes[index];
  8158. }
  8159. }
  8160. return null;
  8161. };
  8162. /**
  8163. * Get a the last added mesh found of a given ID
  8164. * @param {string} id - the id to search for
  8165. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8166. */
  8167. Scene.prototype.getLastMeshByID = function (id) {
  8168. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8169. if (this.meshes[index].id === id) {
  8170. return this.meshes[index];
  8171. }
  8172. }
  8173. return null;
  8174. };
  8175. /**
  8176. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8177. * @param {string} id - the id to search for
  8178. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8179. */
  8180. Scene.prototype.getLastEntryByID = function (id) {
  8181. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8182. if (this.meshes[index].id === id) {
  8183. return this.meshes[index];
  8184. }
  8185. }
  8186. for (index = this.cameras.length - 1; index >= 0; index--) {
  8187. if (this.cameras[index].id === id) {
  8188. return this.cameras[index];
  8189. }
  8190. }
  8191. for (index = this.lights.length - 1; index >= 0; index--) {
  8192. if (this.lights[index].id === id) {
  8193. return this.lights[index];
  8194. }
  8195. }
  8196. return null;
  8197. };
  8198. Scene.prototype.getNodeByName = function (name) {
  8199. var mesh = this.getMeshByName(name);
  8200. if (mesh) {
  8201. return mesh;
  8202. }
  8203. var light = this.getLightByName(name);
  8204. if (light) {
  8205. return light;
  8206. }
  8207. return this.getCameraByName(name);
  8208. };
  8209. Scene.prototype.getMeshByName = function (name) {
  8210. for (var index = 0; index < this.meshes.length; index++) {
  8211. if (this.meshes[index].name === name) {
  8212. return this.meshes[index];
  8213. }
  8214. }
  8215. return null;
  8216. };
  8217. Scene.prototype.getSoundByName = function (name) {
  8218. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8219. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8220. return this.mainSoundTrack.soundCollection[index];
  8221. }
  8222. }
  8223. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8224. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8225. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8226. return this.soundTracks[sdIndex].soundCollection[index];
  8227. }
  8228. }
  8229. }
  8230. return null;
  8231. };
  8232. Scene.prototype.getLastSkeletonByID = function (id) {
  8233. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8234. if (this.skeletons[index].id === id) {
  8235. return this.skeletons[index];
  8236. }
  8237. }
  8238. return null;
  8239. };
  8240. Scene.prototype.getSkeletonById = function (id) {
  8241. for (var index = 0; index < this.skeletons.length; index++) {
  8242. if (this.skeletons[index].id === id) {
  8243. return this.skeletons[index];
  8244. }
  8245. }
  8246. return null;
  8247. };
  8248. Scene.prototype.getSkeletonByName = function (name) {
  8249. for (var index = 0; index < this.skeletons.length; index++) {
  8250. if (this.skeletons[index].name === name) {
  8251. return this.skeletons[index];
  8252. }
  8253. }
  8254. return null;
  8255. };
  8256. Scene.prototype.isActiveMesh = function (mesh) {
  8257. return (this._activeMeshes.indexOf(mesh) !== -1);
  8258. };
  8259. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8260. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8261. var material = subMesh.getMaterial();
  8262. if (mesh.showSubMeshesBoundingBox) {
  8263. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8264. }
  8265. if (material) {
  8266. // Render targets
  8267. if (material.getRenderTargetTextures) {
  8268. if (this._processedMaterials.indexOf(material) === -1) {
  8269. this._processedMaterials.push(material);
  8270. this._renderTargets.concat(material.getRenderTargetTextures());
  8271. }
  8272. }
  8273. // Dispatch
  8274. this._activeVertices += subMesh.indexCount;
  8275. this._renderingManager.dispatch(subMesh);
  8276. }
  8277. }
  8278. };
  8279. Scene.prototype._evaluateActiveMeshes = function () {
  8280. this._activeMeshes.reset();
  8281. this._renderingManager.reset();
  8282. this._processedMaterials.reset();
  8283. this._activeParticleSystems.reset();
  8284. this._activeSkeletons.reset();
  8285. this._boundingBoxRenderer.reset();
  8286. if (!this._frustumPlanes) {
  8287. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8288. }
  8289. else {
  8290. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8291. }
  8292. // Meshes
  8293. var meshes;
  8294. var len;
  8295. if (this._selectionOctree) {
  8296. var selection = this._selectionOctree.select(this._frustumPlanes);
  8297. meshes = selection.data;
  8298. len = selection.length;
  8299. }
  8300. else {
  8301. len = this.meshes.length;
  8302. meshes = this.meshes;
  8303. }
  8304. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8305. var mesh = meshes[meshIndex];
  8306. if (mesh.isBlocked) {
  8307. continue;
  8308. }
  8309. this._totalVertices += mesh.getTotalVertices();
  8310. if (!mesh.isReady()) {
  8311. continue;
  8312. }
  8313. mesh.computeWorldMatrix();
  8314. // Intersections
  8315. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8316. this._meshesForIntersections.pushNoDuplicate(mesh);
  8317. }
  8318. // Switch to current LOD
  8319. var meshLOD = mesh.getLOD(this.activeCamera);
  8320. if (!meshLOD) {
  8321. continue;
  8322. }
  8323. mesh._preActivate();
  8324. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8325. this._activeMeshes.push(mesh);
  8326. mesh._activate(this._renderId);
  8327. this._activeMesh(meshLOD);
  8328. }
  8329. }
  8330. // Particle systems
  8331. var beforeParticlesDate = BABYLON.Tools.Now;
  8332. if (this.particlesEnabled) {
  8333. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8334. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8335. var particleSystem = this.particleSystems[particleIndex];
  8336. if (!particleSystem.isStarted()) {
  8337. continue;
  8338. }
  8339. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8340. this._activeParticleSystems.push(particleSystem);
  8341. particleSystem.animate();
  8342. }
  8343. }
  8344. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8345. }
  8346. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8347. };
  8348. Scene.prototype._activeMesh = function (mesh) {
  8349. if (mesh.skeleton && this.skeletonsEnabled) {
  8350. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8351. }
  8352. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8353. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8354. }
  8355. if (mesh && mesh.subMeshes) {
  8356. // Submeshes Octrees
  8357. var len;
  8358. var subMeshes;
  8359. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8360. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8361. len = intersections.length;
  8362. subMeshes = intersections.data;
  8363. }
  8364. else {
  8365. subMeshes = mesh.subMeshes;
  8366. len = subMeshes.length;
  8367. }
  8368. for (var subIndex = 0; subIndex < len; subIndex++) {
  8369. var subMesh = subMeshes[subIndex];
  8370. this._evaluateSubMesh(subMesh, mesh);
  8371. }
  8372. }
  8373. };
  8374. Scene.prototype.updateTransformMatrix = function (force) {
  8375. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8376. };
  8377. Scene.prototype._renderForCamera = function (camera) {
  8378. var engine = this._engine;
  8379. this.activeCamera = camera;
  8380. if (!this.activeCamera)
  8381. throw new Error("Active camera not set");
  8382. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8383. // Viewport
  8384. engine.setViewport(this.activeCamera.viewport);
  8385. // Camera
  8386. this._renderId++;
  8387. this.updateTransformMatrix();
  8388. if (this.beforeCameraRender) {
  8389. this.beforeCameraRender(this.activeCamera);
  8390. }
  8391. // Meshes
  8392. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8393. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8394. this._evaluateActiveMeshes();
  8395. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8396. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8397. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8398. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8399. skeleton.prepare();
  8400. this._activeBones += skeleton.bones.length;
  8401. }
  8402. // Render targets
  8403. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8404. if (this.renderTargetsEnabled) {
  8405. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8406. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8407. var renderTarget = this._renderTargets.data[renderIndex];
  8408. if (renderTarget._shouldRender()) {
  8409. this._renderId++;
  8410. renderTarget.render();
  8411. }
  8412. }
  8413. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8414. this._renderId++;
  8415. }
  8416. if (this._renderTargets.length > 0) {
  8417. engine.restoreDefaultFramebuffer();
  8418. }
  8419. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8420. // Prepare Frame
  8421. this.postProcessManager._prepareFrame();
  8422. var beforeRenderDate = BABYLON.Tools.Now;
  8423. // Backgrounds
  8424. if (this.layers.length) {
  8425. engine.setDepthBuffer(false);
  8426. var layerIndex;
  8427. var layer;
  8428. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8429. layer = this.layers[layerIndex];
  8430. if (layer.isBackground) {
  8431. layer.render();
  8432. }
  8433. }
  8434. engine.setDepthBuffer(true);
  8435. }
  8436. // Render
  8437. BABYLON.Tools.StartPerformanceCounter("Main render");
  8438. this._renderingManager.render(null, null, true, true);
  8439. BABYLON.Tools.EndPerformanceCounter("Main render");
  8440. // Bounding boxes
  8441. this._boundingBoxRenderer.render();
  8442. // Lens flares
  8443. if (this.lensFlaresEnabled) {
  8444. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8445. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8446. this.lensFlareSystems[lensFlareSystemIndex].render();
  8447. }
  8448. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8449. }
  8450. // Foregrounds
  8451. if (this.layers.length) {
  8452. engine.setDepthBuffer(false);
  8453. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8454. layer = this.layers[layerIndex];
  8455. if (!layer.isBackground) {
  8456. layer.render();
  8457. }
  8458. }
  8459. engine.setDepthBuffer(true);
  8460. }
  8461. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8462. // Finalize frame
  8463. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8464. // Update camera
  8465. this.activeCamera._updateFromScene();
  8466. // Reset some special arrays
  8467. this._renderTargets.reset();
  8468. if (this.afterCameraRender) {
  8469. this.afterCameraRender(this.activeCamera);
  8470. }
  8471. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8472. };
  8473. Scene.prototype._processSubCameras = function (camera) {
  8474. if (camera.subCameras.length === 0) {
  8475. this._renderForCamera(camera);
  8476. return;
  8477. }
  8478. for (var index = 0; index < camera.subCameras.length; index++) {
  8479. this._renderForCamera(camera.subCameras[index]);
  8480. }
  8481. this.activeCamera = camera;
  8482. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8483. // Update camera
  8484. this.activeCamera._updateFromScene();
  8485. };
  8486. Scene.prototype._checkIntersections = function () {
  8487. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8488. var sourceMesh = this._meshesForIntersections.data[index];
  8489. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8490. var action = sourceMesh.actionManager.actions[actionIndex];
  8491. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8492. var parameters = action.getTriggerParameter();
  8493. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8494. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8495. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8496. if (areIntersecting && currentIntersectionInProgress === -1) {
  8497. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8498. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8499. sourceMesh._intersectionsInProgress.push(otherMesh);
  8500. }
  8501. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8502. sourceMesh._intersectionsInProgress.push(otherMesh);
  8503. }
  8504. }
  8505. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8506. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8507. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8508. if (indexOfOther > -1) {
  8509. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8510. }
  8511. }
  8512. }
  8513. }
  8514. }
  8515. };
  8516. Scene.prototype.render = function () {
  8517. var startDate = BABYLON.Tools.Now;
  8518. this._particlesDuration = 0;
  8519. this._spritesDuration = 0;
  8520. this._activeParticles = 0;
  8521. this._renderDuration = 0;
  8522. this._renderTargetsDuration = 0;
  8523. this._evaluateActiveMeshesDuration = 0;
  8524. this._totalVertices = 0;
  8525. this._activeVertices = 0;
  8526. this._activeBones = 0;
  8527. this.getEngine().resetDrawCalls();
  8528. this._meshesForIntersections.reset();
  8529. this.resetCachedMaterial();
  8530. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8531. // Actions
  8532. if (this.actionManager) {
  8533. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8534. }
  8535. // Before render
  8536. if (this.beforeRender) {
  8537. this.beforeRender();
  8538. }
  8539. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8540. this._onBeforeRenderCallbacks[callbackIndex]();
  8541. }
  8542. // Animations
  8543. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8544. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8545. this._animate();
  8546. // Physics
  8547. if (this._physicsEngine) {
  8548. BABYLON.Tools.StartPerformanceCounter("Physics");
  8549. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8550. BABYLON.Tools.EndPerformanceCounter("Physics");
  8551. }
  8552. // Customs render targets
  8553. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8554. var engine = this.getEngine();
  8555. if (this.renderTargetsEnabled) {
  8556. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8557. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8558. var renderTarget = this.customRenderTargets[customIndex];
  8559. if (renderTarget._shouldRender()) {
  8560. this._renderId++;
  8561. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8562. if (!this.activeCamera)
  8563. throw new Error("Active camera not set");
  8564. // Viewport
  8565. engine.setViewport(this.activeCamera.viewport);
  8566. // Camera
  8567. this.updateTransformMatrix();
  8568. renderTarget.render();
  8569. }
  8570. }
  8571. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8572. this._renderId++;
  8573. }
  8574. if (this.customRenderTargets.length > 0) {
  8575. engine.restoreDefaultFramebuffer();
  8576. }
  8577. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8578. // Procedural textures
  8579. if (this.proceduralTexturesEnabled) {
  8580. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8581. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8582. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8583. if (proceduralTexture._shouldRender()) {
  8584. proceduralTexture.render();
  8585. }
  8586. }
  8587. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8588. }
  8589. // Clear
  8590. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8591. // Shadows
  8592. if (this.shadowsEnabled) {
  8593. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8594. var light = this.lights[lightIndex];
  8595. var shadowGenerator = light.getShadowGenerator();
  8596. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8597. this._renderTargets.push(shadowGenerator.getShadowMap());
  8598. }
  8599. }
  8600. }
  8601. // Depth renderer
  8602. if (this._depthRenderer) {
  8603. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8604. }
  8605. // RenderPipeline
  8606. this.postProcessRenderPipelineManager.update();
  8607. // Multi-cameras?
  8608. if (this.activeCameras.length > 0) {
  8609. var currentRenderId = this._renderId;
  8610. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8611. this._renderId = currentRenderId;
  8612. this._processSubCameras(this.activeCameras[cameraIndex]);
  8613. }
  8614. }
  8615. else {
  8616. if (!this.activeCamera) {
  8617. throw new Error("No camera defined");
  8618. }
  8619. this._processSubCameras(this.activeCamera);
  8620. }
  8621. // Intersection checks
  8622. this._checkIntersections();
  8623. // Update the audio listener attached to the camera
  8624. this._updateAudioParameters();
  8625. // After render
  8626. if (this.afterRender) {
  8627. this.afterRender();
  8628. }
  8629. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8630. this._onAfterRenderCallbacks[callbackIndex]();
  8631. }
  8632. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8633. this._toBeDisposed.data[index].dispose();
  8634. this._toBeDisposed[index] = null;
  8635. }
  8636. this._toBeDisposed.reset();
  8637. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8638. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8639. };
  8640. Scene.prototype._updateAudioParameters = function () {
  8641. var listeningCamera;
  8642. var audioEngine = BABYLON.Engine.audioEngine;
  8643. if (this.activeCameras.length > 0) {
  8644. listeningCamera = this.activeCameras[0];
  8645. }
  8646. else {
  8647. listeningCamera = this.activeCamera;
  8648. }
  8649. if (listeningCamera && audioEngine.canUseWebAudio) {
  8650. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8651. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8652. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8653. cameraDirection.normalize();
  8654. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8655. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8656. var sound = this.mainSoundTrack.soundCollection[i];
  8657. if (sound.useCustomAttenuation) {
  8658. sound.updateDistanceFromListener();
  8659. }
  8660. }
  8661. for (i = 0; i < this.soundTracks.length; i++) {
  8662. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8663. sound = this.soundTracks[i].soundCollection[j];
  8664. if (sound.useCustomAttenuation) {
  8665. sound.updateDistanceFromListener();
  8666. }
  8667. }
  8668. }
  8669. }
  8670. };
  8671. Scene.prototype.enableDepthRenderer = function () {
  8672. if (this._depthRenderer) {
  8673. return this._depthRenderer;
  8674. }
  8675. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8676. return this._depthRenderer;
  8677. };
  8678. Scene.prototype.disableDepthRenderer = function () {
  8679. if (!this._depthRenderer) {
  8680. return;
  8681. }
  8682. this._depthRenderer.dispose();
  8683. this._depthRenderer = null;
  8684. };
  8685. Scene.prototype.dispose = function () {
  8686. this.beforeRender = null;
  8687. this.afterRender = null;
  8688. this.skeletons = [];
  8689. this._boundingBoxRenderer.dispose();
  8690. if (this._depthRenderer) {
  8691. this._depthRenderer.dispose();
  8692. }
  8693. // Debug layer
  8694. this.debugLayer.hide();
  8695. // Events
  8696. if (this.onDispose) {
  8697. this.onDispose();
  8698. }
  8699. this._onBeforeRenderCallbacks = [];
  8700. this._onAfterRenderCallbacks = [];
  8701. this.detachControl();
  8702. // Release sounds & sounds tracks
  8703. this.mainSoundTrack.dispose();
  8704. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8705. this.soundTracks[scIndex].dispose();
  8706. }
  8707. // Detach cameras
  8708. var canvas = this._engine.getRenderingCanvas();
  8709. var index;
  8710. for (index = 0; index < this.cameras.length; index++) {
  8711. this.cameras[index].detachControl(canvas);
  8712. }
  8713. while (this.lights.length) {
  8714. this.lights[0].dispose();
  8715. }
  8716. while (this.meshes.length) {
  8717. this.meshes[0].dispose(true);
  8718. }
  8719. while (this.cameras.length) {
  8720. this.cameras[0].dispose();
  8721. }
  8722. while (this.materials.length) {
  8723. this.materials[0].dispose();
  8724. }
  8725. while (this.particleSystems.length) {
  8726. this.particleSystems[0].dispose();
  8727. }
  8728. while (this.spriteManagers.length) {
  8729. this.spriteManagers[0].dispose();
  8730. }
  8731. while (this.layers.length) {
  8732. this.layers[0].dispose();
  8733. }
  8734. while (this.textures.length) {
  8735. this.textures[0].dispose();
  8736. }
  8737. // Post-processes
  8738. this.postProcessManager.dispose();
  8739. // Physics
  8740. if (this._physicsEngine) {
  8741. this.disablePhysicsEngine();
  8742. }
  8743. // Remove from engine
  8744. index = this._engine.scenes.indexOf(this);
  8745. if (index > -1) {
  8746. this._engine.scenes.splice(index, 1);
  8747. }
  8748. this._engine.wipeCaches();
  8749. };
  8750. // Collisions
  8751. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8752. if (excludedMesh === void 0) { excludedMesh = null; }
  8753. position.divideToRef(collider.radius, this._scaledPosition);
  8754. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8755. collider.retry = 0;
  8756. collider.initialVelocity = this._scaledVelocity;
  8757. collider.initialPosition = this._scaledPosition;
  8758. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8759. finalPosition.multiplyInPlace(collider.radius);
  8760. };
  8761. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8762. if (excludedMesh === void 0) { excludedMesh = null; }
  8763. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8764. if (collider.retry >= maximumRetry) {
  8765. finalPosition.copyFrom(position);
  8766. return;
  8767. }
  8768. collider._initialize(position, velocity, closeDistance);
  8769. for (var index = 0; index < this.meshes.length; index++) {
  8770. var mesh = this.meshes[index];
  8771. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8772. mesh._checkCollision(collider);
  8773. }
  8774. }
  8775. if (!collider.collisionFound) {
  8776. position.addToRef(velocity, finalPosition);
  8777. return;
  8778. }
  8779. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8780. collider._getResponse(position, velocity);
  8781. }
  8782. if (velocity.length() <= closeDistance) {
  8783. finalPosition.copyFrom(position);
  8784. return;
  8785. }
  8786. collider.retry++;
  8787. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8788. };
  8789. // Octrees
  8790. Scene.prototype.getWorldExtends = function () {
  8791. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8792. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8793. for (var index = 0; index < this.meshes.length; index++) {
  8794. var mesh = this.meshes[index];
  8795. mesh.computeWorldMatrix(true);
  8796. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8797. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8798. BABYLON.Tools.CheckExtends(minBox, min, max);
  8799. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8800. }
  8801. return {
  8802. min: min,
  8803. max: max
  8804. };
  8805. };
  8806. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8807. if (maxCapacity === void 0) { maxCapacity = 64; }
  8808. if (maxDepth === void 0) { maxDepth = 2; }
  8809. if (!this._selectionOctree) {
  8810. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8811. }
  8812. var worldExtends = this.getWorldExtends();
  8813. // Update octree
  8814. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8815. return this._selectionOctree;
  8816. };
  8817. // Picking
  8818. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8819. var engine = this._engine;
  8820. if (!camera) {
  8821. if (!this.activeCamera)
  8822. throw new Error("Active camera not set");
  8823. camera = this.activeCamera;
  8824. }
  8825. var cameraViewport = camera.viewport;
  8826. var viewport = cameraViewport.toGlobal(engine);
  8827. // Moving coordinates to local viewport world
  8828. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8829. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8830. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8831. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8832. };
  8833. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8834. var pickingInfo = null;
  8835. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8836. var mesh = this.meshes[meshIndex];
  8837. if (predicate) {
  8838. if (!predicate(mesh)) {
  8839. continue;
  8840. }
  8841. }
  8842. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8843. continue;
  8844. }
  8845. var world = mesh.getWorldMatrix();
  8846. var ray = rayFunction(world);
  8847. var result = mesh.intersects(ray, fastCheck);
  8848. if (!result || !result.hit)
  8849. continue;
  8850. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8851. continue;
  8852. pickingInfo = result;
  8853. if (fastCheck) {
  8854. break;
  8855. }
  8856. }
  8857. return pickingInfo || new BABYLON.PickingInfo();
  8858. };
  8859. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8860. var _this = this;
  8861. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8862. /// <param name="x">X position on screen</param>
  8863. /// <param name="y">Y position on screen</param>
  8864. /// <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>
  8865. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8866. /// <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>
  8867. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8868. };
  8869. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8870. var _this = this;
  8871. return this._internalPick(function (world) {
  8872. if (!_this._pickWithRayInverseMatrix) {
  8873. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8874. }
  8875. world.invertToRef(_this._pickWithRayInverseMatrix);
  8876. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8877. }, predicate, fastCheck);
  8878. };
  8879. Scene.prototype.setPointerOverMesh = function (mesh) {
  8880. if (this._pointerOverMesh === mesh) {
  8881. return;
  8882. }
  8883. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8884. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8885. }
  8886. this._pointerOverMesh = mesh;
  8887. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8888. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8889. }
  8890. };
  8891. Scene.prototype.getPointerOverMesh = function () {
  8892. return this._pointerOverMesh;
  8893. };
  8894. // Physics
  8895. Scene.prototype.getPhysicsEngine = function () {
  8896. return this._physicsEngine;
  8897. };
  8898. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8899. if (this._physicsEngine) {
  8900. return true;
  8901. }
  8902. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8903. if (!this._physicsEngine.isSupported()) {
  8904. this._physicsEngine = null;
  8905. return false;
  8906. }
  8907. this._physicsEngine._initialize(gravity);
  8908. return true;
  8909. };
  8910. Scene.prototype.disablePhysicsEngine = function () {
  8911. if (!this._physicsEngine) {
  8912. return;
  8913. }
  8914. this._physicsEngine.dispose();
  8915. this._physicsEngine = undefined;
  8916. };
  8917. Scene.prototype.isPhysicsEnabled = function () {
  8918. return this._physicsEngine !== undefined;
  8919. };
  8920. Scene.prototype.setGravity = function (gravity) {
  8921. if (!this._physicsEngine) {
  8922. return;
  8923. }
  8924. this._physicsEngine._setGravity(gravity);
  8925. };
  8926. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8927. if (parts.parts) {
  8928. options = parts;
  8929. parts = parts.parts;
  8930. }
  8931. if (!this._physicsEngine) {
  8932. return null;
  8933. }
  8934. for (var index = 0; index < parts.length; index++) {
  8935. var mesh = parts[index].mesh;
  8936. mesh._physicImpostor = parts[index].impostor;
  8937. mesh._physicsMass = options.mass / parts.length;
  8938. mesh._physicsFriction = options.friction;
  8939. mesh._physicRestitution = options.restitution;
  8940. }
  8941. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8942. };
  8943. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8944. for (var index = 0; index < compound.parts.length; index++) {
  8945. var mesh = compound.parts[index].mesh;
  8946. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8947. this._physicsEngine._unregisterMesh(mesh);
  8948. }
  8949. };
  8950. // Misc.
  8951. Scene.prototype.createDefaultCameraOrLight = function () {
  8952. // Light
  8953. if (this.lights.length === 0) {
  8954. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8955. }
  8956. // Camera
  8957. if (!this.activeCamera) {
  8958. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8959. // Compute position
  8960. var worldExtends = this.getWorldExtends();
  8961. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8962. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8963. camera.setTarget(worldCenter);
  8964. this.activeCamera = camera;
  8965. }
  8966. };
  8967. // Tags
  8968. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8969. if (tagsQuery === undefined) {
  8970. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8971. return list;
  8972. }
  8973. var listByTags = [];
  8974. forEach = forEach || (function (item) {
  8975. return;
  8976. });
  8977. for (var i in list) {
  8978. var item = list[i];
  8979. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8980. listByTags.push(item);
  8981. forEach(item);
  8982. }
  8983. }
  8984. return listByTags;
  8985. };
  8986. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8987. return this._getByTags(this.meshes, tagsQuery, forEach);
  8988. };
  8989. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8990. return this._getByTags(this.cameras, tagsQuery, forEach);
  8991. };
  8992. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8993. return this._getByTags(this.lights, tagsQuery, forEach);
  8994. };
  8995. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8996. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8997. };
  8998. // Statics
  8999. Scene._FOGMODE_NONE = 0;
  9000. Scene._FOGMODE_EXP = 1;
  9001. Scene._FOGMODE_EXP2 = 2;
  9002. Scene._FOGMODE_LINEAR = 3;
  9003. Scene.MinDeltaTime = 1.0;
  9004. Scene.MaxDeltaTime = 1000.0;
  9005. return Scene;
  9006. })();
  9007. BABYLON.Scene = Scene;
  9008. })(BABYLON || (BABYLON = {}));
  9009. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9010. (function (BABYLON) {
  9011. var VertexBuffer = (function () {
  9012. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9013. if (engine instanceof BABYLON.Mesh) {
  9014. this._engine = engine.getScene().getEngine();
  9015. }
  9016. else {
  9017. this._engine = engine;
  9018. }
  9019. this._updatable = updatable;
  9020. this._data = data;
  9021. if (!postponeInternalCreation) {
  9022. this.create();
  9023. }
  9024. this._kind = kind;
  9025. if (stride) {
  9026. this._strideSize = stride;
  9027. return;
  9028. }
  9029. switch (kind) {
  9030. case VertexBuffer.PositionKind:
  9031. this._strideSize = 3;
  9032. break;
  9033. case VertexBuffer.NormalKind:
  9034. this._strideSize = 3;
  9035. break;
  9036. case VertexBuffer.UVKind:
  9037. this._strideSize = 2;
  9038. break;
  9039. case VertexBuffer.UV2Kind:
  9040. this._strideSize = 2;
  9041. break;
  9042. case VertexBuffer.ColorKind:
  9043. this._strideSize = 4;
  9044. break;
  9045. case VertexBuffer.MatricesIndicesKind:
  9046. this._strideSize = 4;
  9047. break;
  9048. case VertexBuffer.MatricesWeightsKind:
  9049. this._strideSize = 4;
  9050. break;
  9051. }
  9052. }
  9053. // Properties
  9054. VertexBuffer.prototype.isUpdatable = function () {
  9055. return this._updatable;
  9056. };
  9057. VertexBuffer.prototype.getData = function () {
  9058. return this._data;
  9059. };
  9060. VertexBuffer.prototype.getBuffer = function () {
  9061. return this._buffer;
  9062. };
  9063. VertexBuffer.prototype.getStrideSize = function () {
  9064. return this._strideSize;
  9065. };
  9066. // Methods
  9067. VertexBuffer.prototype.create = function (data) {
  9068. if (!data && this._buffer) {
  9069. return; // nothing to do
  9070. }
  9071. data = data || this._data;
  9072. if (!this._buffer) {
  9073. if (this._updatable) {
  9074. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9075. }
  9076. else {
  9077. this._buffer = this._engine.createVertexBuffer(data);
  9078. }
  9079. }
  9080. if (this._updatable) {
  9081. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9082. this._data = data;
  9083. }
  9084. };
  9085. VertexBuffer.prototype.update = function (data) {
  9086. this.create(data);
  9087. };
  9088. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9089. if (!this._buffer) {
  9090. return;
  9091. }
  9092. if (this._updatable) {
  9093. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9094. this._data = null;
  9095. }
  9096. };
  9097. VertexBuffer.prototype.dispose = function () {
  9098. if (!this._buffer) {
  9099. return;
  9100. }
  9101. if (this._engine._releaseBuffer(this._buffer)) {
  9102. this._buffer = null;
  9103. }
  9104. };
  9105. Object.defineProperty(VertexBuffer, "PositionKind", {
  9106. get: function () {
  9107. return VertexBuffer._PositionKind;
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. Object.defineProperty(VertexBuffer, "NormalKind", {
  9113. get: function () {
  9114. return VertexBuffer._NormalKind;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(VertexBuffer, "UVKind", {
  9120. get: function () {
  9121. return VertexBuffer._UVKind;
  9122. },
  9123. enumerable: true,
  9124. configurable: true
  9125. });
  9126. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9127. get: function () {
  9128. return VertexBuffer._UV2Kind;
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(VertexBuffer, "ColorKind", {
  9134. get: function () {
  9135. return VertexBuffer._ColorKind;
  9136. },
  9137. enumerable: true,
  9138. configurable: true
  9139. });
  9140. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9141. get: function () {
  9142. return VertexBuffer._MatricesIndicesKind;
  9143. },
  9144. enumerable: true,
  9145. configurable: true
  9146. });
  9147. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9148. get: function () {
  9149. return VertexBuffer._MatricesWeightsKind;
  9150. },
  9151. enumerable: true,
  9152. configurable: true
  9153. });
  9154. // Enums
  9155. VertexBuffer._PositionKind = "position";
  9156. VertexBuffer._NormalKind = "normal";
  9157. VertexBuffer._UVKind = "uv";
  9158. VertexBuffer._UV2Kind = "uv2";
  9159. VertexBuffer._ColorKind = "color";
  9160. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9161. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9162. return VertexBuffer;
  9163. })();
  9164. BABYLON.VertexBuffer = VertexBuffer;
  9165. })(BABYLON || (BABYLON = {}));
  9166. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9167. var BABYLON;
  9168. (function (BABYLON) {
  9169. var AbstractMesh = (function (_super) {
  9170. __extends(AbstractMesh, _super);
  9171. function AbstractMesh(name, scene) {
  9172. _super.call(this, name, scene);
  9173. // Properties
  9174. this.definedFacingForward = true; // orientation for POV movement & rotation
  9175. this.position = new BABYLON.Vector3(0, 0, 0);
  9176. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9177. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9178. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9179. this.visibility = 1.0;
  9180. this.alphaIndex = Number.MAX_VALUE;
  9181. this.infiniteDistance = false;
  9182. this.isVisible = true;
  9183. this.isPickable = true;
  9184. this.showBoundingBox = false;
  9185. this.showSubMeshesBoundingBox = false;
  9186. this.onDispose = null;
  9187. this.checkCollisions = false;
  9188. this.isBlocker = false;
  9189. this.renderingGroupId = 0;
  9190. this.receiveShadows = false;
  9191. this.renderOutline = false;
  9192. this.outlineColor = BABYLON.Color3.Red();
  9193. this.outlineWidth = 0.02;
  9194. this.renderOverlay = false;
  9195. this.overlayColor = BABYLON.Color3.Red();
  9196. this.overlayAlpha = 0.5;
  9197. this.hasVertexAlpha = false;
  9198. this.useVertexColors = true;
  9199. this.applyFog = true;
  9200. this.useOctreeForRenderingSelection = true;
  9201. this.useOctreeForPicking = true;
  9202. this.useOctreeForCollisions = true;
  9203. this.layerMask = 0xFFFFFFFF;
  9204. // Physics
  9205. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9206. // Collisions
  9207. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9208. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9209. this._collider = new BABYLON.Collider();
  9210. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9211. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9212. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9213. // Cache
  9214. this._localScaling = BABYLON.Matrix.Zero();
  9215. this._localRotation = BABYLON.Matrix.Zero();
  9216. this._localTranslation = BABYLON.Matrix.Zero();
  9217. this._localBillboard = BABYLON.Matrix.Zero();
  9218. this._localPivotScaling = BABYLON.Matrix.Zero();
  9219. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9220. this._localWorld = BABYLON.Matrix.Zero();
  9221. this._worldMatrix = BABYLON.Matrix.Zero();
  9222. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9223. this._absolutePosition = BABYLON.Vector3.Zero();
  9224. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9225. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9226. this._isDirty = false;
  9227. this._pivotMatrix = BABYLON.Matrix.Identity();
  9228. this._isDisposed = false;
  9229. this._renderId = 0;
  9230. this._intersectionsInProgress = new Array();
  9231. this._onAfterWorldMatrixUpdate = new Array();
  9232. scene.meshes.push(this);
  9233. }
  9234. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9235. get: function () {
  9236. return AbstractMesh._BILLBOARDMODE_NONE;
  9237. },
  9238. enumerable: true,
  9239. configurable: true
  9240. });
  9241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9242. get: function () {
  9243. return AbstractMesh._BILLBOARDMODE_X;
  9244. },
  9245. enumerable: true,
  9246. configurable: true
  9247. });
  9248. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9249. get: function () {
  9250. return AbstractMesh._BILLBOARDMODE_Y;
  9251. },
  9252. enumerable: true,
  9253. configurable: true
  9254. });
  9255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9256. get: function () {
  9257. return AbstractMesh._BILLBOARDMODE_Z;
  9258. },
  9259. enumerable: true,
  9260. configurable: true
  9261. });
  9262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9263. get: function () {
  9264. return AbstractMesh._BILLBOARDMODE_ALL;
  9265. },
  9266. enumerable: true,
  9267. configurable: true
  9268. });
  9269. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9270. // Methods
  9271. get: function () {
  9272. return false;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. AbstractMesh.prototype.getLOD = function (camera) {
  9278. return this;
  9279. };
  9280. AbstractMesh.prototype.getTotalVertices = function () {
  9281. return 0;
  9282. };
  9283. AbstractMesh.prototype.getIndices = function () {
  9284. return null;
  9285. };
  9286. AbstractMesh.prototype.getVerticesData = function (kind) {
  9287. return null;
  9288. };
  9289. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9290. return false;
  9291. };
  9292. AbstractMesh.prototype.getBoundingInfo = function () {
  9293. if (this._masterMesh) {
  9294. return this._masterMesh.getBoundingInfo();
  9295. }
  9296. if (!this._boundingInfo) {
  9297. this._updateBoundingInfo();
  9298. }
  9299. return this._boundingInfo;
  9300. };
  9301. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9302. get: function () {
  9303. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. AbstractMesh.prototype._preActivate = function () {
  9309. };
  9310. AbstractMesh.prototype._activate = function (renderId) {
  9311. this._renderId = renderId;
  9312. };
  9313. AbstractMesh.prototype.getWorldMatrix = function () {
  9314. if (this._masterMesh) {
  9315. return this._masterMesh.getWorldMatrix();
  9316. }
  9317. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9318. this.computeWorldMatrix();
  9319. }
  9320. return this._worldMatrix;
  9321. };
  9322. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9323. get: function () {
  9324. return this._worldMatrix;
  9325. },
  9326. enumerable: true,
  9327. configurable: true
  9328. });
  9329. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9330. get: function () {
  9331. return this._absolutePosition;
  9332. },
  9333. enumerable: true,
  9334. configurable: true
  9335. });
  9336. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9337. if (!this.rotationQuaternion) {
  9338. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9339. this.rotation = BABYLON.Vector3.Zero();
  9340. }
  9341. if (!space || space == 0 /* LOCAL */) {
  9342. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9343. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9344. }
  9345. else {
  9346. if (this.parent) {
  9347. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9348. invertParentWorldMatrix.invert();
  9349. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9350. }
  9351. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9352. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9353. }
  9354. };
  9355. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9356. var displacementVector = axis.scale(distance);
  9357. if (!space || space == 0 /* LOCAL */) {
  9358. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9359. this.setPositionWithLocalVector(tempV3);
  9360. }
  9361. else {
  9362. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9363. }
  9364. };
  9365. AbstractMesh.prototype.getAbsolutePosition = function () {
  9366. this.computeWorldMatrix();
  9367. return this._absolutePosition;
  9368. };
  9369. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9370. if (!absolutePosition) {
  9371. return;
  9372. }
  9373. var absolutePositionX;
  9374. var absolutePositionY;
  9375. var absolutePositionZ;
  9376. if (absolutePosition.x === undefined) {
  9377. if (arguments.length < 3) {
  9378. return;
  9379. }
  9380. absolutePositionX = arguments[0];
  9381. absolutePositionY = arguments[1];
  9382. absolutePositionZ = arguments[2];
  9383. }
  9384. else {
  9385. absolutePositionX = absolutePosition.x;
  9386. absolutePositionY = absolutePosition.y;
  9387. absolutePositionZ = absolutePosition.z;
  9388. }
  9389. if (this.parent) {
  9390. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9391. invertParentWorldMatrix.invert();
  9392. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9393. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9394. }
  9395. else {
  9396. this.position.x = absolutePositionX;
  9397. this.position.y = absolutePositionY;
  9398. this.position.z = absolutePositionZ;
  9399. }
  9400. };
  9401. // ================================== Point of View Movement =================================
  9402. /**
  9403. * Perform relative position change from the point of view of behind the front of the mesh.
  9404. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9405. * Supports definition of mesh facing forward or backward.
  9406. * @param {number} amountRight
  9407. * @param {number} amountUp
  9408. * @param {number} amountForward
  9409. */
  9410. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9411. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9412. };
  9413. /**
  9414. * Calculate relative position change from the point of view of behind the front of the mesh.
  9415. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9416. * Supports definition of mesh facing forward or backward.
  9417. * @param {number} amountRight
  9418. * @param {number} amountUp
  9419. * @param {number} amountForward
  9420. */
  9421. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9422. var rotMatrix = new BABYLON.Matrix();
  9423. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9424. rotQuaternion.toRotationMatrix(rotMatrix);
  9425. var translationDelta = BABYLON.Vector3.Zero();
  9426. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9428. return translationDelta;
  9429. };
  9430. // ================================== Point of View Rotation =================================
  9431. /**
  9432. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9433. * Supports definition of mesh facing forward or backward.
  9434. * @param {number} flipBack
  9435. * @param {number} twirlClockwise
  9436. * @param {number} tiltRight
  9437. */
  9438. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9439. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9440. };
  9441. /**
  9442. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9443. * Supports definition of mesh facing forward or backward.
  9444. * @param {number} flipBack
  9445. * @param {number} twirlClockwise
  9446. * @param {number} tiltRight
  9447. */
  9448. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9449. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9450. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9451. };
  9452. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9453. this._pivotMatrix = matrix;
  9454. this._cache.pivotMatrixUpdated = true;
  9455. };
  9456. AbstractMesh.prototype.getPivotMatrix = function () {
  9457. return this._pivotMatrix;
  9458. };
  9459. AbstractMesh.prototype._isSynchronized = function () {
  9460. if (this._isDirty) {
  9461. return false;
  9462. }
  9463. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9464. return false;
  9465. if (this._cache.pivotMatrixUpdated) {
  9466. return false;
  9467. }
  9468. if (this.infiniteDistance) {
  9469. return false;
  9470. }
  9471. if (!this._cache.position.equals(this.position))
  9472. return false;
  9473. if (this.rotationQuaternion) {
  9474. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9475. return false;
  9476. }
  9477. else {
  9478. if (!this._cache.rotation.equals(this.rotation))
  9479. return false;
  9480. }
  9481. if (!this._cache.scaling.equals(this.scaling))
  9482. return false;
  9483. return true;
  9484. };
  9485. AbstractMesh.prototype._initCache = function () {
  9486. _super.prototype._initCache.call(this);
  9487. this._cache.localMatrixUpdated = false;
  9488. this._cache.position = BABYLON.Vector3.Zero();
  9489. this._cache.scaling = BABYLON.Vector3.Zero();
  9490. this._cache.rotation = BABYLON.Vector3.Zero();
  9491. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9492. };
  9493. AbstractMesh.prototype.markAsDirty = function (property) {
  9494. if (property === "rotation") {
  9495. this.rotationQuaternion = null;
  9496. }
  9497. this._currentRenderId = Number.MAX_VALUE;
  9498. this._isDirty = true;
  9499. };
  9500. AbstractMesh.prototype._updateBoundingInfo = function () {
  9501. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9502. this._boundingInfo._update(this.worldMatrixFromCache);
  9503. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9504. };
  9505. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9506. if (!this.subMeshes) {
  9507. return;
  9508. }
  9509. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9510. var subMesh = this.subMeshes[subIndex];
  9511. subMesh.updateBoundingInfo(matrix);
  9512. }
  9513. };
  9514. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9515. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9516. return this._worldMatrix;
  9517. }
  9518. this._cache.position.copyFrom(this.position);
  9519. this._cache.scaling.copyFrom(this.scaling);
  9520. this._cache.pivotMatrixUpdated = false;
  9521. this._currentRenderId = this.getScene().getRenderId();
  9522. this._isDirty = false;
  9523. // Scaling
  9524. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9525. // Rotation
  9526. if (this.rotationQuaternion) {
  9527. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9528. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9529. }
  9530. else {
  9531. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9532. this._cache.rotation.copyFrom(this.rotation);
  9533. }
  9534. // Translation
  9535. if (this.infiniteDistance && !this.parent) {
  9536. var camera = this.getScene().activeCamera;
  9537. var cameraWorldMatrix = camera.getWorldMatrix();
  9538. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9539. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9540. }
  9541. else {
  9542. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9543. }
  9544. // Composing transformations
  9545. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9546. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9547. // Billboarding
  9548. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9549. var localPosition = this.position.clone();
  9550. var zero = this.getScene().activeCamera.position.clone();
  9551. if (this.parent && this.parent.position) {
  9552. localPosition.addInPlace(this.parent.position);
  9553. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9554. }
  9555. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9556. zero = this.getScene().activeCamera.position;
  9557. }
  9558. else {
  9559. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9560. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9561. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9562. zero.y = localPosition.y + 0.001;
  9563. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9564. zero.z = localPosition.z + 0.001;
  9565. }
  9566. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9567. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9568. this._localBillboard.invert();
  9569. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9570. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9571. }
  9572. // Local world
  9573. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9574. // Parent
  9575. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9576. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9577. }
  9578. else {
  9579. this._worldMatrix.copyFrom(this._localWorld);
  9580. }
  9581. // Bounding info
  9582. this._updateBoundingInfo();
  9583. // Absolute position
  9584. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9585. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9586. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9587. }
  9588. return this._worldMatrix;
  9589. };
  9590. /**
  9591. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9592. * @param func: callback function to add
  9593. */
  9594. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9595. this._onAfterWorldMatrixUpdate.push(func);
  9596. };
  9597. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9598. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9599. if (index > -1) {
  9600. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9601. }
  9602. };
  9603. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9604. this.computeWorldMatrix();
  9605. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9606. };
  9607. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9608. this.computeWorldMatrix();
  9609. var invLocalWorldMatrix = this._localWorld.clone();
  9610. invLocalWorldMatrix.invert();
  9611. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9612. };
  9613. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9614. this.computeWorldMatrix();
  9615. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9616. };
  9617. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9618. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9619. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9620. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9621. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9622. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9623. /// <returns>Mesh oriented towards targetMesh</returns>
  9624. yawCor = yawCor || 0; // default to zero if undefined
  9625. pitchCor = pitchCor || 0;
  9626. rollCor = rollCor || 0;
  9627. var dv = targetPoint.subtract(this.position);
  9628. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9629. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9630. var pitch = Math.atan2(dv.y, len);
  9631. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9632. };
  9633. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9634. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9635. return false;
  9636. }
  9637. return true;
  9638. };
  9639. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9640. if (!camera) {
  9641. camera = this.getScene().activeCamera;
  9642. }
  9643. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9644. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9645. return false;
  9646. }
  9647. return true;
  9648. };
  9649. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9650. if (!this._boundingInfo || !mesh._boundingInfo) {
  9651. return false;
  9652. }
  9653. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9654. };
  9655. AbstractMesh.prototype.intersectsPoint = function (point) {
  9656. if (!this._boundingInfo) {
  9657. return false;
  9658. }
  9659. return this._boundingInfo.intersectsPoint(point);
  9660. };
  9661. // Physics
  9662. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9663. var physicsEngine = this.getScene().getPhysicsEngine();
  9664. if (!physicsEngine) {
  9665. return;
  9666. }
  9667. if (impostor.impostor) {
  9668. // Old API
  9669. options = impostor;
  9670. impostor = impostor.impostor;
  9671. }
  9672. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9673. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9674. physicsEngine._unregisterMesh(this);
  9675. return;
  9676. }
  9677. options.mass = options.mass || 0;
  9678. options.friction = options.friction || 0.2;
  9679. options.restitution = options.restitution || 0.2;
  9680. this._physicImpostor = impostor;
  9681. this._physicsMass = options.mass;
  9682. this._physicsFriction = options.friction;
  9683. this._physicRestitution = options.restitution;
  9684. return physicsEngine._registerMesh(this, impostor, options);
  9685. };
  9686. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9687. if (!this._physicImpostor) {
  9688. return BABYLON.PhysicsEngine.NoImpostor;
  9689. }
  9690. return this._physicImpostor;
  9691. };
  9692. AbstractMesh.prototype.getPhysicsMass = function () {
  9693. if (!this._physicsMass) {
  9694. return 0;
  9695. }
  9696. return this._physicsMass;
  9697. };
  9698. AbstractMesh.prototype.getPhysicsFriction = function () {
  9699. if (!this._physicsFriction) {
  9700. return 0;
  9701. }
  9702. return this._physicsFriction;
  9703. };
  9704. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9705. if (!this._physicRestitution) {
  9706. return 0;
  9707. }
  9708. return this._physicRestitution;
  9709. };
  9710. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9711. if (!camera) {
  9712. camera = this.getScene().activeCamera;
  9713. }
  9714. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9715. };
  9716. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9717. if (!camera) {
  9718. camera = this.getScene().activeCamera;
  9719. }
  9720. return this.absolutePosition.subtract(camera.position).length();
  9721. };
  9722. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9723. if (!this._physicImpostor) {
  9724. return;
  9725. }
  9726. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9727. };
  9728. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9729. if (!this._physicImpostor) {
  9730. return;
  9731. }
  9732. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9733. };
  9734. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9735. if (!this._physicImpostor) {
  9736. return;
  9737. }
  9738. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9739. };
  9740. // Collisions
  9741. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9742. var globalPosition = this.getAbsolutePosition();
  9743. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9744. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9745. this._collider.radius = this.ellipsoid;
  9746. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9747. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9748. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9749. this.position.addInPlace(this._diffPositionForCollisions);
  9750. }
  9751. };
  9752. // Submeshes octree
  9753. /**
  9754. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9755. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9756. */
  9757. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9758. if (maxCapacity === void 0) { maxCapacity = 64; }
  9759. if (maxDepth === void 0) { maxDepth = 2; }
  9760. if (!this._submeshesOctree) {
  9761. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9762. }
  9763. this.computeWorldMatrix(true);
  9764. // Update octree
  9765. var bbox = this.getBoundingInfo().boundingBox;
  9766. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9767. return this._submeshesOctree;
  9768. };
  9769. // Collisions
  9770. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9771. this._generatePointsArray();
  9772. // Transformation
  9773. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9774. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9775. subMesh._lastColliderWorldVertices = [];
  9776. subMesh._trianglePlanes = [];
  9777. var start = subMesh.verticesStart;
  9778. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9779. for (var i = start; i < end; i++) {
  9780. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9781. }
  9782. }
  9783. // Collide
  9784. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9785. };
  9786. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9787. var subMeshes;
  9788. var len;
  9789. // Octrees
  9790. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9791. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9792. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9793. len = intersections.length;
  9794. subMeshes = intersections.data;
  9795. }
  9796. else {
  9797. subMeshes = this.subMeshes;
  9798. len = subMeshes.length;
  9799. }
  9800. for (var index = 0; index < len; index++) {
  9801. var subMesh = subMeshes[index];
  9802. // Bounding test
  9803. if (len > 1 && !subMesh._checkCollision(collider))
  9804. continue;
  9805. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9806. }
  9807. };
  9808. AbstractMesh.prototype._checkCollision = function (collider) {
  9809. // Bounding box test
  9810. if (!this._boundingInfo._checkCollision(collider))
  9811. return;
  9812. // Transformation matrix
  9813. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9814. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9815. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9816. };
  9817. // Picking
  9818. AbstractMesh.prototype._generatePointsArray = function () {
  9819. return false;
  9820. };
  9821. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9822. var pickingInfo = new BABYLON.PickingInfo();
  9823. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9824. return pickingInfo;
  9825. }
  9826. if (!this._generatePointsArray()) {
  9827. return pickingInfo;
  9828. }
  9829. var intersectInfo = null;
  9830. // Octrees
  9831. var subMeshes;
  9832. var len;
  9833. if (this._submeshesOctree && this.useOctreeForPicking) {
  9834. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9835. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9836. len = intersections.length;
  9837. subMeshes = intersections.data;
  9838. }
  9839. else {
  9840. subMeshes = this.subMeshes;
  9841. len = subMeshes.length;
  9842. }
  9843. for (var index = 0; index < len; index++) {
  9844. var subMesh = subMeshes[index];
  9845. // Bounding test
  9846. if (len > 1 && !subMesh.canIntersects(ray))
  9847. continue;
  9848. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9849. if (currentIntersectInfo) {
  9850. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9851. intersectInfo = currentIntersectInfo;
  9852. if (fastCheck) {
  9853. break;
  9854. }
  9855. }
  9856. }
  9857. }
  9858. if (intersectInfo) {
  9859. // Get picked point
  9860. var world = this.getWorldMatrix();
  9861. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9862. var direction = ray.direction.clone();
  9863. direction = direction.scale(intersectInfo.distance);
  9864. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9865. var pickedPoint = worldOrigin.add(worldDirection);
  9866. // Return result
  9867. pickingInfo.hit = true;
  9868. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9869. pickingInfo.pickedPoint = pickedPoint;
  9870. pickingInfo.pickedMesh = this;
  9871. pickingInfo.bu = intersectInfo.bu;
  9872. pickingInfo.bv = intersectInfo.bv;
  9873. pickingInfo.faceId = intersectInfo.faceId;
  9874. return pickingInfo;
  9875. }
  9876. return pickingInfo;
  9877. };
  9878. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9879. return null;
  9880. };
  9881. AbstractMesh.prototype.releaseSubMeshes = function () {
  9882. if (this.subMeshes) {
  9883. while (this.subMeshes.length) {
  9884. this.subMeshes[0].dispose();
  9885. }
  9886. }
  9887. else {
  9888. this.subMeshes = new Array();
  9889. }
  9890. };
  9891. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9892. // Physics
  9893. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9894. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9895. }
  9896. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9897. var other = this._intersectionsInProgress[index];
  9898. var pos = other._intersectionsInProgress.indexOf(this);
  9899. other._intersectionsInProgress.splice(pos, 1);
  9900. }
  9901. this._intersectionsInProgress = [];
  9902. // SubMeshes
  9903. this.releaseSubMeshes();
  9904. // Remove from scene
  9905. var index = this.getScene().meshes.indexOf(this);
  9906. if (index != -1) {
  9907. // Remove from the scene if mesh found
  9908. this.getScene().meshes.splice(index, 1);
  9909. }
  9910. if (!doNotRecurse) {
  9911. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9912. if (this.getScene().particleSystems[index].emitter == this) {
  9913. this.getScene().particleSystems[index].dispose();
  9914. index--;
  9915. }
  9916. }
  9917. // Children
  9918. var objects = this.getScene().meshes.slice(0);
  9919. for (index = 0; index < objects.length; index++) {
  9920. if (objects[index].parent == this) {
  9921. objects[index].dispose();
  9922. }
  9923. }
  9924. }
  9925. else {
  9926. for (index = 0; index < this.getScene().meshes.length; index++) {
  9927. var obj = this.getScene().meshes[index];
  9928. if (obj.parent === this) {
  9929. obj.parent = null;
  9930. obj.computeWorldMatrix(true);
  9931. }
  9932. }
  9933. }
  9934. this._onAfterWorldMatrixUpdate = [];
  9935. this._isDisposed = true;
  9936. // Callback
  9937. if (this.onDispose) {
  9938. this.onDispose();
  9939. }
  9940. };
  9941. // Statics
  9942. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9943. AbstractMesh._BILLBOARDMODE_X = 1;
  9944. AbstractMesh._BILLBOARDMODE_Y = 2;
  9945. AbstractMesh._BILLBOARDMODE_Z = 4;
  9946. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9947. return AbstractMesh;
  9948. })(BABYLON.Node);
  9949. BABYLON.AbstractMesh = AbstractMesh;
  9950. })(BABYLON || (BABYLON = {}));
  9951. //# sourceMappingURL=babylon.abstractMesh.js.map
  9952. var BABYLON;
  9953. (function (BABYLON) {
  9954. var _InstancesBatch = (function () {
  9955. function _InstancesBatch() {
  9956. this.mustReturn = false;
  9957. this.visibleInstances = new Array();
  9958. this.renderSelf = new Array();
  9959. }
  9960. return _InstancesBatch;
  9961. })();
  9962. BABYLON._InstancesBatch = _InstancesBatch;
  9963. var Mesh = (function (_super) {
  9964. __extends(Mesh, _super);
  9965. /**
  9966. * @constructor
  9967. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9968. * @param {Scene} scene - The scene to add this mesh to.
  9969. * @param {Node} parent - The parent of this mesh, if it has one
  9970. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9971. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9972. * When false, achieved by calling a clone(), also passing False.
  9973. * This will make creation of children, recursive.
  9974. */
  9975. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9976. if (parent === void 0) { parent = null; }
  9977. _super.call(this, name, scene);
  9978. // Members
  9979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9980. this.instances = new Array();
  9981. this._LODLevels = new Array();
  9982. this._onBeforeRenderCallbacks = new Array();
  9983. this._onAfterRenderCallbacks = new Array();
  9984. this._visibleInstances = {};
  9985. this._renderIdForInstances = new Array();
  9986. this._batchCache = new _InstancesBatch();
  9987. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9988. if (source) {
  9989. // Geometry
  9990. if (source._geometry) {
  9991. source._geometry.applyToMesh(this);
  9992. }
  9993. // Deep copy
  9994. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9995. // Material
  9996. this.material = source.material;
  9997. if (!doNotCloneChildren) {
  9998. for (var index = 0; index < scene.meshes.length; index++) {
  9999. var mesh = scene.meshes[index];
  10000. if (mesh.parent === source) {
  10001. // doNotCloneChildren is always going to be False
  10002. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10003. }
  10004. }
  10005. }
  10006. for (index = 0; index < scene.particleSystems.length; index++) {
  10007. var system = scene.particleSystems[index];
  10008. if (system.emitter === source) {
  10009. system.clone(system.name, this);
  10010. }
  10011. }
  10012. this.computeWorldMatrix(true);
  10013. }
  10014. // Parent
  10015. if (parent !== null) {
  10016. this.parent = parent;
  10017. }
  10018. }
  10019. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10020. // Methods
  10021. get: function () {
  10022. return this._LODLevels.length > 0;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Mesh.prototype._sortLODLevels = function () {
  10028. this._LODLevels.sort(function (a, b) {
  10029. if (a.distance < b.distance) {
  10030. return 1;
  10031. }
  10032. if (a.distance > b.distance) {
  10033. return -1;
  10034. }
  10035. return 0;
  10036. });
  10037. };
  10038. /**
  10039. * Add a mesh as LOD level triggered at the given distance.
  10040. * @param {number} distance - the distance from the center of the object to show this level
  10041. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10042. * @return {BABYLON.Mesh} this mesh (for chaining)
  10043. */
  10044. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10045. if (mesh && mesh._masterMesh) {
  10046. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10047. return this;
  10048. }
  10049. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10050. this._LODLevels.push(level);
  10051. if (mesh) {
  10052. mesh._masterMesh = this;
  10053. }
  10054. this._sortLODLevels();
  10055. return this;
  10056. };
  10057. /**
  10058. * Remove a mesh from the LOD array
  10059. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10060. * @return {BABYLON.Mesh} this mesh (for chaining)
  10061. */
  10062. Mesh.prototype.removeLODLevel = function (mesh) {
  10063. for (var index = 0; index < this._LODLevels.length; index++) {
  10064. if (this._LODLevels[index].mesh === mesh) {
  10065. this._LODLevels.splice(index, 1);
  10066. if (mesh) {
  10067. mesh._masterMesh = null;
  10068. }
  10069. }
  10070. }
  10071. this._sortLODLevels();
  10072. return this;
  10073. };
  10074. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10075. if (!this._LODLevels || this._LODLevels.length === 0) {
  10076. return this;
  10077. }
  10078. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10079. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10080. return this;
  10081. }
  10082. for (var index = 0; index < this._LODLevels.length; index++) {
  10083. var level = this._LODLevels[index];
  10084. if (level.distance < distanceToCamera) {
  10085. if (level.mesh) {
  10086. level.mesh._preActivate();
  10087. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10088. }
  10089. return level.mesh;
  10090. }
  10091. }
  10092. return this;
  10093. };
  10094. Object.defineProperty(Mesh.prototype, "geometry", {
  10095. get: function () {
  10096. return this._geometry;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Mesh.prototype.getTotalVertices = function () {
  10102. if (!this._geometry) {
  10103. return 0;
  10104. }
  10105. return this._geometry.getTotalVertices();
  10106. };
  10107. Mesh.prototype.getVerticesData = function (kind) {
  10108. if (!this._geometry) {
  10109. return null;
  10110. }
  10111. return this._geometry.getVerticesData(kind);
  10112. };
  10113. Mesh.prototype.getVertexBuffer = function (kind) {
  10114. if (!this._geometry) {
  10115. return undefined;
  10116. }
  10117. return this._geometry.getVertexBuffer(kind);
  10118. };
  10119. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10120. if (!this._geometry) {
  10121. if (this._delayInfo) {
  10122. return this._delayInfo.indexOf(kind) !== -1;
  10123. }
  10124. return false;
  10125. }
  10126. return this._geometry.isVerticesDataPresent(kind);
  10127. };
  10128. Mesh.prototype.getVerticesDataKinds = function () {
  10129. if (!this._geometry) {
  10130. var result = [];
  10131. if (this._delayInfo) {
  10132. for (var kind in this._delayInfo) {
  10133. result.push(kind);
  10134. }
  10135. }
  10136. return result;
  10137. }
  10138. return this._geometry.getVerticesDataKinds();
  10139. };
  10140. Mesh.prototype.getTotalIndices = function () {
  10141. if (!this._geometry) {
  10142. return 0;
  10143. }
  10144. return this._geometry.getTotalIndices();
  10145. };
  10146. Mesh.prototype.getIndices = function () {
  10147. if (!this._geometry) {
  10148. return [];
  10149. }
  10150. return this._geometry.getIndices();
  10151. };
  10152. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10153. get: function () {
  10154. return this._masterMesh !== null && this._masterMesh !== undefined;
  10155. },
  10156. enumerable: true,
  10157. configurable: true
  10158. });
  10159. Mesh.prototype.isReady = function () {
  10160. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10161. return false;
  10162. }
  10163. return _super.prototype.isReady.call(this);
  10164. };
  10165. Mesh.prototype.isDisposed = function () {
  10166. return this._isDisposed;
  10167. };
  10168. // Methods
  10169. Mesh.prototype._preActivate = function () {
  10170. var sceneRenderId = this.getScene().getRenderId();
  10171. if (this._preActivateId == sceneRenderId) {
  10172. return;
  10173. }
  10174. this._preActivateId = sceneRenderId;
  10175. this._visibleInstances = null;
  10176. };
  10177. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10178. if (!this._visibleInstances) {
  10179. this._visibleInstances = {};
  10180. this._visibleInstances.defaultRenderId = renderId;
  10181. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10182. }
  10183. if (!this._visibleInstances[renderId]) {
  10184. this._visibleInstances[renderId] = new Array();
  10185. }
  10186. this._visibleInstances[renderId].push(instance);
  10187. };
  10188. Mesh.prototype.refreshBoundingInfo = function () {
  10189. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10190. if (data) {
  10191. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10192. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10193. }
  10194. if (this.subMeshes) {
  10195. for (var index = 0; index < this.subMeshes.length; index++) {
  10196. this.subMeshes[index].refreshBoundingInfo();
  10197. }
  10198. }
  10199. this._updateBoundingInfo();
  10200. };
  10201. Mesh.prototype._createGlobalSubMesh = function () {
  10202. var totalVertices = this.getTotalVertices();
  10203. if (!totalVertices || !this.getIndices()) {
  10204. return null;
  10205. }
  10206. this.releaseSubMeshes();
  10207. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10208. };
  10209. Mesh.prototype.subdivide = function (count) {
  10210. if (count < 1) {
  10211. return;
  10212. }
  10213. var totalIndices = this.getTotalIndices();
  10214. var subdivisionSize = (totalIndices / count) | 0;
  10215. var offset = 0;
  10216. while (subdivisionSize % 3 != 0) {
  10217. subdivisionSize++;
  10218. }
  10219. this.releaseSubMeshes();
  10220. for (var index = 0; index < count; index++) {
  10221. if (offset >= totalIndices) {
  10222. break;
  10223. }
  10224. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10225. offset += subdivisionSize;
  10226. }
  10227. this.synchronizeInstances();
  10228. };
  10229. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10230. if (kind instanceof Array) {
  10231. var temp = data;
  10232. data = kind;
  10233. kind = temp;
  10234. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10235. }
  10236. if (!this._geometry) {
  10237. var vertexData = new BABYLON.VertexData();
  10238. vertexData.set(data, kind);
  10239. var scene = this.getScene();
  10240. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10241. }
  10242. else {
  10243. this._geometry.setVerticesData(kind, data, updatable, stride);
  10244. }
  10245. };
  10246. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10247. if (!this._geometry) {
  10248. return;
  10249. }
  10250. if (!makeItUnique) {
  10251. this._geometry.updateVerticesData(kind, data, updateExtends);
  10252. }
  10253. else {
  10254. this.makeGeometryUnique();
  10255. this.updateVerticesData(kind, data, updateExtends, false);
  10256. }
  10257. };
  10258. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10259. if (!this._geometry) {
  10260. return;
  10261. }
  10262. if (!makeItUnique) {
  10263. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10264. }
  10265. else {
  10266. this.makeGeometryUnique();
  10267. this.updateVerticesDataDirectly(kind, data, offset, false);
  10268. }
  10269. };
  10270. Mesh.prototype.makeGeometryUnique = function () {
  10271. if (!this._geometry) {
  10272. return;
  10273. }
  10274. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10275. geometry.applyToMesh(this);
  10276. };
  10277. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10278. if (!this._geometry) {
  10279. var vertexData = new BABYLON.VertexData();
  10280. vertexData.indices = indices;
  10281. var scene = this.getScene();
  10282. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10283. }
  10284. else {
  10285. this._geometry.setIndices(indices, totalVertices);
  10286. }
  10287. };
  10288. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10289. var engine = this.getScene().getEngine();
  10290. // Wireframe
  10291. var indexToBind;
  10292. switch (fillMode) {
  10293. case BABYLON.Material.PointFillMode:
  10294. indexToBind = null;
  10295. break;
  10296. case BABYLON.Material.WireFrameFillMode:
  10297. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10298. break;
  10299. default:
  10300. case BABYLON.Material.TriangleFillMode:
  10301. indexToBind = this._geometry.getIndexBuffer();
  10302. break;
  10303. }
  10304. // VBOs
  10305. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10306. };
  10307. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10308. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10309. return;
  10310. }
  10311. var engine = this.getScene().getEngine();
  10312. switch (fillMode) {
  10313. case BABYLON.Material.PointFillMode:
  10314. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10315. break;
  10316. case BABYLON.Material.WireFrameFillMode:
  10317. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10318. break;
  10319. default:
  10320. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10321. }
  10322. };
  10323. Mesh.prototype.registerBeforeRender = function (func) {
  10324. this._onBeforeRenderCallbacks.push(func);
  10325. };
  10326. Mesh.prototype.unregisterBeforeRender = function (func) {
  10327. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10328. if (index > -1) {
  10329. this._onBeforeRenderCallbacks.splice(index, 1);
  10330. }
  10331. };
  10332. Mesh.prototype.registerAfterRender = function (func) {
  10333. this._onAfterRenderCallbacks.push(func);
  10334. };
  10335. Mesh.prototype.unregisterAfterRender = function (func) {
  10336. var index = this._onAfterRenderCallbacks.indexOf(func);
  10337. if (index > -1) {
  10338. this._onAfterRenderCallbacks.splice(index, 1);
  10339. }
  10340. };
  10341. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10342. var scene = this.getScene();
  10343. this._batchCache.mustReturn = false;
  10344. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10345. this._batchCache.visibleInstances[subMeshId] = null;
  10346. if (this._visibleInstances) {
  10347. var currentRenderId = scene.getRenderId();
  10348. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10349. var selfRenderId = this._renderId;
  10350. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10351. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10352. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10353. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10354. }
  10355. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10356. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10357. this._batchCache.mustReturn = true;
  10358. return this._batchCache;
  10359. }
  10360. if (currentRenderId !== selfRenderId) {
  10361. this._batchCache.renderSelf[subMeshId] = false;
  10362. }
  10363. }
  10364. this._renderIdForInstances[subMeshId] = currentRenderId;
  10365. }
  10366. return this._batchCache;
  10367. };
  10368. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10369. var visibleInstances = batch.visibleInstances[subMesh._id];
  10370. var matricesCount = visibleInstances.length + 1;
  10371. var bufferSize = matricesCount * 16 * 4;
  10372. while (this._instancesBufferSize < bufferSize) {
  10373. this._instancesBufferSize *= 2;
  10374. }
  10375. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10376. if (this._worldMatricesInstancesBuffer) {
  10377. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10378. }
  10379. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10380. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10381. }
  10382. var offset = 0;
  10383. var instancesCount = 0;
  10384. var world = this.getWorldMatrix();
  10385. if (batch.renderSelf[subMesh._id]) {
  10386. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10387. offset += 16;
  10388. instancesCount++;
  10389. }
  10390. if (visibleInstances) {
  10391. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10392. var instance = visibleInstances[instanceIndex];
  10393. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10394. offset += 16;
  10395. instancesCount++;
  10396. }
  10397. }
  10398. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10399. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10400. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10401. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10402. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10403. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10404. this._draw(subMesh, fillMode, instancesCount);
  10405. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10406. };
  10407. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10408. var scene = this.getScene();
  10409. var engine = scene.getEngine();
  10410. if (hardwareInstancedRendering) {
  10411. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10412. }
  10413. else {
  10414. if (batch.renderSelf[subMesh._id]) {
  10415. // Draw
  10416. if (onBeforeDraw) {
  10417. onBeforeDraw(false, this.getWorldMatrix());
  10418. }
  10419. this._draw(subMesh, fillMode);
  10420. }
  10421. if (batch.visibleInstances[subMesh._id]) {
  10422. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10423. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10424. // World
  10425. var world = instance.getWorldMatrix();
  10426. if (onBeforeDraw) {
  10427. onBeforeDraw(true, world);
  10428. }
  10429. // Draw
  10430. this._draw(subMesh, fillMode);
  10431. }
  10432. }
  10433. }
  10434. };
  10435. Mesh.prototype.render = function (subMesh) {
  10436. var scene = this.getScene();
  10437. // Managing instances
  10438. var batch = this._getInstancesRenderList(subMesh._id);
  10439. if (batch.mustReturn) {
  10440. return;
  10441. }
  10442. // Checking geometry state
  10443. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10444. return;
  10445. }
  10446. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10447. this._onBeforeRenderCallbacks[callbackIndex]();
  10448. }
  10449. var engine = scene.getEngine();
  10450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10451. // Material
  10452. var effectiveMaterial = subMesh.getMaterial();
  10453. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10454. return;
  10455. }
  10456. // Outline - step 1
  10457. var savedDepthWrite = engine.getDepthWrite();
  10458. if (this.renderOutline) {
  10459. engine.setDepthWrite(false);
  10460. scene.getOutlineRenderer().render(subMesh, batch);
  10461. engine.setDepthWrite(savedDepthWrite);
  10462. }
  10463. effectiveMaterial._preBind();
  10464. var effect = effectiveMaterial.getEffect();
  10465. // Bind
  10466. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10467. this._bind(subMesh, effect, fillMode);
  10468. var world = this.getWorldMatrix();
  10469. effectiveMaterial.bind(world, this);
  10470. // Draw
  10471. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10472. if (isInstance) {
  10473. effectiveMaterial.bindOnlyWorldMatrix(world);
  10474. }
  10475. });
  10476. // Unbind
  10477. effectiveMaterial.unbind();
  10478. // Outline - step 2
  10479. if (this.renderOutline && savedDepthWrite) {
  10480. engine.setDepthWrite(true);
  10481. engine.setColorWrite(false);
  10482. scene.getOutlineRenderer().render(subMesh, batch);
  10483. engine.setColorWrite(true);
  10484. }
  10485. // Overlay
  10486. if (this.renderOverlay) {
  10487. var currentMode = engine.getAlphaMode();
  10488. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10489. scene.getOutlineRenderer().render(subMesh, batch, true);
  10490. engine.setAlphaMode(currentMode);
  10491. }
  10492. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10493. this._onAfterRenderCallbacks[callbackIndex]();
  10494. }
  10495. };
  10496. Mesh.prototype.getEmittedParticleSystems = function () {
  10497. var results = new Array();
  10498. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10499. var particleSystem = this.getScene().particleSystems[index];
  10500. if (particleSystem.emitter === this) {
  10501. results.push(particleSystem);
  10502. }
  10503. }
  10504. return results;
  10505. };
  10506. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10507. var results = new Array();
  10508. var descendants = this.getDescendants();
  10509. descendants.push(this);
  10510. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10511. var particleSystem = this.getScene().particleSystems[index];
  10512. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10513. results.push(particleSystem);
  10514. }
  10515. }
  10516. return results;
  10517. };
  10518. Mesh.prototype.getChildren = function () {
  10519. var results = [];
  10520. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10521. var mesh = this.getScene().meshes[index];
  10522. if (mesh.parent === this) {
  10523. results.push(mesh);
  10524. }
  10525. }
  10526. return results;
  10527. };
  10528. Mesh.prototype._checkDelayState = function () {
  10529. var _this = this;
  10530. var that = this;
  10531. var scene = this.getScene();
  10532. if (this._geometry) {
  10533. this._geometry.load(scene);
  10534. }
  10535. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10536. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10537. scene._addPendingData(that);
  10538. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10539. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10540. if (data instanceof ArrayBuffer) {
  10541. _this._delayLoadingFunction(data, _this);
  10542. }
  10543. else {
  10544. _this._delayLoadingFunction(JSON.parse(data), _this);
  10545. }
  10546. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10547. scene._removePendingData(_this);
  10548. }, function () {
  10549. }, scene.database, getBinaryData);
  10550. }
  10551. };
  10552. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10553. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10554. return false;
  10555. }
  10556. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10557. return false;
  10558. }
  10559. this._checkDelayState();
  10560. return true;
  10561. };
  10562. Mesh.prototype.setMaterialByID = function (id) {
  10563. var materials = this.getScene().materials;
  10564. for (var index = 0; index < materials.length; index++) {
  10565. if (materials[index].id === id) {
  10566. this.material = materials[index];
  10567. return;
  10568. }
  10569. }
  10570. // Multi
  10571. var multiMaterials = this.getScene().multiMaterials;
  10572. for (index = 0; index < multiMaterials.length; index++) {
  10573. if (multiMaterials[index].id === id) {
  10574. this.material = multiMaterials[index];
  10575. return;
  10576. }
  10577. }
  10578. };
  10579. Mesh.prototype.getAnimatables = function () {
  10580. var results = [];
  10581. if (this.material) {
  10582. results.push(this.material);
  10583. }
  10584. if (this.skeleton) {
  10585. results.push(this.skeleton);
  10586. }
  10587. return results;
  10588. };
  10589. // Geometry
  10590. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10591. // Position
  10592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10593. return;
  10594. }
  10595. this._resetPointsArrayCache();
  10596. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10597. var temp = [];
  10598. for (var index = 0; index < data.length; index += 3) {
  10599. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10600. }
  10601. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10602. // Normals
  10603. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10604. return;
  10605. }
  10606. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10607. for (index = 0; index < data.length; index += 3) {
  10608. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10609. }
  10610. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10611. };
  10612. // Cache
  10613. Mesh.prototype._resetPointsArrayCache = function () {
  10614. this._positions = null;
  10615. };
  10616. Mesh.prototype._generatePointsArray = function () {
  10617. if (this._positions)
  10618. return true;
  10619. this._positions = [];
  10620. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10621. if (!data) {
  10622. return false;
  10623. }
  10624. for (var index = 0; index < data.length; index += 3) {
  10625. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10626. }
  10627. return true;
  10628. };
  10629. // Clone
  10630. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10631. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10632. };
  10633. // Dispose
  10634. Mesh.prototype.dispose = function (doNotRecurse) {
  10635. if (this._geometry) {
  10636. this._geometry.releaseForMesh(this, true);
  10637. }
  10638. // Instances
  10639. if (this._worldMatricesInstancesBuffer) {
  10640. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10641. this._worldMatricesInstancesBuffer = null;
  10642. }
  10643. while (this.instances.length) {
  10644. this.instances[0].dispose();
  10645. }
  10646. _super.prototype.dispose.call(this, doNotRecurse);
  10647. };
  10648. // Geometric tools
  10649. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10650. var _this = this;
  10651. var scene = this.getScene();
  10652. var onload = function (img) {
  10653. // Getting height map data
  10654. var canvas = document.createElement("canvas");
  10655. var context = canvas.getContext("2d");
  10656. var heightMapWidth = img.width;
  10657. var heightMapHeight = img.height;
  10658. canvas.width = heightMapWidth;
  10659. canvas.height = heightMapHeight;
  10660. context.drawImage(img, 0, 0);
  10661. // Create VertexData from map data
  10662. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10663. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10664. //execute success callback, if set
  10665. if (onSuccess) {
  10666. onSuccess(_this);
  10667. }
  10668. };
  10669. BABYLON.Tools.LoadImage(url, onload, function () {
  10670. }, scene.database);
  10671. };
  10672. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10673. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10674. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10675. return;
  10676. }
  10677. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10678. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10679. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10680. var position = BABYLON.Vector3.Zero();
  10681. var normal = BABYLON.Vector3.Zero();
  10682. var uv = BABYLON.Vector2.Zero();
  10683. for (var index = 0; index < positions.length; index += 3) {
  10684. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10685. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10686. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10687. // Compute height
  10688. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10689. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10690. var pos = (u + v * heightMapWidth) * 4;
  10691. var r = buffer[pos] / 255.0;
  10692. var g = buffer[pos + 1] / 255.0;
  10693. var b = buffer[pos + 2] / 255.0;
  10694. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10695. normal.normalize();
  10696. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10697. position = position.add(normal);
  10698. position.toArray(positions, index);
  10699. }
  10700. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10701. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10702. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10703. };
  10704. Mesh.prototype.convertToFlatShadedMesh = function () {
  10705. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10706. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10707. var kinds = this.getVerticesDataKinds();
  10708. var vbs = [];
  10709. var data = [];
  10710. var newdata = [];
  10711. var updatableNormals = false;
  10712. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10713. var kind = kinds[kindIndex];
  10714. var vertexBuffer = this.getVertexBuffer(kind);
  10715. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10716. updatableNormals = vertexBuffer.isUpdatable();
  10717. kinds.splice(kindIndex, 1);
  10718. kindIndex--;
  10719. continue;
  10720. }
  10721. vbs[kind] = vertexBuffer;
  10722. data[kind] = vbs[kind].getData();
  10723. newdata[kind] = [];
  10724. }
  10725. // Save previous submeshes
  10726. var previousSubmeshes = this.subMeshes.slice(0);
  10727. var indices = this.getIndices();
  10728. var totalIndices = this.getTotalIndices();
  10729. for (var index = 0; index < totalIndices; index++) {
  10730. var vertexIndex = indices[index];
  10731. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10732. kind = kinds[kindIndex];
  10733. var stride = vbs[kind].getStrideSize();
  10734. for (var offset = 0; offset < stride; offset++) {
  10735. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10736. }
  10737. }
  10738. }
  10739. // Updating faces & normal
  10740. var normals = [];
  10741. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10742. for (index = 0; index < totalIndices; index += 3) {
  10743. indices[index] = index;
  10744. indices[index + 1] = index + 1;
  10745. indices[index + 2] = index + 2;
  10746. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10747. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10748. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10749. var p1p2 = p1.subtract(p2);
  10750. var p3p2 = p3.subtract(p2);
  10751. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10752. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10753. normals.push(normal.x);
  10754. normals.push(normal.y);
  10755. normals.push(normal.z);
  10756. }
  10757. }
  10758. this.setIndices(indices);
  10759. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10760. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10761. kind = kinds[kindIndex];
  10762. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10763. }
  10764. // Updating submeshes
  10765. this.releaseSubMeshes();
  10766. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10767. var previousOne = previousSubmeshes[submeshIndex];
  10768. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10769. }
  10770. this.synchronizeInstances();
  10771. };
  10772. // Instances
  10773. Mesh.prototype.createInstance = function (name) {
  10774. return new BABYLON.InstancedMesh(name, this);
  10775. };
  10776. Mesh.prototype.synchronizeInstances = function () {
  10777. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10778. var instance = this.instances[instanceIndex];
  10779. instance._syncSubMeshes();
  10780. }
  10781. };
  10782. /**
  10783. * Simplify the mesh according to the given array of settings.
  10784. * Function will return immediately and will simplify async.
  10785. * @param settings a collection of simplification settings.
  10786. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10787. * @param type the type of simplification to run.
  10788. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10789. */
  10790. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10791. var _this = this;
  10792. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10793. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10794. var getSimplifier = function () {
  10795. switch (type) {
  10796. case 0 /* QUADRATIC */:
  10797. default:
  10798. return new BABYLON.QuadraticErrorSimplification(_this);
  10799. }
  10800. };
  10801. if (parallelProcessing) {
  10802. //parallel simplifier
  10803. settings.forEach(function (setting) {
  10804. var simplifier = getSimplifier();
  10805. simplifier.simplify(setting, function (newMesh) {
  10806. _this.addLODLevel(setting.distance, newMesh);
  10807. //check if it is the last
  10808. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10809. //all done, run the success callback.
  10810. successCallback();
  10811. }
  10812. });
  10813. });
  10814. }
  10815. else {
  10816. //single simplifier.
  10817. var simplifier = getSimplifier();
  10818. var runDecimation = function (setting, callback) {
  10819. simplifier.simplify(setting, function (newMesh) {
  10820. _this.addLODLevel(setting.distance, newMesh);
  10821. //run the next quality level
  10822. callback();
  10823. });
  10824. };
  10825. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10826. runDecimation(settings[loop.index], function () {
  10827. loop.executeNext();
  10828. });
  10829. }, function () {
  10830. //execution ended, run the success callback.
  10831. if (successCallback) {
  10832. successCallback();
  10833. }
  10834. });
  10835. }
  10836. };
  10837. // Statics
  10838. Mesh.CreateBox = function (name, size, scene, updatable) {
  10839. var box = new Mesh(name, scene);
  10840. var vertexData = BABYLON.VertexData.CreateBox(size);
  10841. vertexData.applyToMesh(box, updatable);
  10842. return box;
  10843. };
  10844. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10845. var sphere = new Mesh(name, scene);
  10846. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10847. vertexData.applyToMesh(sphere, updatable);
  10848. return sphere;
  10849. };
  10850. // Cylinder and cone (Code inspired by SharpDX.org)
  10851. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10852. // subdivisions is a new parameter, we need to support old signature
  10853. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10854. if (scene !== undefined) {
  10855. updatable = scene;
  10856. }
  10857. scene = subdivisions;
  10858. subdivisions = 1;
  10859. }
  10860. var cylinder = new Mesh(name, scene);
  10861. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10862. vertexData.applyToMesh(cylinder, updatable);
  10863. return cylinder;
  10864. };
  10865. // Torus (Code from SharpDX.org)
  10866. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10867. var torus = new Mesh(name, scene);
  10868. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10869. vertexData.applyToMesh(torus, updatable);
  10870. return torus;
  10871. };
  10872. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10873. var torusKnot = new Mesh(name, scene);
  10874. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10875. vertexData.applyToMesh(torusKnot, updatable);
  10876. return torusKnot;
  10877. };
  10878. // Lines
  10879. Mesh.CreateLines = function (name, points, scene, updatable) {
  10880. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10881. var vertexData = BABYLON.VertexData.CreateLines(points);
  10882. vertexData.applyToMesh(lines, updatable);
  10883. return lines;
  10884. };
  10885. // Plane & ground
  10886. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10887. var plane = new Mesh(name, scene);
  10888. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10889. vertexData.applyToMesh(plane, updatable);
  10890. return plane;
  10891. };
  10892. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10893. var ground = new BABYLON.GroundMesh(name, scene);
  10894. ground._setReady(false);
  10895. ground._subdivisions = subdivisions;
  10896. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10897. vertexData.applyToMesh(ground, updatable);
  10898. ground._setReady(true);
  10899. return ground;
  10900. };
  10901. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10902. var tiledGround = new Mesh(name, scene);
  10903. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10904. vertexData.applyToMesh(tiledGround, updatable);
  10905. return tiledGround;
  10906. };
  10907. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10908. var ground = new BABYLON.GroundMesh(name, scene);
  10909. ground._subdivisions = subdivisions;
  10910. ground._setReady(false);
  10911. var onload = function (img) {
  10912. // Getting height map data
  10913. var canvas = document.createElement("canvas");
  10914. var context = canvas.getContext("2d");
  10915. var heightMapWidth = img.width;
  10916. var heightMapHeight = img.height;
  10917. canvas.width = heightMapWidth;
  10918. canvas.height = heightMapHeight;
  10919. context.drawImage(img, 0, 0);
  10920. // Create VertexData from map data
  10921. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10922. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10923. vertexData.applyToMesh(ground, updatable);
  10924. ground._setReady(true);
  10925. //execute ready callback, if set
  10926. if (onReady) {
  10927. onReady(ground);
  10928. }
  10929. };
  10930. BABYLON.Tools.LoadImage(url, onload, function () {
  10931. }, scene.database);
  10932. return ground;
  10933. };
  10934. // Tools
  10935. Mesh.MinMax = function (meshes) {
  10936. var minVector = null;
  10937. var maxVector = null;
  10938. for (var i in meshes) {
  10939. var mesh = meshes[i];
  10940. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10941. if (!minVector) {
  10942. minVector = boundingBox.minimumWorld;
  10943. maxVector = boundingBox.maximumWorld;
  10944. continue;
  10945. }
  10946. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10947. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10948. }
  10949. return {
  10950. min: minVector,
  10951. max: maxVector
  10952. };
  10953. };
  10954. Mesh.Center = function (meshesOrMinMaxVector) {
  10955. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10956. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10957. };
  10958. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10959. if (disposeSource === void 0) { disposeSource = true; }
  10960. var source = meshes[0];
  10961. var material = source.material;
  10962. var scene = source.getScene();
  10963. if (!allow32BitsIndices) {
  10964. var totalVertices = 0;
  10965. for (var index = 0; index < meshes.length; index++) {
  10966. totalVertices += meshes[index].getTotalVertices();
  10967. if (totalVertices > 65536) {
  10968. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10969. return null;
  10970. }
  10971. }
  10972. }
  10973. // Merge
  10974. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10975. vertexData.transform(source.getWorldMatrix());
  10976. for (index = 1; index < meshes.length; index++) {
  10977. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10978. otherVertexData.transform(meshes[index].getWorldMatrix());
  10979. vertexData.merge(otherVertexData);
  10980. }
  10981. var newMesh = new Mesh(source.name + "_merged", scene);
  10982. vertexData.applyToMesh(newMesh);
  10983. // Setting properties
  10984. newMesh.material = material;
  10985. newMesh.checkCollisions = source.checkCollisions;
  10986. // Cleaning
  10987. if (disposeSource) {
  10988. for (index = 0; index < meshes.length; index++) {
  10989. meshes[index].dispose();
  10990. }
  10991. }
  10992. return newMesh;
  10993. };
  10994. return Mesh;
  10995. })(BABYLON.AbstractMesh);
  10996. BABYLON.Mesh = Mesh;
  10997. })(BABYLON || (BABYLON = {}));
  10998. //# sourceMappingURL=babylon.mesh.js.map
  10999. var BABYLON;
  11000. (function (BABYLON) {
  11001. var GroundMesh = (function (_super) {
  11002. __extends(GroundMesh, _super);
  11003. function GroundMesh(name, scene) {
  11004. _super.call(this, name, scene);
  11005. this.generateOctree = false;
  11006. this._worldInverse = new BABYLON.Matrix();
  11007. }
  11008. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11009. get: function () {
  11010. return this._subdivisions;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. GroundMesh.prototype.optimize = function (chunksCount) {
  11016. this.subdivide(this._subdivisions);
  11017. this.createOrUpdateSubmeshesOctree(32);
  11018. };
  11019. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11020. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11021. this.getWorldMatrix().invertToRef(this._worldInverse);
  11022. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11023. var pickInfo = this.intersects(ray);
  11024. if (pickInfo.hit) {
  11025. return pickInfo.pickedPoint.y;
  11026. }
  11027. return 0;
  11028. };
  11029. return GroundMesh;
  11030. })(BABYLON.Mesh);
  11031. BABYLON.GroundMesh = GroundMesh;
  11032. })(BABYLON || (BABYLON = {}));
  11033. //# sourceMappingURL=babylon.groundMesh.js.map
  11034. var BABYLON;
  11035. (function (BABYLON) {
  11036. /**
  11037. * Creates an instance based on a source mesh.
  11038. */
  11039. var InstancedMesh = (function (_super) {
  11040. __extends(InstancedMesh, _super);
  11041. function InstancedMesh(name, source) {
  11042. _super.call(this, name, source.getScene());
  11043. source.instances.push(this);
  11044. this._sourceMesh = source;
  11045. this.position.copyFrom(source.position);
  11046. this.rotation.copyFrom(source.rotation);
  11047. this.scaling.copyFrom(source.scaling);
  11048. if (source.rotationQuaternion) {
  11049. this.rotationQuaternion = source.rotationQuaternion.clone();
  11050. }
  11051. this.infiniteDistance = source.infiniteDistance;
  11052. this.setPivotMatrix(source.getPivotMatrix());
  11053. this.refreshBoundingInfo();
  11054. this._syncSubMeshes();
  11055. }
  11056. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11057. // Methods
  11058. get: function () {
  11059. return this._sourceMesh.receiveShadows;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(InstancedMesh.prototype, "material", {
  11065. get: function () {
  11066. return this._sourceMesh.material;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11072. get: function () {
  11073. return this._sourceMesh.visibility;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11079. get: function () {
  11080. return this._sourceMesh.skeleton;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. InstancedMesh.prototype.getTotalVertices = function () {
  11086. return this._sourceMesh.getTotalVertices();
  11087. };
  11088. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11089. get: function () {
  11090. return this._sourceMesh;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. InstancedMesh.prototype.getVerticesData = function (kind) {
  11096. return this._sourceMesh.getVerticesData(kind);
  11097. };
  11098. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11099. return this._sourceMesh.isVerticesDataPresent(kind);
  11100. };
  11101. InstancedMesh.prototype.getIndices = function () {
  11102. return this._sourceMesh.getIndices();
  11103. };
  11104. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11105. get: function () {
  11106. return this._sourceMesh._positions;
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11112. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11113. if (data) {
  11114. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11115. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11116. }
  11117. this._updateBoundingInfo();
  11118. };
  11119. InstancedMesh.prototype._preActivate = function () {
  11120. if (this._currentLOD) {
  11121. this._currentLOD._preActivate();
  11122. }
  11123. };
  11124. InstancedMesh.prototype._activate = function (renderId) {
  11125. if (this._currentLOD) {
  11126. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11127. }
  11128. };
  11129. InstancedMesh.prototype.getLOD = function (camera) {
  11130. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11131. if (this._currentLOD === this.sourceMesh) {
  11132. return this;
  11133. }
  11134. return this._currentLOD;
  11135. };
  11136. InstancedMesh.prototype._syncSubMeshes = function () {
  11137. this.releaseSubMeshes();
  11138. if (this._sourceMesh.subMeshes) {
  11139. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11140. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11141. }
  11142. }
  11143. };
  11144. InstancedMesh.prototype._generatePointsArray = function () {
  11145. return this._sourceMesh._generatePointsArray();
  11146. };
  11147. // Clone
  11148. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11149. var result = this._sourceMesh.createInstance(name);
  11150. // Deep copy
  11151. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11152. // Bounding info
  11153. this.refreshBoundingInfo();
  11154. // Parent
  11155. if (newParent) {
  11156. result.parent = newParent;
  11157. }
  11158. if (!doNotCloneChildren) {
  11159. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11160. var mesh = this.getScene().meshes[index];
  11161. if (mesh.parent === this) {
  11162. mesh.clone(mesh.name, result);
  11163. }
  11164. }
  11165. }
  11166. result.computeWorldMatrix(true);
  11167. return result;
  11168. };
  11169. // Dispoe
  11170. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11171. // Remove from mesh
  11172. var index = this._sourceMesh.instances.indexOf(this);
  11173. this._sourceMesh.instances.splice(index, 1);
  11174. _super.prototype.dispose.call(this, doNotRecurse);
  11175. };
  11176. return InstancedMesh;
  11177. })(BABYLON.AbstractMesh);
  11178. BABYLON.InstancedMesh = InstancedMesh;
  11179. })(BABYLON || (BABYLON = {}));
  11180. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11181. (function (BABYLON) {
  11182. var SubMesh = (function () {
  11183. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11184. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11185. this.materialIndex = materialIndex;
  11186. this.verticesStart = verticesStart;
  11187. this.verticesCount = verticesCount;
  11188. this.indexStart = indexStart;
  11189. this.indexCount = indexCount;
  11190. this._renderId = 0;
  11191. this._mesh = mesh;
  11192. this._renderingMesh = renderingMesh || mesh;
  11193. mesh.subMeshes.push(this);
  11194. this._id = mesh.subMeshes.length - 1;
  11195. if (createBoundingBox) {
  11196. this.refreshBoundingInfo();
  11197. }
  11198. }
  11199. SubMesh.prototype.getBoundingInfo = function () {
  11200. return this._boundingInfo;
  11201. };
  11202. SubMesh.prototype.getMesh = function () {
  11203. return this._mesh;
  11204. };
  11205. SubMesh.prototype.getRenderingMesh = function () {
  11206. return this._renderingMesh;
  11207. };
  11208. SubMesh.prototype.getMaterial = function () {
  11209. var rootMaterial = this._renderingMesh.material;
  11210. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11211. var multiMaterial = rootMaterial;
  11212. return multiMaterial.getSubMaterial(this.materialIndex);
  11213. }
  11214. if (!rootMaterial) {
  11215. return this._mesh.getScene().defaultMaterial;
  11216. }
  11217. return rootMaterial;
  11218. };
  11219. // Methods
  11220. SubMesh.prototype.refreshBoundingInfo = function () {
  11221. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11222. if (!data) {
  11223. this._boundingInfo = this._mesh._boundingInfo;
  11224. return;
  11225. }
  11226. var indices = this._renderingMesh.getIndices();
  11227. var extend;
  11228. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11229. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11230. }
  11231. else {
  11232. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11233. }
  11234. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11235. };
  11236. SubMesh.prototype._checkCollision = function (collider) {
  11237. return this._boundingInfo._checkCollision(collider);
  11238. };
  11239. SubMesh.prototype.updateBoundingInfo = function (world) {
  11240. if (!this._boundingInfo) {
  11241. this.refreshBoundingInfo();
  11242. }
  11243. this._boundingInfo._update(world);
  11244. };
  11245. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11246. return this._boundingInfo.isInFrustum(frustumPlanes);
  11247. };
  11248. SubMesh.prototype.render = function () {
  11249. this._renderingMesh.render(this);
  11250. };
  11251. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11252. if (!this._linesIndexBuffer) {
  11253. var linesIndices = [];
  11254. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11255. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11256. }
  11257. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11258. this.linesIndexCount = linesIndices.length;
  11259. }
  11260. return this._linesIndexBuffer;
  11261. };
  11262. SubMesh.prototype.canIntersects = function (ray) {
  11263. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11264. };
  11265. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11266. var intersectInfo = null;
  11267. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11268. var p0 = positions[indices[index]];
  11269. var p1 = positions[indices[index + 1]];
  11270. var p2 = positions[indices[index + 2]];
  11271. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11272. if (currentIntersectInfo) {
  11273. if (currentIntersectInfo.distance < 0) {
  11274. continue;
  11275. }
  11276. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11277. intersectInfo = currentIntersectInfo;
  11278. intersectInfo.faceId = index / 3;
  11279. if (fastCheck) {
  11280. break;
  11281. }
  11282. }
  11283. }
  11284. }
  11285. return intersectInfo;
  11286. };
  11287. // Clone
  11288. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11289. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11290. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11291. return result;
  11292. };
  11293. // Dispose
  11294. SubMesh.prototype.dispose = function () {
  11295. if (this._linesIndexBuffer) {
  11296. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11297. this._linesIndexBuffer = null;
  11298. }
  11299. // Remove from mesh
  11300. var index = this._mesh.subMeshes.indexOf(this);
  11301. this._mesh.subMeshes.splice(index, 1);
  11302. };
  11303. // Statics
  11304. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11305. var minVertexIndex = Number.MAX_VALUE;
  11306. var maxVertexIndex = -Number.MAX_VALUE;
  11307. renderingMesh = renderingMesh || mesh;
  11308. var indices = renderingMesh.getIndices();
  11309. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11310. var vertexIndex = indices[index];
  11311. if (vertexIndex < minVertexIndex)
  11312. minVertexIndex = vertexIndex;
  11313. if (vertexIndex > maxVertexIndex)
  11314. maxVertexIndex = vertexIndex;
  11315. }
  11316. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11317. };
  11318. return SubMesh;
  11319. })();
  11320. BABYLON.SubMesh = SubMesh;
  11321. })(BABYLON || (BABYLON = {}));
  11322. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11323. (function (BABYLON) {
  11324. var BaseTexture = (function () {
  11325. function BaseTexture(scene) {
  11326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11327. this.hasAlpha = false;
  11328. this.getAlphaFromRGB = false;
  11329. this.level = 1;
  11330. this.isCube = false;
  11331. this.isRenderTarget = false;
  11332. this.animations = new Array();
  11333. this.coordinatesIndex = 0;
  11334. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11335. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11336. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11337. this.anisotropicFilteringLevel = 4;
  11338. this._scene = scene;
  11339. this._scene.textures.push(this);
  11340. }
  11341. BaseTexture.prototype.getScene = function () {
  11342. return this._scene;
  11343. };
  11344. BaseTexture.prototype.getTextureMatrix = function () {
  11345. return null;
  11346. };
  11347. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11348. return null;
  11349. };
  11350. BaseTexture.prototype.getInternalTexture = function () {
  11351. return this._texture;
  11352. };
  11353. BaseTexture.prototype.isReady = function () {
  11354. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11355. return true;
  11356. }
  11357. if (this._texture) {
  11358. return this._texture.isReady;
  11359. }
  11360. return false;
  11361. };
  11362. BaseTexture.prototype.getSize = function () {
  11363. if (this._texture._width) {
  11364. return { width: this._texture._width, height: this._texture._height };
  11365. }
  11366. if (this._texture._size) {
  11367. return { width: this._texture._size, height: this._texture._size };
  11368. }
  11369. return { width: 0, height: 0 };
  11370. };
  11371. BaseTexture.prototype.getBaseSize = function () {
  11372. if (!this.isReady())
  11373. return { width: 0, height: 0 };
  11374. if (this._texture._size) {
  11375. return { width: this._texture._size, height: this._texture._size };
  11376. }
  11377. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11378. };
  11379. BaseTexture.prototype.scale = function (ratio) {
  11380. };
  11381. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11382. get: function () {
  11383. return false;
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11389. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11390. for (var index = 0; index < texturesCache.length; index++) {
  11391. var texturesCacheEntry = texturesCache[index];
  11392. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11393. texturesCache.splice(index, 1);
  11394. return;
  11395. }
  11396. }
  11397. };
  11398. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11399. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11400. for (var index = 0; index < texturesCache.length; index++) {
  11401. var texturesCacheEntry = texturesCache[index];
  11402. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11403. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11404. texturesCacheEntry.references++;
  11405. return texturesCacheEntry;
  11406. }
  11407. }
  11408. }
  11409. return null;
  11410. };
  11411. BaseTexture.prototype.delayLoad = function () {
  11412. };
  11413. BaseTexture.prototype.releaseInternalTexture = function () {
  11414. if (!this._texture) {
  11415. return;
  11416. }
  11417. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11418. this._texture.references--;
  11419. // Final reference ?
  11420. if (this._texture.references === 0) {
  11421. var index = texturesCache.indexOf(this._texture);
  11422. texturesCache.splice(index, 1);
  11423. this._scene.getEngine()._releaseTexture(this._texture);
  11424. delete this._texture;
  11425. }
  11426. };
  11427. BaseTexture.prototype.clone = function () {
  11428. return null;
  11429. };
  11430. BaseTexture.prototype.dispose = function () {
  11431. // Remove from scene
  11432. var index = this._scene.textures.indexOf(this);
  11433. if (index >= 0) {
  11434. this._scene.textures.splice(index, 1);
  11435. }
  11436. if (this._texture === undefined) {
  11437. return;
  11438. }
  11439. this.releaseInternalTexture();
  11440. // Callback
  11441. if (this.onDispose) {
  11442. this.onDispose();
  11443. }
  11444. };
  11445. return BaseTexture;
  11446. })();
  11447. BABYLON.BaseTexture = BaseTexture;
  11448. })(BABYLON || (BABYLON = {}));
  11449. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11450. (function (BABYLON) {
  11451. var RenderingGroup = (function () {
  11452. function RenderingGroup(index, scene) {
  11453. this.index = index;
  11454. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11455. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11456. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11457. this._scene = scene;
  11458. }
  11459. RenderingGroup.prototype.render = function (customRenderFunction) {
  11460. if (customRenderFunction) {
  11461. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11462. return true;
  11463. }
  11464. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11465. return false;
  11466. }
  11467. var engine = this._scene.getEngine();
  11468. // Opaque
  11469. var subIndex;
  11470. var submesh;
  11471. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11472. submesh = this._opaqueSubMeshes.data[subIndex];
  11473. submesh.render();
  11474. }
  11475. // Alpha test
  11476. engine.setAlphaTesting(true);
  11477. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11478. submesh = this._alphaTestSubMeshes.data[subIndex];
  11479. submesh.render();
  11480. }
  11481. engine.setAlphaTesting(false);
  11482. // Transparent
  11483. if (this._transparentSubMeshes.length) {
  11484. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11485. submesh = this._transparentSubMeshes.data[subIndex];
  11486. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11487. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11488. }
  11489. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11490. sortedArray.sort(function (a, b) {
  11491. // Alpha index first
  11492. if (a._alphaIndex > b._alphaIndex) {
  11493. return 1;
  11494. }
  11495. if (a._alphaIndex < b._alphaIndex) {
  11496. return -1;
  11497. }
  11498. // Then distance to camera
  11499. if (a._distanceToCamera < b._distanceToCamera) {
  11500. return 1;
  11501. }
  11502. if (a._distanceToCamera > b._distanceToCamera) {
  11503. return -1;
  11504. }
  11505. return 0;
  11506. });
  11507. // Rendering
  11508. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11509. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11510. submesh = sortedArray[subIndex];
  11511. submesh.render();
  11512. }
  11513. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11514. }
  11515. return true;
  11516. };
  11517. RenderingGroup.prototype.prepare = function () {
  11518. this._opaqueSubMeshes.reset();
  11519. this._transparentSubMeshes.reset();
  11520. this._alphaTestSubMeshes.reset();
  11521. };
  11522. RenderingGroup.prototype.dispatch = function (subMesh) {
  11523. var material = subMesh.getMaterial();
  11524. var mesh = subMesh.getMesh();
  11525. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11526. this._transparentSubMeshes.push(subMesh);
  11527. }
  11528. else if (material.needAlphaTesting()) {
  11529. this._alphaTestSubMeshes.push(subMesh);
  11530. }
  11531. else {
  11532. this._opaqueSubMeshes.push(subMesh); // Opaque
  11533. }
  11534. };
  11535. return RenderingGroup;
  11536. })();
  11537. BABYLON.RenderingGroup = RenderingGroup;
  11538. })(BABYLON || (BABYLON = {}));
  11539. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11540. (function (BABYLON) {
  11541. var RenderingManager = (function () {
  11542. function RenderingManager(scene) {
  11543. this._renderingGroups = new Array();
  11544. this._scene = scene;
  11545. }
  11546. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11547. if (this._scene._activeParticleSystems.length === 0) {
  11548. return;
  11549. }
  11550. // Particles
  11551. var beforeParticlesDate = BABYLON.Tools.Now;
  11552. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11553. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11554. if (particleSystem.renderingGroupId !== index) {
  11555. continue;
  11556. }
  11557. this._clearDepthBuffer();
  11558. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11559. this._scene._activeParticles += particleSystem.render();
  11560. }
  11561. }
  11562. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11563. };
  11564. RenderingManager.prototype._renderSprites = function (index) {
  11565. if (this._scene.spriteManagers.length === 0) {
  11566. return;
  11567. }
  11568. // Sprites
  11569. var beforeSpritessDate = BABYLON.Tools.Now;
  11570. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11571. var spriteManager = this._scene.spriteManagers[id];
  11572. if (spriteManager.renderingGroupId === index) {
  11573. this._clearDepthBuffer();
  11574. spriteManager.render();
  11575. }
  11576. }
  11577. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11578. };
  11579. RenderingManager.prototype._clearDepthBuffer = function () {
  11580. if (this._depthBufferAlreadyCleaned) {
  11581. return;
  11582. }
  11583. this._scene.getEngine().clear(0, false, true);
  11584. this._depthBufferAlreadyCleaned = true;
  11585. };
  11586. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11587. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11588. this._depthBufferAlreadyCleaned = false;
  11589. var renderingGroup = this._renderingGroups[index];
  11590. if (renderingGroup) {
  11591. this._clearDepthBuffer();
  11592. if (!renderingGroup.render(customRenderFunction)) {
  11593. this._renderingGroups.splice(index, 1);
  11594. }
  11595. }
  11596. if (renderSprites) {
  11597. this._renderSprites(index);
  11598. }
  11599. if (renderParticles) {
  11600. this._renderParticles(index, activeMeshes);
  11601. }
  11602. }
  11603. };
  11604. RenderingManager.prototype.reset = function () {
  11605. for (var index in this._renderingGroups) {
  11606. var renderingGroup = this._renderingGroups[index];
  11607. renderingGroup.prepare();
  11608. }
  11609. };
  11610. RenderingManager.prototype.dispatch = function (subMesh) {
  11611. var mesh = subMesh.getMesh();
  11612. var renderingGroupId = mesh.renderingGroupId || 0;
  11613. if (!this._renderingGroups[renderingGroupId]) {
  11614. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11615. }
  11616. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11617. };
  11618. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11619. return RenderingManager;
  11620. })();
  11621. BABYLON.RenderingManager = RenderingManager;
  11622. })(BABYLON || (BABYLON = {}));
  11623. //# sourceMappingURL=babylon.renderingManager.js.map
  11624. var BABYLON;
  11625. (function (BABYLON) {
  11626. var Texture = (function (_super) {
  11627. __extends(Texture, _super);
  11628. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11629. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11630. if (onLoad === void 0) { onLoad = null; }
  11631. if (onError === void 0) { onError = null; }
  11632. if (buffer === void 0) { buffer = null; }
  11633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11634. _super.call(this, scene);
  11635. this.uOffset = 0;
  11636. this.vOffset = 0;
  11637. this.uScale = 1.0;
  11638. this.vScale = 1.0;
  11639. this.uAng = 0;
  11640. this.vAng = 0;
  11641. this.wAng = 0;
  11642. this.name = url;
  11643. this.url = url;
  11644. this._noMipmap = noMipmap;
  11645. this._invertY = invertY;
  11646. this._samplingMode = samplingMode;
  11647. this._buffer = buffer;
  11648. this._deleteBuffer = deleteBuffer;
  11649. if (!url) {
  11650. return;
  11651. }
  11652. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11653. if (!this._texture) {
  11654. if (!scene.useDelayedTextureLoading) {
  11655. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11656. if (deleteBuffer) {
  11657. delete this._buffer;
  11658. }
  11659. }
  11660. else {
  11661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11662. }
  11663. }
  11664. }
  11665. Texture.prototype.delayLoad = function () {
  11666. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11667. return;
  11668. }
  11669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11670. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11671. if (!this._texture) {
  11672. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11673. if (this._deleteBuffer) {
  11674. delete this._buffer;
  11675. }
  11676. }
  11677. };
  11678. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11679. x -= this.uOffset + 0.5;
  11680. y -= this.vOffset + 0.5;
  11681. z -= 0.5;
  11682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11683. t.x *= this.uScale;
  11684. t.y *= this.vScale;
  11685. t.x += 0.5;
  11686. t.y += 0.5;
  11687. t.z += 0.5;
  11688. };
  11689. Texture.prototype.getTextureMatrix = function () {
  11690. 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) {
  11691. return this._cachedTextureMatrix;
  11692. }
  11693. this._cachedUOffset = this.uOffset;
  11694. this._cachedVOffset = this.vOffset;
  11695. this._cachedUScale = this.uScale;
  11696. this._cachedVScale = this.vScale;
  11697. this._cachedUAng = this.uAng;
  11698. this._cachedVAng = this.vAng;
  11699. this._cachedWAng = this.wAng;
  11700. if (!this._cachedTextureMatrix) {
  11701. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11702. this._rowGenerationMatrix = new BABYLON.Matrix();
  11703. this._t0 = BABYLON.Vector3.Zero();
  11704. this._t1 = BABYLON.Vector3.Zero();
  11705. this._t2 = BABYLON.Vector3.Zero();
  11706. }
  11707. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11708. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11709. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11710. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11711. this._t1.subtractInPlace(this._t0);
  11712. this._t2.subtractInPlace(this._t0);
  11713. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11714. this._cachedTextureMatrix.m[0] = this._t1.x;
  11715. this._cachedTextureMatrix.m[1] = this._t1.y;
  11716. this._cachedTextureMatrix.m[2] = this._t1.z;
  11717. this._cachedTextureMatrix.m[4] = this._t2.x;
  11718. this._cachedTextureMatrix.m[5] = this._t2.y;
  11719. this._cachedTextureMatrix.m[6] = this._t2.z;
  11720. this._cachedTextureMatrix.m[8] = this._t0.x;
  11721. this._cachedTextureMatrix.m[9] = this._t0.y;
  11722. this._cachedTextureMatrix.m[10] = this._t0.z;
  11723. return this._cachedTextureMatrix;
  11724. };
  11725. Texture.prototype.getReflectionTextureMatrix = function () {
  11726. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11727. return this._cachedTextureMatrix;
  11728. }
  11729. if (!this._cachedTextureMatrix) {
  11730. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11731. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11732. }
  11733. this._cachedCoordinatesMode = this.coordinatesMode;
  11734. switch (this.coordinatesMode) {
  11735. case BABYLON.Texture.SPHERICAL_MODE:
  11736. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11737. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11738. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11739. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11740. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11741. break;
  11742. case BABYLON.Texture.PLANAR_MODE:
  11743. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11744. this._cachedTextureMatrix[0] = this.uScale;
  11745. this._cachedTextureMatrix[5] = this.vScale;
  11746. this._cachedTextureMatrix[12] = this.uOffset;
  11747. this._cachedTextureMatrix[13] = this.vOffset;
  11748. break;
  11749. case BABYLON.Texture.PROJECTION_MODE:
  11750. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11751. this._projectionModeMatrix.m[0] = 0.5;
  11752. this._projectionModeMatrix.m[5] = -0.5;
  11753. this._projectionModeMatrix.m[10] = 0.0;
  11754. this._projectionModeMatrix.m[12] = 0.5;
  11755. this._projectionModeMatrix.m[13] = 0.5;
  11756. this._projectionModeMatrix.m[14] = 1.0;
  11757. this._projectionModeMatrix.m[15] = 1.0;
  11758. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11759. break;
  11760. default:
  11761. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11762. break;
  11763. }
  11764. return this._cachedTextureMatrix;
  11765. };
  11766. Texture.prototype.clone = function () {
  11767. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11768. // Base texture
  11769. newTexture.hasAlpha = this.hasAlpha;
  11770. newTexture.level = this.level;
  11771. newTexture.wrapU = this.wrapU;
  11772. newTexture.wrapV = this.wrapV;
  11773. newTexture.coordinatesIndex = this.coordinatesIndex;
  11774. newTexture.coordinatesMode = this.coordinatesMode;
  11775. // Texture
  11776. newTexture.uOffset = this.uOffset;
  11777. newTexture.vOffset = this.vOffset;
  11778. newTexture.uScale = this.uScale;
  11779. newTexture.vScale = this.vScale;
  11780. newTexture.uAng = this.uAng;
  11781. newTexture.vAng = this.vAng;
  11782. newTexture.wAng = this.wAng;
  11783. return newTexture;
  11784. };
  11785. // Statics
  11786. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11787. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11788. if (onLoad === void 0) { onLoad = null; }
  11789. if (onError === void 0) { onError = null; }
  11790. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11791. };
  11792. // Constants
  11793. Texture.NEAREST_SAMPLINGMODE = 1;
  11794. Texture.BILINEAR_SAMPLINGMODE = 2;
  11795. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11796. Texture.EXPLICIT_MODE = 0;
  11797. Texture.SPHERICAL_MODE = 1;
  11798. Texture.PLANAR_MODE = 2;
  11799. Texture.CUBIC_MODE = 3;
  11800. Texture.PROJECTION_MODE = 4;
  11801. Texture.SKYBOX_MODE = 5;
  11802. Texture.CLAMP_ADDRESSMODE = 0;
  11803. Texture.WRAP_ADDRESSMODE = 1;
  11804. Texture.MIRROR_ADDRESSMODE = 2;
  11805. return Texture;
  11806. })(BABYLON.BaseTexture);
  11807. BABYLON.Texture = Texture;
  11808. })(BABYLON || (BABYLON = {}));
  11809. //# sourceMappingURL=babylon.texture.js.map
  11810. var BABYLON;
  11811. (function (BABYLON) {
  11812. var CubeTexture = (function (_super) {
  11813. __extends(CubeTexture, _super);
  11814. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11815. _super.call(this, scene);
  11816. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11817. this.name = rootUrl;
  11818. this.url = rootUrl;
  11819. this._noMipmap = noMipmap;
  11820. this.hasAlpha = false;
  11821. this._texture = this._getFromCache(rootUrl, noMipmap);
  11822. if (!extensions) {
  11823. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11824. }
  11825. this._extensions = extensions;
  11826. if (!this._texture) {
  11827. if (!scene.useDelayedTextureLoading) {
  11828. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11829. }
  11830. else {
  11831. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11832. }
  11833. }
  11834. this.isCube = true;
  11835. this._textureMatrix = BABYLON.Matrix.Identity();
  11836. }
  11837. CubeTexture.prototype.clone = function () {
  11838. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11839. // Base texture
  11840. newTexture.level = this.level;
  11841. newTexture.wrapU = this.wrapU;
  11842. newTexture.wrapV = this.wrapV;
  11843. newTexture.coordinatesIndex = this.coordinatesIndex;
  11844. newTexture.coordinatesMode = this.coordinatesMode;
  11845. return newTexture;
  11846. };
  11847. // Methods
  11848. CubeTexture.prototype.delayLoad = function () {
  11849. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11850. return;
  11851. }
  11852. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11853. this._texture = this._getFromCache(this.url, this._noMipmap);
  11854. if (!this._texture) {
  11855. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11856. }
  11857. };
  11858. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11859. return this._textureMatrix;
  11860. };
  11861. return CubeTexture;
  11862. })(BABYLON.BaseTexture);
  11863. BABYLON.CubeTexture = CubeTexture;
  11864. })(BABYLON || (BABYLON = {}));
  11865. //# sourceMappingURL=babylon.cubeTexture.js.map
  11866. var BABYLON;
  11867. (function (BABYLON) {
  11868. var RenderTargetTexture = (function (_super) {
  11869. __extends(RenderTargetTexture, _super);
  11870. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11871. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11872. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11873. _super.call(this, null, scene, !generateMipMaps);
  11874. this.renderList = new Array();
  11875. this.renderParticles = true;
  11876. this.renderSprites = false;
  11877. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11878. this._currentRefreshId = -1;
  11879. this._refreshRate = 1;
  11880. this.name = name;
  11881. this.isRenderTarget = true;
  11882. this._size = size;
  11883. this._generateMipMaps = generateMipMaps;
  11884. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11885. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11886. // Rendering groups
  11887. this._renderingManager = new BABYLON.RenderingManager(scene);
  11888. }
  11889. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11890. this._currentRefreshId = -1;
  11891. };
  11892. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11893. get: function () {
  11894. return this._refreshRate;
  11895. },
  11896. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11897. set: function (value) {
  11898. this._refreshRate = value;
  11899. this.resetRefreshCounter();
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. RenderTargetTexture.prototype._shouldRender = function () {
  11905. if (this._currentRefreshId === -1) {
  11906. this._currentRefreshId = 1;
  11907. return true;
  11908. }
  11909. if (this.refreshRate === this._currentRefreshId) {
  11910. this._currentRefreshId = 1;
  11911. return true;
  11912. }
  11913. this._currentRefreshId++;
  11914. return false;
  11915. };
  11916. RenderTargetTexture.prototype.isReady = function () {
  11917. if (!this.getScene().renderTargetsEnabled) {
  11918. return false;
  11919. }
  11920. return _super.prototype.isReady.call(this);
  11921. };
  11922. RenderTargetTexture.prototype.getRenderSize = function () {
  11923. return this._size;
  11924. };
  11925. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11926. get: function () {
  11927. return true;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. RenderTargetTexture.prototype.scale = function (ratio) {
  11933. var newSize = this._size * ratio;
  11934. this.resize(newSize, this._generateMipMaps);
  11935. };
  11936. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11937. this.releaseInternalTexture();
  11938. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11939. };
  11940. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11941. var scene = this.getScene();
  11942. var engine = scene.getEngine();
  11943. if (!this.activeCamera) {
  11944. this.activeCamera = scene.activeCamera;
  11945. }
  11946. if (this._waitingRenderList) {
  11947. this.renderList = [];
  11948. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11949. var id = this._waitingRenderList[index];
  11950. this.renderList.push(scene.getMeshByID(id));
  11951. }
  11952. delete this._waitingRenderList;
  11953. }
  11954. if (this.renderList && this.renderList.length === 0) {
  11955. return;
  11956. }
  11957. // Bind
  11958. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11959. engine.bindFramebuffer(this._texture);
  11960. }
  11961. // Clear
  11962. engine.clear(scene.clearColor, true, true);
  11963. this._renderingManager.reset();
  11964. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11965. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11966. var mesh = currentRenderList[meshIndex];
  11967. if (mesh) {
  11968. if (!mesh.isReady()) {
  11969. // Reset _currentRefreshId
  11970. this.resetRefreshCounter();
  11971. continue;
  11972. }
  11973. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11974. mesh._activate(scene.getRenderId());
  11975. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11976. var subMesh = mesh.subMeshes[subIndex];
  11977. scene._activeVertices += subMesh.indexCount;
  11978. this._renderingManager.dispatch(subMesh);
  11979. }
  11980. }
  11981. }
  11982. }
  11983. if (!this._doNotChangeAspectRatio) {
  11984. scene.updateTransformMatrix(true);
  11985. }
  11986. if (this.onBeforeRender) {
  11987. this.onBeforeRender();
  11988. }
  11989. // Render
  11990. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11991. if (useCameraPostProcess) {
  11992. scene.postProcessManager._finalizeFrame(false, this._texture);
  11993. }
  11994. if (this.onAfterRender) {
  11995. this.onAfterRender();
  11996. }
  11997. // Unbind
  11998. engine.unBindFramebuffer(this._texture);
  11999. if (!this._doNotChangeAspectRatio) {
  12000. scene.updateTransformMatrix(true);
  12001. }
  12002. };
  12003. RenderTargetTexture.prototype.clone = function () {
  12004. var textureSize = this.getSize();
  12005. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12006. // Base texture
  12007. newTexture.hasAlpha = this.hasAlpha;
  12008. newTexture.level = this.level;
  12009. // RenderTarget Texture
  12010. newTexture.coordinatesMode = this.coordinatesMode;
  12011. newTexture.renderList = this.renderList.slice(0);
  12012. return newTexture;
  12013. };
  12014. return RenderTargetTexture;
  12015. })(BABYLON.Texture);
  12016. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12017. })(BABYLON || (BABYLON = {}));
  12018. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12019. var BABYLON;
  12020. (function (BABYLON) {
  12021. var ProceduralTexture = (function (_super) {
  12022. __extends(ProceduralTexture, _super);
  12023. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12024. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12025. _super.call(this, null, scene, !generateMipMaps);
  12026. this._currentRefreshId = -1;
  12027. this._refreshRate = 1;
  12028. this._vertexDeclaration = [2];
  12029. this._vertexStrideSize = 2 * 4;
  12030. this._uniforms = new Array();
  12031. this._samplers = new Array();
  12032. this._textures = new Array();
  12033. this._floats = new Array();
  12034. this._floatsArrays = {};
  12035. this._colors3 = new Array();
  12036. this._colors4 = new Array();
  12037. this._vectors2 = new Array();
  12038. this._vectors3 = new Array();
  12039. this._matrices = new Array();
  12040. this._fallbackTextureUsed = false;
  12041. scene._proceduralTextures.push(this);
  12042. this.name = name;
  12043. this.isRenderTarget = true;
  12044. this._size = size;
  12045. this._generateMipMaps = generateMipMaps;
  12046. this.setFragment(fragment);
  12047. this._fallbackTexture = fallbackTexture;
  12048. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12049. // VBO
  12050. var vertices = [];
  12051. vertices.push(1, 1);
  12052. vertices.push(-1, 1);
  12053. vertices.push(-1, -1);
  12054. vertices.push(1, -1);
  12055. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12056. // Indices
  12057. var indices = [];
  12058. indices.push(0);
  12059. indices.push(1);
  12060. indices.push(2);
  12061. indices.push(0);
  12062. indices.push(2);
  12063. indices.push(3);
  12064. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12065. }
  12066. ProceduralTexture.prototype.reset = function () {
  12067. if (this._effect === undefined) {
  12068. return;
  12069. }
  12070. var engine = this.getScene().getEngine();
  12071. engine._releaseEffect(this._effect);
  12072. };
  12073. ProceduralTexture.prototype.isReady = function () {
  12074. var _this = this;
  12075. var engine = this.getScene().getEngine();
  12076. var shaders;
  12077. if (!this._fragment) {
  12078. return false;
  12079. }
  12080. if (this._fallbackTextureUsed) {
  12081. return true;
  12082. }
  12083. if (this._fragment.fragmentElement !== undefined) {
  12084. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12085. }
  12086. else {
  12087. shaders = { vertex: "procedural", fragment: this._fragment };
  12088. }
  12089. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12090. _this.releaseInternalTexture();
  12091. if (_this._fallbackTexture) {
  12092. _this._texture = _this._fallbackTexture._texture;
  12093. _this._texture.references++;
  12094. }
  12095. _this._fallbackTextureUsed = true;
  12096. });
  12097. return this._effect.isReady();
  12098. };
  12099. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12100. this._currentRefreshId = -1;
  12101. };
  12102. ProceduralTexture.prototype.setFragment = function (fragment) {
  12103. this._fragment = fragment;
  12104. };
  12105. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12106. get: function () {
  12107. return this._refreshRate;
  12108. },
  12109. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12110. set: function (value) {
  12111. this._refreshRate = value;
  12112. this.resetRefreshCounter();
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. ProceduralTexture.prototype._shouldRender = function () {
  12118. if (!this.isReady() || !this._texture) {
  12119. return false;
  12120. }
  12121. if (this._fallbackTextureUsed) {
  12122. return false;
  12123. }
  12124. if (this._currentRefreshId === -1) {
  12125. this._currentRefreshId = 1;
  12126. return true;
  12127. }
  12128. if (this.refreshRate === this._currentRefreshId) {
  12129. this._currentRefreshId = 1;
  12130. return true;
  12131. }
  12132. this._currentRefreshId++;
  12133. return false;
  12134. };
  12135. ProceduralTexture.prototype.getRenderSize = function () {
  12136. return this._size;
  12137. };
  12138. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12139. if (this._fallbackTextureUsed) {
  12140. return;
  12141. }
  12142. this.releaseInternalTexture();
  12143. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12144. };
  12145. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12146. if (this._uniforms.indexOf(uniformName) === -1) {
  12147. this._uniforms.push(uniformName);
  12148. }
  12149. };
  12150. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12151. if (this._samplers.indexOf(name) === -1) {
  12152. this._samplers.push(name);
  12153. }
  12154. this._textures[name] = texture;
  12155. return this;
  12156. };
  12157. ProceduralTexture.prototype.setFloat = function (name, value) {
  12158. this._checkUniform(name);
  12159. this._floats[name] = value;
  12160. return this;
  12161. };
  12162. ProceduralTexture.prototype.setFloats = function (name, value) {
  12163. this._checkUniform(name);
  12164. this._floatsArrays[name] = value;
  12165. return this;
  12166. };
  12167. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12168. this._checkUniform(name);
  12169. this._colors3[name] = value;
  12170. return this;
  12171. };
  12172. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12173. this._checkUniform(name);
  12174. this._colors4[name] = value;
  12175. return this;
  12176. };
  12177. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12178. this._checkUniform(name);
  12179. this._vectors2[name] = value;
  12180. return this;
  12181. };
  12182. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12183. this._checkUniform(name);
  12184. this._vectors3[name] = value;
  12185. return this;
  12186. };
  12187. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12188. this._checkUniform(name);
  12189. this._matrices[name] = value;
  12190. return this;
  12191. };
  12192. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12193. var scene = this.getScene();
  12194. var engine = scene.getEngine();
  12195. engine.bindFramebuffer(this._texture);
  12196. // Clear
  12197. engine.clear(scene.clearColor, true, true);
  12198. // Render
  12199. engine.enableEffect(this._effect);
  12200. engine.setState(false);
  12201. for (var name in this._textures) {
  12202. this._effect.setTexture(name, this._textures[name]);
  12203. }
  12204. for (name in this._floats) {
  12205. this._effect.setFloat(name, this._floats[name]);
  12206. }
  12207. for (name in this._floatsArrays) {
  12208. this._effect.setArray(name, this._floatsArrays[name]);
  12209. }
  12210. for (name in this._colors3) {
  12211. this._effect.setColor3(name, this._colors3[name]);
  12212. }
  12213. for (name in this._colors4) {
  12214. var color = this._colors4[name];
  12215. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12216. }
  12217. for (name in this._vectors2) {
  12218. this._effect.setVector2(name, this._vectors2[name]);
  12219. }
  12220. for (name in this._vectors3) {
  12221. this._effect.setVector3(name, this._vectors3[name]);
  12222. }
  12223. for (name in this._matrices) {
  12224. this._effect.setMatrix(name, this._matrices[name]);
  12225. }
  12226. // VBOs
  12227. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12228. // Draw order
  12229. engine.draw(true, 0, 6);
  12230. // Unbind
  12231. engine.unBindFramebuffer(this._texture);
  12232. };
  12233. ProceduralTexture.prototype.clone = function () {
  12234. var textureSize = this.getSize();
  12235. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12236. // Base texture
  12237. newTexture.hasAlpha = this.hasAlpha;
  12238. newTexture.level = this.level;
  12239. // RenderTarget Texture
  12240. newTexture.coordinatesMode = this.coordinatesMode;
  12241. return newTexture;
  12242. };
  12243. ProceduralTexture.prototype.dispose = function () {
  12244. var index = this.getScene()._proceduralTextures.indexOf(this);
  12245. if (index >= 0) {
  12246. this.getScene()._proceduralTextures.splice(index, 1);
  12247. }
  12248. _super.prototype.dispose.call(this);
  12249. };
  12250. return ProceduralTexture;
  12251. })(BABYLON.Texture);
  12252. BABYLON.ProceduralTexture = ProceduralTexture;
  12253. })(BABYLON || (BABYLON = {}));
  12254. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12255. var BABYLON;
  12256. (function (BABYLON) {
  12257. var WoodProceduralTexture = (function (_super) {
  12258. __extends(WoodProceduralTexture, _super);
  12259. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12260. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12261. this._ampScale = 100.0;
  12262. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12263. this.updateShaderUniforms();
  12264. this.refreshRate = 0;
  12265. }
  12266. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12267. this.setFloat("ampScale", this._ampScale);
  12268. this.setColor3("woodColor", this._woodColor);
  12269. };
  12270. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12271. get: function () {
  12272. return this._ampScale;
  12273. },
  12274. set: function (value) {
  12275. this._ampScale = value;
  12276. this.updateShaderUniforms();
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12282. get: function () {
  12283. return this._woodColor;
  12284. },
  12285. set: function (value) {
  12286. this._woodColor = value;
  12287. this.updateShaderUniforms();
  12288. },
  12289. enumerable: true,
  12290. configurable: true
  12291. });
  12292. return WoodProceduralTexture;
  12293. })(BABYLON.ProceduralTexture);
  12294. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12295. var FireProceduralTexture = (function (_super) {
  12296. __extends(FireProceduralTexture, _super);
  12297. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12298. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12299. this._time = 0.0;
  12300. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12301. this._shift = 1.6;
  12302. this._autoGenerateTime = true;
  12303. this._alphaThreshold = 0.5;
  12304. this._fireColors = FireProceduralTexture.RedFireColors;
  12305. this.updateShaderUniforms();
  12306. this.refreshRate = 1;
  12307. }
  12308. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12309. this.setFloat("time", this._time);
  12310. this.setVector2("speed", this._speed);
  12311. this.setFloat("shift", this._shift);
  12312. this.setColor3("c1", this._fireColors[0]);
  12313. this.setColor3("c2", this._fireColors[1]);
  12314. this.setColor3("c3", this._fireColors[2]);
  12315. this.setColor3("c4", this._fireColors[3]);
  12316. this.setColor3("c5", this._fireColors[4]);
  12317. this.setColor3("c6", this._fireColors[5]);
  12318. this.setFloat("alphaThreshold", this._alphaThreshold);
  12319. };
  12320. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12321. if (this._autoGenerateTime) {
  12322. this._time += this.getScene().getAnimationRatio() * 0.03;
  12323. this.updateShaderUniforms();
  12324. }
  12325. _super.prototype.render.call(this, useCameraPostProcess);
  12326. };
  12327. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12328. get: function () {
  12329. return [
  12330. new BABYLON.Color3(0.5, 0.0, 1.0),
  12331. new BABYLON.Color3(0.9, 0.0, 1.0),
  12332. new BABYLON.Color3(0.2, 0.0, 1.0),
  12333. new BABYLON.Color3(1.0, 0.9, 1.0),
  12334. new BABYLON.Color3(0.1, 0.1, 1.0),
  12335. new BABYLON.Color3(0.9, 0.9, 1.0)
  12336. ];
  12337. },
  12338. enumerable: true,
  12339. configurable: true
  12340. });
  12341. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12342. get: function () {
  12343. return [
  12344. new BABYLON.Color3(0.5, 1.0, 0.0),
  12345. new BABYLON.Color3(0.5, 1.0, 0.0),
  12346. new BABYLON.Color3(0.3, 0.4, 0.0),
  12347. new BABYLON.Color3(0.5, 1.0, 0.0),
  12348. new BABYLON.Color3(0.2, 0.0, 0.0),
  12349. new BABYLON.Color3(0.5, 1.0, 0.0)
  12350. ];
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12356. get: function () {
  12357. return [
  12358. new BABYLON.Color3(0.5, 0.0, 0.1),
  12359. new BABYLON.Color3(0.9, 0.0, 0.0),
  12360. new BABYLON.Color3(0.2, 0.0, 0.0),
  12361. new BABYLON.Color3(1.0, 0.9, 0.0),
  12362. new BABYLON.Color3(0.1, 0.1, 0.1),
  12363. new BABYLON.Color3(0.9, 0.9, 0.9)
  12364. ];
  12365. },
  12366. enumerable: true,
  12367. configurable: true
  12368. });
  12369. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12370. get: function () {
  12371. return [
  12372. new BABYLON.Color3(0.1, 0.0, 0.5),
  12373. new BABYLON.Color3(0.0, 0.0, 0.5),
  12374. new BABYLON.Color3(0.1, 0.0, 0.2),
  12375. new BABYLON.Color3(0.0, 0.0, 1.0),
  12376. new BABYLON.Color3(0.1, 0.2, 0.3),
  12377. new BABYLON.Color3(0.0, 0.2, 0.9)
  12378. ];
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12384. get: function () {
  12385. return this._fireColors;
  12386. },
  12387. set: function (value) {
  12388. this._fireColors = value;
  12389. this.updateShaderUniforms();
  12390. },
  12391. enumerable: true,
  12392. configurable: true
  12393. });
  12394. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12395. get: function () {
  12396. return this._time;
  12397. },
  12398. set: function (value) {
  12399. this._time = value;
  12400. this.updateShaderUniforms();
  12401. },
  12402. enumerable: true,
  12403. configurable: true
  12404. });
  12405. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12406. get: function () {
  12407. return this._speed;
  12408. },
  12409. set: function (value) {
  12410. this._speed = value;
  12411. this.updateShaderUniforms();
  12412. },
  12413. enumerable: true,
  12414. configurable: true
  12415. });
  12416. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12417. get: function () {
  12418. return this._shift;
  12419. },
  12420. set: function (value) {
  12421. this._shift = value;
  12422. this.updateShaderUniforms();
  12423. },
  12424. enumerable: true,
  12425. configurable: true
  12426. });
  12427. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12428. get: function () {
  12429. return this._alphaThreshold;
  12430. },
  12431. set: function (value) {
  12432. this._alphaThreshold = value;
  12433. this.updateShaderUniforms();
  12434. },
  12435. enumerable: true,
  12436. configurable: true
  12437. });
  12438. return FireProceduralTexture;
  12439. })(BABYLON.ProceduralTexture);
  12440. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12441. var CloudProceduralTexture = (function (_super) {
  12442. __extends(CloudProceduralTexture, _super);
  12443. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12444. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12445. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12446. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12447. this.updateShaderUniforms();
  12448. this.refreshRate = 0;
  12449. }
  12450. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12451. this.setColor3("skyColor", this._skyColor);
  12452. this.setColor3("cloudColor", this._cloudColor);
  12453. };
  12454. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12455. get: function () {
  12456. return this._skyColor;
  12457. },
  12458. set: function (value) {
  12459. this._skyColor = value;
  12460. this.updateShaderUniforms();
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12466. get: function () {
  12467. return this._cloudColor;
  12468. },
  12469. set: function (value) {
  12470. this._cloudColor = value;
  12471. this.updateShaderUniforms();
  12472. },
  12473. enumerable: true,
  12474. configurable: true
  12475. });
  12476. return CloudProceduralTexture;
  12477. })(BABYLON.ProceduralTexture);
  12478. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12479. var GrassProceduralTexture = (function (_super) {
  12480. __extends(GrassProceduralTexture, _super);
  12481. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12482. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12483. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12484. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12485. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12486. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12487. this._grassColors = [
  12488. new BABYLON.Color3(0.29, 0.38, 0.02),
  12489. new BABYLON.Color3(0.36, 0.49, 0.09),
  12490. new BABYLON.Color3(0.51, 0.6, 0.28)
  12491. ];
  12492. this.updateShaderUniforms();
  12493. this.refreshRate = 0;
  12494. }
  12495. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12496. this.setColor3("herb1Color", this._grassColors[0]);
  12497. this.setColor3("herb2Color", this._grassColors[1]);
  12498. this.setColor3("herb3Color", this._grassColors[2]);
  12499. this.setColor3("groundColor", this._groundColor);
  12500. };
  12501. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12502. get: function () {
  12503. return this._grassColors;
  12504. },
  12505. set: function (value) {
  12506. this._grassColors = value;
  12507. this.updateShaderUniforms();
  12508. },
  12509. enumerable: true,
  12510. configurable: true
  12511. });
  12512. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12513. get: function () {
  12514. return this._groundColor;
  12515. },
  12516. set: function (value) {
  12517. this.groundColor = value;
  12518. this.updateShaderUniforms();
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. return GrassProceduralTexture;
  12524. })(BABYLON.ProceduralTexture);
  12525. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12526. var RoadProceduralTexture = (function (_super) {
  12527. __extends(RoadProceduralTexture, _super);
  12528. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12529. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12530. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12531. this.updateShaderUniforms();
  12532. this.refreshRate = 0;
  12533. }
  12534. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12535. this.setColor3("roadColor", this._roadColor);
  12536. };
  12537. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12538. get: function () {
  12539. return this._roadColor;
  12540. },
  12541. set: function (value) {
  12542. this._roadColor = value;
  12543. this.updateShaderUniforms();
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. return RoadProceduralTexture;
  12549. })(BABYLON.ProceduralTexture);
  12550. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12551. var BrickProceduralTexture = (function (_super) {
  12552. __extends(BrickProceduralTexture, _super);
  12553. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12554. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12555. this._numberOfBricksHeight = 15;
  12556. this._numberOfBricksWidth = 5;
  12557. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12558. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12559. this.updateShaderUniforms();
  12560. this.refreshRate = 0;
  12561. }
  12562. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12563. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12564. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12565. this.setColor3("brickColor", this._brickColor);
  12566. this.setColor3("jointColor", this._jointColor);
  12567. };
  12568. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12569. get: function () {
  12570. return this._numberOfBricksHeight;
  12571. },
  12572. enumerable: true,
  12573. configurable: true
  12574. });
  12575. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12576. set: function (value) {
  12577. this._numberOfBricksHeight = value;
  12578. this.updateShaderUniforms();
  12579. },
  12580. enumerable: true,
  12581. configurable: true
  12582. });
  12583. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12584. get: function () {
  12585. return this._numberOfBricksWidth;
  12586. },
  12587. set: function (value) {
  12588. this._numberOfBricksHeight = value;
  12589. this.updateShaderUniforms();
  12590. },
  12591. enumerable: true,
  12592. configurable: true
  12593. });
  12594. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12595. get: function () {
  12596. return this._jointColor;
  12597. },
  12598. set: function (value) {
  12599. this._jointColor = value;
  12600. this.updateShaderUniforms();
  12601. },
  12602. enumerable: true,
  12603. configurable: true
  12604. });
  12605. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12606. get: function () {
  12607. return this._brickColor;
  12608. },
  12609. set: function (value) {
  12610. this._brickColor = value;
  12611. this.updateShaderUniforms();
  12612. },
  12613. enumerable: true,
  12614. configurable: true
  12615. });
  12616. return BrickProceduralTexture;
  12617. })(BABYLON.ProceduralTexture);
  12618. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12619. var MarbleProceduralTexture = (function (_super) {
  12620. __extends(MarbleProceduralTexture, _super);
  12621. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12622. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12623. this._numberOfTilesHeight = 3;
  12624. this._numberOfTilesWidth = 3;
  12625. this._amplitude = 9.0;
  12626. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12627. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12628. this.updateShaderUniforms();
  12629. this.refreshRate = 0;
  12630. }
  12631. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12632. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12633. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12634. this.setFloat("amplitude", this._amplitude);
  12635. this.setColor3("marbleColor", this._marbleColor);
  12636. this.setColor3("jointColor", this._jointColor);
  12637. };
  12638. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12639. get: function () {
  12640. return this._numberOfTilesHeight;
  12641. },
  12642. set: function (value) {
  12643. this._numberOfTilesHeight = value;
  12644. this.updateShaderUniforms();
  12645. },
  12646. enumerable: true,
  12647. configurable: true
  12648. });
  12649. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12650. get: function () {
  12651. return this._numberOfTilesWidth;
  12652. },
  12653. set: function (value) {
  12654. this._numberOfTilesWidth = value;
  12655. this.updateShaderUniforms();
  12656. },
  12657. enumerable: true,
  12658. configurable: true
  12659. });
  12660. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12661. get: function () {
  12662. return this._jointColor;
  12663. },
  12664. set: function (value) {
  12665. this._jointColor = value;
  12666. this.updateShaderUniforms();
  12667. },
  12668. enumerable: true,
  12669. configurable: true
  12670. });
  12671. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12672. get: function () {
  12673. return this._marbleColor;
  12674. },
  12675. set: function (value) {
  12676. this._marbleColor = value;
  12677. this.updateShaderUniforms();
  12678. },
  12679. enumerable: true,
  12680. configurable: true
  12681. });
  12682. return MarbleProceduralTexture;
  12683. })(BABYLON.ProceduralTexture);
  12684. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12685. })(BABYLON || (BABYLON = {}));
  12686. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12687. var BABYLON;
  12688. (function (BABYLON) {
  12689. var CustomProceduralTexture = (function (_super) {
  12690. __extends(CustomProceduralTexture, _super);
  12691. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12692. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12693. this._animate = true;
  12694. this._time = 0;
  12695. this._texturePath = texturePath;
  12696. //Try to load json
  12697. this.loadJson(texturePath);
  12698. this.refreshRate = 1;
  12699. }
  12700. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12701. var _this = this;
  12702. var that = this;
  12703. function noConfigFile() {
  12704. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12705. try {
  12706. that.setFragment(that._texturePath);
  12707. }
  12708. catch (ex) {
  12709. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12710. }
  12711. }
  12712. var configFileUrl = jsonUrl + "/config.json";
  12713. var xhr = new XMLHttpRequest();
  12714. xhr.open("GET", configFileUrl, true);
  12715. xhr.addEventListener("load", function () {
  12716. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12717. try {
  12718. _this._config = JSON.parse(xhr.response);
  12719. _this.updateShaderUniforms();
  12720. _this.updateTextures();
  12721. _this.setFragment(_this._texturePath + "/custom");
  12722. _this._animate = _this._config.animate;
  12723. _this.refreshRate = _this._config.refreshrate;
  12724. }
  12725. catch (ex) {
  12726. noConfigFile();
  12727. }
  12728. }
  12729. else {
  12730. noConfigFile();
  12731. }
  12732. }, false);
  12733. xhr.addEventListener("error", function (event) {
  12734. noConfigFile();
  12735. }, false);
  12736. try {
  12737. xhr.send();
  12738. }
  12739. catch (ex) {
  12740. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12741. }
  12742. };
  12743. CustomProceduralTexture.prototype.isReady = function () {
  12744. if (!_super.prototype.isReady.call(this)) {
  12745. return false;
  12746. }
  12747. for (var name in this._textures) {
  12748. var texture = this._textures[name];
  12749. if (!texture.isReady()) {
  12750. return false;
  12751. }
  12752. }
  12753. return true;
  12754. };
  12755. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12756. if (this._animate) {
  12757. this._time += this.getScene().getAnimationRatio() * 0.03;
  12758. this.updateShaderUniforms();
  12759. }
  12760. _super.prototype.render.call(this, useCameraPostProcess);
  12761. };
  12762. CustomProceduralTexture.prototype.updateTextures = function () {
  12763. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12764. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12765. }
  12766. };
  12767. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12768. if (this._config) {
  12769. for (var j = 0; j < this._config.uniforms.length; j++) {
  12770. var uniform = this._config.uniforms[j];
  12771. switch (uniform.type) {
  12772. case "float":
  12773. this.setFloat(uniform.name, uniform.value);
  12774. break;
  12775. case "color3":
  12776. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12777. break;
  12778. case "color4":
  12779. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12780. break;
  12781. case "vector2":
  12782. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12783. break;
  12784. case "vector3":
  12785. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12786. break;
  12787. }
  12788. }
  12789. }
  12790. this.setFloat("time", this._time);
  12791. };
  12792. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12793. get: function () {
  12794. return this._animate;
  12795. },
  12796. set: function (value) {
  12797. this._animate = value;
  12798. },
  12799. enumerable: true,
  12800. configurable: true
  12801. });
  12802. return CustomProceduralTexture;
  12803. })(BABYLON.ProceduralTexture);
  12804. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12805. })(BABYLON || (BABYLON = {}));
  12806. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12807. var BABYLON;
  12808. (function (BABYLON) {
  12809. var MirrorTexture = (function (_super) {
  12810. __extends(MirrorTexture, _super);
  12811. function MirrorTexture(name, size, scene, generateMipMaps) {
  12812. var _this = this;
  12813. _super.call(this, name, size, scene, generateMipMaps, true);
  12814. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12815. this._transformMatrix = BABYLON.Matrix.Zero();
  12816. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12817. this.onBeforeRender = function () {
  12818. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12819. _this._savedViewMatrix = scene.getViewMatrix();
  12820. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12821. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12822. scene.clipPlane = _this.mirrorPlane;
  12823. scene.getEngine().cullBackFaces = false;
  12824. };
  12825. this.onAfterRender = function () {
  12826. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12827. scene.getEngine().cullBackFaces = true;
  12828. delete scene.clipPlane;
  12829. };
  12830. }
  12831. MirrorTexture.prototype.clone = function () {
  12832. var textureSize = this.getSize();
  12833. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12834. // Base texture
  12835. newTexture.hasAlpha = this.hasAlpha;
  12836. newTexture.level = this.level;
  12837. // Mirror Texture
  12838. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12839. newTexture.renderList = this.renderList.slice(0);
  12840. return newTexture;
  12841. };
  12842. return MirrorTexture;
  12843. })(BABYLON.RenderTargetTexture);
  12844. BABYLON.MirrorTexture = MirrorTexture;
  12845. })(BABYLON || (BABYLON = {}));
  12846. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12847. var BABYLON;
  12848. (function (BABYLON) {
  12849. var DynamicTexture = (function (_super) {
  12850. __extends(DynamicTexture, _super);
  12851. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12853. _super.call(this, null, scene, !generateMipMaps);
  12854. this.name = name;
  12855. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12856. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12857. this._generateMipMaps = generateMipMaps;
  12858. if (options.getContext) {
  12859. this._canvas = options;
  12860. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12861. }
  12862. else {
  12863. this._canvas = document.createElement("canvas");
  12864. if (options.width) {
  12865. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12866. }
  12867. else {
  12868. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12869. }
  12870. }
  12871. var textureSize = this.getSize();
  12872. this._canvas.width = textureSize.width;
  12873. this._canvas.height = textureSize.height;
  12874. this._context = this._canvas.getContext("2d");
  12875. }
  12876. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12877. get: function () {
  12878. return true;
  12879. },
  12880. enumerable: true,
  12881. configurable: true
  12882. });
  12883. DynamicTexture.prototype.scale = function (ratio) {
  12884. var textureSize = this.getSize();
  12885. textureSize.width *= ratio;
  12886. textureSize.height *= ratio;
  12887. this._canvas.width = textureSize.width;
  12888. this._canvas.height = textureSize.height;
  12889. this.releaseInternalTexture();
  12890. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12891. };
  12892. DynamicTexture.prototype.getContext = function () {
  12893. return this._context;
  12894. };
  12895. DynamicTexture.prototype.clear = function () {
  12896. var size = this.getSize();
  12897. this._context.fillRect(0, 0, size.width, size.height);
  12898. };
  12899. DynamicTexture.prototype.update = function (invertY) {
  12900. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12901. };
  12902. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12903. if (update === void 0) { update = true; }
  12904. var size = this.getSize();
  12905. if (clearColor) {
  12906. this._context.fillStyle = clearColor;
  12907. this._context.fillRect(0, 0, size.width, size.height);
  12908. }
  12909. this._context.font = font;
  12910. if (x === null) {
  12911. var textSize = this._context.measureText(text);
  12912. x = (size.width - textSize.width) / 2;
  12913. }
  12914. this._context.fillStyle = color;
  12915. this._context.fillText(text, x, y);
  12916. if (update) {
  12917. this.update(invertY);
  12918. }
  12919. };
  12920. DynamicTexture.prototype.clone = function () {
  12921. var textureSize = this.getSize();
  12922. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12923. // Base texture
  12924. newTexture.hasAlpha = this.hasAlpha;
  12925. newTexture.level = this.level;
  12926. // Dynamic Texture
  12927. newTexture.wrapU = this.wrapU;
  12928. newTexture.wrapV = this.wrapV;
  12929. return newTexture;
  12930. };
  12931. return DynamicTexture;
  12932. })(BABYLON.Texture);
  12933. BABYLON.DynamicTexture = DynamicTexture;
  12934. })(BABYLON || (BABYLON = {}));
  12935. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12936. var BABYLON;
  12937. (function (BABYLON) {
  12938. var VideoTexture = (function (_super) {
  12939. __extends(VideoTexture, _super);
  12940. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12941. var _this = this;
  12942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12943. _super.call(this, null, scene, !generateMipMaps, invertY);
  12944. this._autoLaunch = true;
  12945. this.name = name;
  12946. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12947. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12948. var requiredWidth = size.width || size;
  12949. var requiredHeight = size.height || size;
  12950. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12951. var textureSize = this.getSize();
  12952. this.video = document.createElement("video");
  12953. this.video.width = textureSize.width;
  12954. this.video.height = textureSize.height;
  12955. this.video.autoplay = false;
  12956. this.video.loop = true;
  12957. this.video.addEventListener("canplaythrough", function () {
  12958. if (_this._texture) {
  12959. _this._texture.isReady = true;
  12960. }
  12961. });
  12962. urls.forEach(function (url) {
  12963. var source = document.createElement("source");
  12964. source.src = url;
  12965. _this.video.appendChild(source);
  12966. });
  12967. this._lastUpdate = BABYLON.Tools.Now;
  12968. }
  12969. VideoTexture.prototype.update = function () {
  12970. if (this._autoLaunch) {
  12971. this._autoLaunch = false;
  12972. this.video.play();
  12973. }
  12974. var now = BABYLON.Tools.Now;
  12975. if (now - this._lastUpdate < 15) {
  12976. return false;
  12977. }
  12978. this._lastUpdate = now;
  12979. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12980. return true;
  12981. };
  12982. return VideoTexture;
  12983. })(BABYLON.Texture);
  12984. BABYLON.VideoTexture = VideoTexture;
  12985. })(BABYLON || (BABYLON = {}));
  12986. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12987. (function (BABYLON) {
  12988. var EffectFallbacks = (function () {
  12989. function EffectFallbacks() {
  12990. this._defines = {};
  12991. this._currentRank = 32;
  12992. this._maxRank = -1;
  12993. }
  12994. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12995. if (!this._defines[rank]) {
  12996. if (rank < this._currentRank) {
  12997. this._currentRank = rank;
  12998. }
  12999. if (rank > this._maxRank) {
  13000. this._maxRank = rank;
  13001. }
  13002. this._defines[rank] = new Array();
  13003. }
  13004. this._defines[rank].push(define);
  13005. };
  13006. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13007. get: function () {
  13008. return this._currentRank <= this._maxRank;
  13009. },
  13010. enumerable: true,
  13011. configurable: true
  13012. });
  13013. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13014. var currentFallbacks = this._defines[this._currentRank];
  13015. for (var index = 0; index < currentFallbacks.length; index++) {
  13016. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13017. }
  13018. this._currentRank++;
  13019. return currentDefines;
  13020. };
  13021. return EffectFallbacks;
  13022. })();
  13023. BABYLON.EffectFallbacks = EffectFallbacks;
  13024. var Effect = (function () {
  13025. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13026. var _this = this;
  13027. this._isReady = false;
  13028. this._compilationError = "";
  13029. this._valueCache = [];
  13030. this._engine = engine;
  13031. this.name = baseName;
  13032. this.defines = defines;
  13033. this._uniformsNames = uniformsNames.concat(samplers);
  13034. this._samplers = samplers;
  13035. this._attributesNames = attributesNames;
  13036. this.onError = onError;
  13037. this.onCompiled = onCompiled;
  13038. var vertexSource;
  13039. var fragmentSource;
  13040. if (baseName.vertexElement) {
  13041. vertexSource = document.getElementById(baseName.vertexElement);
  13042. if (!vertexSource) {
  13043. vertexSource = baseName.vertexElement;
  13044. }
  13045. }
  13046. else {
  13047. vertexSource = baseName.vertex || baseName;
  13048. }
  13049. if (baseName.fragmentElement) {
  13050. fragmentSource = document.getElementById(baseName.fragmentElement);
  13051. if (!fragmentSource) {
  13052. fragmentSource = baseName.fragmentElement;
  13053. }
  13054. }
  13055. else {
  13056. fragmentSource = baseName.fragment || baseName;
  13057. }
  13058. this._loadVertexShader(vertexSource, function (vertexCode) {
  13059. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13060. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13061. });
  13062. });
  13063. }
  13064. // Properties
  13065. Effect.prototype.isReady = function () {
  13066. return this._isReady;
  13067. };
  13068. Effect.prototype.getProgram = function () {
  13069. return this._program;
  13070. };
  13071. Effect.prototype.getAttributesNames = function () {
  13072. return this._attributesNames;
  13073. };
  13074. Effect.prototype.getAttributeLocation = function (index) {
  13075. return this._attributes[index];
  13076. };
  13077. Effect.prototype.getAttributeLocationByName = function (name) {
  13078. var index = this._attributesNames.indexOf(name);
  13079. return this._attributes[index];
  13080. };
  13081. Effect.prototype.getAttributesCount = function () {
  13082. return this._attributes.length;
  13083. };
  13084. Effect.prototype.getUniformIndex = function (uniformName) {
  13085. return this._uniformsNames.indexOf(uniformName);
  13086. };
  13087. Effect.prototype.getUniform = function (uniformName) {
  13088. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13089. };
  13090. Effect.prototype.getSamplers = function () {
  13091. return this._samplers;
  13092. };
  13093. Effect.prototype.getCompilationError = function () {
  13094. return this._compilationError;
  13095. };
  13096. // Methods
  13097. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13098. // DOM element ?
  13099. if (vertex instanceof HTMLElement) {
  13100. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13101. callback(vertexCode);
  13102. return;
  13103. }
  13104. // Is in local store ?
  13105. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13106. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13107. return;
  13108. }
  13109. var vertexShaderUrl;
  13110. if (vertex[0] === ".") {
  13111. vertexShaderUrl = vertex;
  13112. }
  13113. else {
  13114. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13115. }
  13116. // Vertex shader
  13117. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13118. };
  13119. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13120. // DOM element ?
  13121. if (fragment instanceof HTMLElement) {
  13122. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13123. callback(fragmentCode);
  13124. return;
  13125. }
  13126. // Is in local store ?
  13127. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13128. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13129. return;
  13130. }
  13131. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13132. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13133. return;
  13134. }
  13135. var fragmentShaderUrl;
  13136. if (fragment[0] === ".") {
  13137. fragmentShaderUrl = fragment;
  13138. }
  13139. else {
  13140. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13141. }
  13142. // Fragment shader
  13143. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13144. };
  13145. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13146. try {
  13147. var engine = this._engine;
  13148. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13149. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13150. this._attributes = engine.getAttributes(this._program, attributesNames);
  13151. for (var index = 0; index < this._samplers.length; index++) {
  13152. var sampler = this.getUniform(this._samplers[index]);
  13153. if (sampler == null) {
  13154. this._samplers.splice(index, 1);
  13155. index--;
  13156. }
  13157. }
  13158. engine.bindSamplers(this);
  13159. this._isReady = true;
  13160. if (this.onCompiled) {
  13161. this.onCompiled(this);
  13162. }
  13163. }
  13164. catch (e) {
  13165. // Is it a problem with precision?
  13166. if (e.message.indexOf("highp") !== -1) {
  13167. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13168. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13169. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13170. return;
  13171. }
  13172. // Let's go through fallbacks then
  13173. if (fallbacks && fallbacks.isMoreFallbacks) {
  13174. defines = fallbacks.reduce(defines);
  13175. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13176. }
  13177. else {
  13178. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13179. BABYLON.Tools.Error("Defines: " + defines);
  13180. BABYLON.Tools.Error("Error: " + e.message);
  13181. this._compilationError = e.message;
  13182. if (this.onError) {
  13183. this.onError(this, this._compilationError);
  13184. }
  13185. }
  13186. }
  13187. };
  13188. Effect.prototype._bindTexture = function (channel, texture) {
  13189. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13190. };
  13191. Effect.prototype.setTexture = function (channel, texture) {
  13192. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13193. };
  13194. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13195. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13196. };
  13197. //public _cacheMatrix(uniformName, matrix) {
  13198. // if (!this._valueCache[uniformName]) {
  13199. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13200. // }
  13201. // for (var index = 0; index < 16; index++) {
  13202. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13203. // }
  13204. //};
  13205. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13206. if (!this._valueCache[uniformName]) {
  13207. this._valueCache[uniformName] = [x, y];
  13208. return;
  13209. }
  13210. this._valueCache[uniformName][0] = x;
  13211. this._valueCache[uniformName][1] = y;
  13212. };
  13213. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13214. if (!this._valueCache[uniformName]) {
  13215. this._valueCache[uniformName] = [x, y, z];
  13216. return;
  13217. }
  13218. this._valueCache[uniformName][0] = x;
  13219. this._valueCache[uniformName][1] = y;
  13220. this._valueCache[uniformName][2] = z;
  13221. };
  13222. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13223. if (!this._valueCache[uniformName]) {
  13224. this._valueCache[uniformName] = [x, y, z, w];
  13225. return;
  13226. }
  13227. this._valueCache[uniformName][0] = x;
  13228. this._valueCache[uniformName][1] = y;
  13229. this._valueCache[uniformName][2] = z;
  13230. this._valueCache[uniformName][3] = w;
  13231. };
  13232. Effect.prototype.setArray = function (uniformName, array) {
  13233. this._engine.setArray(this.getUniform(uniformName), array);
  13234. return this;
  13235. };
  13236. Effect.prototype.setArray2 = function (uniformName, array) {
  13237. this._engine.setArray2(this.getUniform(uniformName), array);
  13238. return this;
  13239. };
  13240. Effect.prototype.setArray3 = function (uniformName, array) {
  13241. this._engine.setArray3(this.getUniform(uniformName), array);
  13242. return this;
  13243. };
  13244. Effect.prototype.setArray4 = function (uniformName, array) {
  13245. this._engine.setArray4(this.getUniform(uniformName), array);
  13246. return this;
  13247. };
  13248. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13249. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13250. return this;
  13251. };
  13252. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13253. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13254. // return;
  13255. //this._cacheMatrix(uniformName, matrix);
  13256. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13257. return this;
  13258. };
  13259. Effect.prototype.setFloat = function (uniformName, value) {
  13260. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13261. return this;
  13262. this._valueCache[uniformName] = value;
  13263. this._engine.setFloat(this.getUniform(uniformName), value);
  13264. return this;
  13265. };
  13266. Effect.prototype.setBool = function (uniformName, bool) {
  13267. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13268. return this;
  13269. this._valueCache[uniformName] = bool;
  13270. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13271. return this;
  13272. };
  13273. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13274. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13275. return this;
  13276. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13277. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13278. return this;
  13279. };
  13280. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13281. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13282. return this;
  13283. this._cacheFloat2(uniformName, x, y);
  13284. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13285. return this;
  13286. };
  13287. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13288. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13289. return this;
  13290. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13291. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13292. return this;
  13293. };
  13294. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13295. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13296. return this;
  13297. this._cacheFloat3(uniformName, x, y, z);
  13298. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13299. return this;
  13300. };
  13301. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13302. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13303. return this;
  13304. this._cacheFloat4(uniformName, x, y, z, w);
  13305. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13306. return this;
  13307. };
  13308. Effect.prototype.setColor3 = function (uniformName, color3) {
  13309. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13310. return this;
  13311. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13312. this._engine.setColor3(this.getUniform(uniformName), color3);
  13313. return this;
  13314. };
  13315. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13316. 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)
  13317. return this;
  13318. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13319. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13320. return this;
  13321. };
  13322. // Statics
  13323. 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}",
  13324. 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}",
  13325. 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}",
  13326. 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}",
  13327. 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}",
  13328. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13329. 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}",
  13330. 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}",
  13331. 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}",
  13332. 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}",
  13333. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13334. depthVertexShader:"#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#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 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}",
  13335. 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}",
  13336. 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}",
  13337. 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}",
  13338. 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}",
  13339. 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}",
  13340. 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}",
  13341. 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}",
  13342. 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}",
  13343. 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}",
  13344. 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}",
  13345. 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}",
  13346. 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}",
  13347. 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}",
  13348. 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}",
  13349. 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}",
  13350. 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}",
  13351. 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}",
  13352. 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}",
  13353. 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}",
  13354. 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}",
  13355. 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}",
  13356. 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}",
  13357. 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}",
  13358. 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}",
  13359. 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}",
  13360. 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}",
  13361. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13362. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13363. volumetricLightScatteringPixelShader:"// Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html\n\n#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform vec2 lightPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n \n float decay = 0.96815;\n float exposure = 0.3;\n float density = 0.926;\n float weight = 0.58767;\n\n const int NUM_SAMPLES = 100;\n\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - lightPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++)\n {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13364. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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 BASIC_RENDER\n gl_FragColor = texture2D(diffuseSampler, vUV);\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n}",
  13365. 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}",
  13366. };
  13367. return Effect;
  13368. })();
  13369. BABYLON.Effect = Effect;
  13370. })(BABYLON || (BABYLON = {}));
  13371. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13372. (function (BABYLON) {
  13373. var Material = (function () {
  13374. function Material(name, scene, doNotAdd) {
  13375. this.name = name;
  13376. this.checkReadyOnEveryCall = true;
  13377. this.checkReadyOnlyOnce = false;
  13378. this.state = "";
  13379. this.alpha = 1.0;
  13380. this.backFaceCulling = true;
  13381. this._wasPreviouslyReady = false;
  13382. this._fillMode = Material.TriangleFillMode;
  13383. this.pointSize = 1.0;
  13384. this.id = name;
  13385. this._scene = scene;
  13386. if (!doNotAdd) {
  13387. scene.materials.push(this);
  13388. }
  13389. }
  13390. Object.defineProperty(Material, "TriangleFillMode", {
  13391. get: function () {
  13392. return Material._TriangleFillMode;
  13393. },
  13394. enumerable: true,
  13395. configurable: true
  13396. });
  13397. Object.defineProperty(Material, "WireFrameFillMode", {
  13398. get: function () {
  13399. return Material._WireFrameFillMode;
  13400. },
  13401. enumerable: true,
  13402. configurable: true
  13403. });
  13404. Object.defineProperty(Material, "PointFillMode", {
  13405. get: function () {
  13406. return Material._PointFillMode;
  13407. },
  13408. enumerable: true,
  13409. configurable: true
  13410. });
  13411. Object.defineProperty(Material.prototype, "wireframe", {
  13412. get: function () {
  13413. return this._fillMode === Material.WireFrameFillMode;
  13414. },
  13415. set: function (value) {
  13416. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. Object.defineProperty(Material.prototype, "pointsCloud", {
  13422. get: function () {
  13423. return this._fillMode === Material.PointFillMode;
  13424. },
  13425. set: function (value) {
  13426. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13427. },
  13428. enumerable: true,
  13429. configurable: true
  13430. });
  13431. Object.defineProperty(Material.prototype, "fillMode", {
  13432. get: function () {
  13433. return this._fillMode;
  13434. },
  13435. set: function (value) {
  13436. this._fillMode = value;
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Material.prototype.isReady = function (mesh, useInstances) {
  13442. return true;
  13443. };
  13444. Material.prototype.getEffect = function () {
  13445. return this._effect;
  13446. };
  13447. Material.prototype.getScene = function () {
  13448. return this._scene;
  13449. };
  13450. Material.prototype.needAlphaBlending = function () {
  13451. return (this.alpha < 1.0);
  13452. };
  13453. Material.prototype.needAlphaTesting = function () {
  13454. return false;
  13455. };
  13456. Material.prototype.getAlphaTestTexture = function () {
  13457. return null;
  13458. };
  13459. Material.prototype.trackCreation = function (onCompiled, onError) {
  13460. };
  13461. Material.prototype._preBind = function () {
  13462. var engine = this._scene.getEngine();
  13463. engine.enableEffect(this._effect);
  13464. engine.setState(this.backFaceCulling);
  13465. };
  13466. Material.prototype.bind = function (world, mesh) {
  13467. this._scene._cachedMaterial = this;
  13468. if (this.onBind) {
  13469. this.onBind(this);
  13470. }
  13471. };
  13472. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13473. };
  13474. Material.prototype.unbind = function () {
  13475. };
  13476. Material.prototype.dispose = function (forceDisposeEffect) {
  13477. // Remove from scene
  13478. var index = this._scene.materials.indexOf(this);
  13479. this._scene.materials.splice(index, 1);
  13480. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13481. if (forceDisposeEffect && this._effect) {
  13482. this._scene.getEngine()._releaseEffect(this._effect);
  13483. this._effect = null;
  13484. }
  13485. // Callback
  13486. if (this.onDispose) {
  13487. this.onDispose();
  13488. }
  13489. };
  13490. Material._TriangleFillMode = 0;
  13491. Material._WireFrameFillMode = 1;
  13492. Material._PointFillMode = 2;
  13493. return Material;
  13494. })();
  13495. BABYLON.Material = Material;
  13496. })(BABYLON || (BABYLON = {}));
  13497. //# sourceMappingURL=babylon.material.js.map
  13498. var BABYLON;
  13499. (function (BABYLON) {
  13500. var maxSimultaneousLights = 4;
  13501. var FresnelParameters = (function () {
  13502. function FresnelParameters() {
  13503. this.isEnabled = true;
  13504. this.leftColor = BABYLON.Color3.White();
  13505. this.rightColor = BABYLON.Color3.Black();
  13506. this.bias = 0;
  13507. this.power = 1;
  13508. }
  13509. return FresnelParameters;
  13510. })();
  13511. BABYLON.FresnelParameters = FresnelParameters;
  13512. var StandardMaterial = (function (_super) {
  13513. __extends(StandardMaterial, _super);
  13514. function StandardMaterial(name, scene) {
  13515. var _this = this;
  13516. _super.call(this, name, scene);
  13517. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13518. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13519. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13520. this.specularPower = 64;
  13521. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13522. this.useAlphaFromDiffuseTexture = false;
  13523. this.useSpecularOverAlpha = true;
  13524. this.fogEnabled = true;
  13525. this._cachedDefines = null;
  13526. this._renderTargets = new BABYLON.SmartArray(16);
  13527. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13528. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13529. this._scaledDiffuse = new BABYLON.Color3();
  13530. this._scaledSpecular = new BABYLON.Color3();
  13531. this.getRenderTargetTextures = function () {
  13532. _this._renderTargets.reset();
  13533. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13534. _this._renderTargets.push(_this.reflectionTexture);
  13535. }
  13536. return _this._renderTargets;
  13537. };
  13538. }
  13539. StandardMaterial.prototype.needAlphaBlending = function () {
  13540. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13541. };
  13542. StandardMaterial.prototype.needAlphaTesting = function () {
  13543. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13544. };
  13545. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13546. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13547. };
  13548. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13549. return this.diffuseTexture;
  13550. };
  13551. // Methods
  13552. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13553. if (this.checkReadyOnlyOnce) {
  13554. if (this._wasPreviouslyReady) {
  13555. return true;
  13556. }
  13557. }
  13558. var scene = this.getScene();
  13559. if (!this.checkReadyOnEveryCall) {
  13560. if (this._renderId === scene.getRenderId()) {
  13561. return true;
  13562. }
  13563. }
  13564. var engine = scene.getEngine();
  13565. var defines = [];
  13566. var fallbacks = new BABYLON.EffectFallbacks();
  13567. // Textures
  13568. if (scene.texturesEnabled) {
  13569. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13570. if (!this.diffuseTexture.isReady()) {
  13571. return false;
  13572. }
  13573. else {
  13574. defines.push("#define DIFFUSE");
  13575. }
  13576. }
  13577. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13578. if (!this.ambientTexture.isReady()) {
  13579. return false;
  13580. }
  13581. else {
  13582. defines.push("#define AMBIENT");
  13583. }
  13584. }
  13585. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13586. if (!this.opacityTexture.isReady()) {
  13587. return false;
  13588. }
  13589. else {
  13590. defines.push("#define OPACITY");
  13591. if (this.opacityTexture.getAlphaFromRGB) {
  13592. defines.push("#define OPACITYRGB");
  13593. }
  13594. }
  13595. }
  13596. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13597. if (!this.reflectionTexture.isReady()) {
  13598. return false;
  13599. }
  13600. else {
  13601. defines.push("#define REFLECTION");
  13602. fallbacks.addFallback(0, "REFLECTION");
  13603. }
  13604. }
  13605. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13606. if (!this.emissiveTexture.isReady()) {
  13607. return false;
  13608. }
  13609. else {
  13610. defines.push("#define EMISSIVE");
  13611. }
  13612. }
  13613. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13614. if (!this.specularTexture.isReady()) {
  13615. return false;
  13616. }
  13617. else {
  13618. defines.push("#define SPECULAR");
  13619. fallbacks.addFallback(0, "SPECULAR");
  13620. }
  13621. }
  13622. }
  13623. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13624. if (!this.bumpTexture.isReady()) {
  13625. return false;
  13626. }
  13627. else {
  13628. defines.push("#define BUMP");
  13629. fallbacks.addFallback(0, "BUMP");
  13630. }
  13631. }
  13632. // Effect
  13633. if (this.useSpecularOverAlpha) {
  13634. defines.push("#define SPECULAROVERALPHA");
  13635. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13636. }
  13637. if (scene.clipPlane) {
  13638. defines.push("#define CLIPPLANE");
  13639. }
  13640. if (engine.getAlphaTesting()) {
  13641. defines.push("#define ALPHATEST");
  13642. }
  13643. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13644. defines.push("#define ALPHAFROMDIFFUSE");
  13645. }
  13646. // Point size
  13647. if (this.pointsCloud || scene.forcePointsCloud) {
  13648. defines.push("#define POINTSIZE");
  13649. }
  13650. // Fog
  13651. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13652. defines.push("#define FOG");
  13653. fallbacks.addFallback(1, "FOG");
  13654. }
  13655. var shadowsActivated = false;
  13656. var lightIndex = 0;
  13657. if (scene.lightsEnabled) {
  13658. for (var index = 0; index < scene.lights.length; index++) {
  13659. var light = scene.lights[index];
  13660. if (!light.isEnabled()) {
  13661. continue;
  13662. }
  13663. // Excluded check
  13664. if (light._excludedMeshesIds.length > 0) {
  13665. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13666. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13667. if (excludedMesh) {
  13668. light.excludedMeshes.push(excludedMesh);
  13669. }
  13670. }
  13671. light._excludedMeshesIds = [];
  13672. }
  13673. // Included check
  13674. if (light._includedOnlyMeshesIds.length > 0) {
  13675. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13676. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13677. if (includedOnlyMesh) {
  13678. light.includedOnlyMeshes.push(includedOnlyMesh);
  13679. }
  13680. }
  13681. light._includedOnlyMeshesIds = [];
  13682. }
  13683. if (!light.canAffectMesh(mesh)) {
  13684. continue;
  13685. }
  13686. defines.push("#define LIGHT" + lightIndex);
  13687. if (lightIndex > 0) {
  13688. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13689. }
  13690. var type;
  13691. if (light instanceof BABYLON.SpotLight) {
  13692. type = "#define SPOTLIGHT" + lightIndex;
  13693. }
  13694. else if (light instanceof BABYLON.HemisphericLight) {
  13695. type = "#define HEMILIGHT" + lightIndex;
  13696. }
  13697. else {
  13698. type = "#define POINTDIRLIGHT" + lightIndex;
  13699. }
  13700. defines.push(type);
  13701. if (lightIndex > 0) {
  13702. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13703. }
  13704. // Shadows
  13705. if (scene.shadowsEnabled) {
  13706. var shadowGenerator = light.getShadowGenerator();
  13707. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13708. defines.push("#define SHADOW" + lightIndex);
  13709. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13710. if (!shadowsActivated) {
  13711. defines.push("#define SHADOWS");
  13712. shadowsActivated = true;
  13713. }
  13714. if (shadowGenerator.useVarianceShadowMap) {
  13715. defines.push("#define SHADOWVSM" + lightIndex);
  13716. if (lightIndex > 0) {
  13717. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13718. }
  13719. }
  13720. if (shadowGenerator.usePoissonSampling) {
  13721. defines.push("#define SHADOWPCF" + lightIndex);
  13722. if (lightIndex > 0) {
  13723. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13724. }
  13725. }
  13726. }
  13727. }
  13728. lightIndex++;
  13729. if (lightIndex === maxSimultaneousLights)
  13730. break;
  13731. }
  13732. }
  13733. if (StandardMaterial.FresnelEnabled) {
  13734. // Fresnel
  13735. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13736. var fresnelRank = 1;
  13737. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13738. defines.push("#define DIFFUSEFRESNEL");
  13739. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13740. fresnelRank++;
  13741. }
  13742. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13743. defines.push("#define OPACITYFRESNEL");
  13744. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13745. fresnelRank++;
  13746. }
  13747. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13748. defines.push("#define REFLECTIONFRESNEL");
  13749. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13750. fresnelRank++;
  13751. }
  13752. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13753. defines.push("#define EMISSIVEFRESNEL");
  13754. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13755. fresnelRank++;
  13756. }
  13757. defines.push("#define FRESNEL");
  13758. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13759. }
  13760. }
  13761. // Attribs
  13762. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13763. if (mesh) {
  13764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13765. attribs.push(BABYLON.VertexBuffer.UVKind);
  13766. defines.push("#define UV1");
  13767. }
  13768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13770. defines.push("#define UV2");
  13771. }
  13772. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13773. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13774. defines.push("#define VERTEXCOLOR");
  13775. if (mesh.hasVertexAlpha) {
  13776. defines.push("#define VERTEXALPHA");
  13777. }
  13778. }
  13779. if (mesh.useBones) {
  13780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13782. defines.push("#define BONES");
  13783. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13784. defines.push("#define BONES4");
  13785. fallbacks.addFallback(0, "BONES4");
  13786. }
  13787. // Instances
  13788. if (useInstances) {
  13789. defines.push("#define INSTANCES");
  13790. attribs.push("world0");
  13791. attribs.push("world1");
  13792. attribs.push("world2");
  13793. attribs.push("world3");
  13794. }
  13795. }
  13796. // Get correct effect
  13797. var join = defines.join("\n");
  13798. if (this._cachedDefines !== join) {
  13799. this._cachedDefines = join;
  13800. scene.resetCachedMaterial();
  13801. // Legacy browser patch
  13802. var shaderName = "default";
  13803. if (!scene.getEngine().getCaps().standardDerivatives) {
  13804. shaderName = "legacydefault";
  13805. }
  13806. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13807. }
  13808. if (!this._effect.isReady()) {
  13809. return false;
  13810. }
  13811. this._renderId = scene.getRenderId();
  13812. this._wasPreviouslyReady = true;
  13813. return true;
  13814. };
  13815. StandardMaterial.prototype.unbind = function () {
  13816. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13817. this._effect.setTexture("reflection2DSampler", null);
  13818. }
  13819. };
  13820. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13821. this._effect.setMatrix("world", world);
  13822. };
  13823. StandardMaterial.prototype.bind = function (world, mesh) {
  13824. var scene = this.getScene();
  13825. // Matrices
  13826. this.bindOnlyWorldMatrix(world);
  13827. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13828. // Bones
  13829. if (mesh.useBones) {
  13830. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13831. }
  13832. if (scene.getCachedMaterial() !== this) {
  13833. if (StandardMaterial.FresnelEnabled) {
  13834. // Fresnel
  13835. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13836. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13837. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13838. }
  13839. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13840. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13841. }
  13842. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13843. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13844. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13845. }
  13846. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13847. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13848. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13849. }
  13850. }
  13851. // Textures
  13852. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13853. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13854. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13855. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13856. }
  13857. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13858. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13859. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13860. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13861. }
  13862. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13863. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13864. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13865. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13866. }
  13867. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13868. if (this.reflectionTexture.isCube) {
  13869. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13870. }
  13871. else {
  13872. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13873. }
  13874. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13875. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13876. }
  13877. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13878. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13879. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13880. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13881. }
  13882. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13883. this._effect.setTexture("specularSampler", this.specularTexture);
  13884. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13885. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13886. }
  13887. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13888. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13889. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13890. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13891. }
  13892. // Clip plane
  13893. if (scene.clipPlane) {
  13894. var clipPlane = scene.clipPlane;
  13895. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13896. }
  13897. // Point size
  13898. if (this.pointsCloud) {
  13899. this._effect.setFloat("pointSize", this.pointSize);
  13900. }
  13901. // Colors
  13902. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13903. // Scaling down color according to emissive
  13904. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13905. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13906. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13907. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13908. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13909. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13910. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13911. }
  13912. // Scaling down color according to emissive
  13913. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13914. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13915. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13916. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13917. if (scene.lightsEnabled) {
  13918. var lightIndex = 0;
  13919. for (var index = 0; index < scene.lights.length; index++) {
  13920. var light = scene.lights[index];
  13921. if (!light.isEnabled()) {
  13922. continue;
  13923. }
  13924. if (!light.canAffectMesh(mesh)) {
  13925. continue;
  13926. }
  13927. if (light instanceof BABYLON.PointLight) {
  13928. // Point Light
  13929. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13930. }
  13931. else if (light instanceof BABYLON.DirectionalLight) {
  13932. // Directional Light
  13933. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13934. }
  13935. else if (light instanceof BABYLON.SpotLight) {
  13936. // Spot Light
  13937. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13938. }
  13939. else if (light instanceof BABYLON.HemisphericLight) {
  13940. // Hemispheric Light
  13941. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13942. }
  13943. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13944. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13945. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13946. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13947. // Shadows
  13948. if (scene.shadowsEnabled) {
  13949. var shadowGenerator = light.getShadowGenerator();
  13950. if (mesh.receiveShadows && shadowGenerator) {
  13951. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13952. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13953. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13954. }
  13955. }
  13956. lightIndex++;
  13957. if (lightIndex === maxSimultaneousLights)
  13958. break;
  13959. }
  13960. }
  13961. // View
  13962. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13963. this._effect.setMatrix("view", scene.getViewMatrix());
  13964. }
  13965. // Fog
  13966. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13967. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13968. this._effect.setColor3("vFogColor", scene.fogColor);
  13969. }
  13970. _super.prototype.bind.call(this, world, mesh);
  13971. };
  13972. StandardMaterial.prototype.getAnimatables = function () {
  13973. var results = [];
  13974. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13975. results.push(this.diffuseTexture);
  13976. }
  13977. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13978. results.push(this.ambientTexture);
  13979. }
  13980. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13981. results.push(this.opacityTexture);
  13982. }
  13983. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13984. results.push(this.reflectionTexture);
  13985. }
  13986. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13987. results.push(this.emissiveTexture);
  13988. }
  13989. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13990. results.push(this.specularTexture);
  13991. }
  13992. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13993. results.push(this.bumpTexture);
  13994. }
  13995. return results;
  13996. };
  13997. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13998. if (this.diffuseTexture) {
  13999. this.diffuseTexture.dispose();
  14000. }
  14001. if (this.ambientTexture) {
  14002. this.ambientTexture.dispose();
  14003. }
  14004. if (this.opacityTexture) {
  14005. this.opacityTexture.dispose();
  14006. }
  14007. if (this.reflectionTexture) {
  14008. this.reflectionTexture.dispose();
  14009. }
  14010. if (this.emissiveTexture) {
  14011. this.emissiveTexture.dispose();
  14012. }
  14013. if (this.specularTexture) {
  14014. this.specularTexture.dispose();
  14015. }
  14016. if (this.bumpTexture) {
  14017. this.bumpTexture.dispose();
  14018. }
  14019. _super.prototype.dispose.call(this, forceDisposeEffect);
  14020. };
  14021. StandardMaterial.prototype.clone = function (name) {
  14022. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14023. // Base material
  14024. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14025. newStandardMaterial.alpha = this.alpha;
  14026. newStandardMaterial.fillMode = this.fillMode;
  14027. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14028. // Standard material
  14029. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14030. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14031. }
  14032. if (this.ambientTexture && this.ambientTexture.clone) {
  14033. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14034. }
  14035. if (this.opacityTexture && this.opacityTexture.clone) {
  14036. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14037. }
  14038. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14039. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14040. }
  14041. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14042. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14043. }
  14044. if (this.specularTexture && this.specularTexture.clone) {
  14045. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14046. }
  14047. if (this.bumpTexture && this.bumpTexture.clone) {
  14048. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14049. }
  14050. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14051. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14052. newStandardMaterial.specularColor = this.specularColor.clone();
  14053. newStandardMaterial.specularPower = this.specularPower;
  14054. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14055. return newStandardMaterial;
  14056. };
  14057. // Statics
  14058. // Flags used to enable or disable a type of texture for all Standard Materials
  14059. StandardMaterial.DiffuseTextureEnabled = true;
  14060. StandardMaterial.AmbientTextureEnabled = true;
  14061. StandardMaterial.OpacityTextureEnabled = true;
  14062. StandardMaterial.ReflectionTextureEnabled = true;
  14063. StandardMaterial.EmissiveTextureEnabled = true;
  14064. StandardMaterial.SpecularTextureEnabled = true;
  14065. StandardMaterial.BumpTextureEnabled = true;
  14066. StandardMaterial.FresnelEnabled = true;
  14067. return StandardMaterial;
  14068. })(BABYLON.Material);
  14069. BABYLON.StandardMaterial = StandardMaterial;
  14070. })(BABYLON || (BABYLON = {}));
  14071. //# sourceMappingURL=babylon.standardMaterial.js.map
  14072. var BABYLON;
  14073. (function (BABYLON) {
  14074. var MultiMaterial = (function (_super) {
  14075. __extends(MultiMaterial, _super);
  14076. function MultiMaterial(name, scene) {
  14077. _super.call(this, name, scene, true);
  14078. this.subMaterials = new Array();
  14079. scene.multiMaterials.push(this);
  14080. }
  14081. // Properties
  14082. MultiMaterial.prototype.getSubMaterial = function (index) {
  14083. if (index < 0 || index >= this.subMaterials.length) {
  14084. return this.getScene().defaultMaterial;
  14085. }
  14086. return this.subMaterials[index];
  14087. };
  14088. // Methods
  14089. MultiMaterial.prototype.isReady = function (mesh) {
  14090. for (var index = 0; index < this.subMaterials.length; index++) {
  14091. var subMaterial = this.subMaterials[index];
  14092. if (subMaterial) {
  14093. if (!this.subMaterials[index].isReady(mesh)) {
  14094. return false;
  14095. }
  14096. }
  14097. }
  14098. return true;
  14099. };
  14100. return MultiMaterial;
  14101. })(BABYLON.Material);
  14102. BABYLON.MultiMaterial = MultiMaterial;
  14103. })(BABYLON || (BABYLON = {}));
  14104. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14105. (function (BABYLON) {
  14106. var Database = (function () {
  14107. function Database(urlToScene, callbackManifestChecked) {
  14108. // Handling various flavors of prefixed version of IndexedDB
  14109. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14110. this.callbackManifestChecked = callbackManifestChecked;
  14111. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14112. this.db = null;
  14113. this.enableSceneOffline = false;
  14114. this.enableTexturesOffline = false;
  14115. this.manifestVersionFound = 0;
  14116. this.mustUpdateRessources = false;
  14117. this.hasReachedQuota = false;
  14118. this.checkManifestFile();
  14119. }
  14120. Database.prototype.checkManifestFile = function () {
  14121. var _this = this;
  14122. function noManifestFile() {
  14123. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14124. that.enableSceneOffline = false;
  14125. that.enableTexturesOffline = false;
  14126. that.callbackManifestChecked(false);
  14127. }
  14128. var that = this;
  14129. var manifestURL = this.currentSceneUrl + ".manifest";
  14130. var xhr = new XMLHttpRequest();
  14131. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14132. xhr.open("GET", manifestURLTimeStamped, true);
  14133. xhr.addEventListener("load", function () {
  14134. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14135. try {
  14136. var manifestFile = JSON.parse(xhr.response);
  14137. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14138. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14139. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14140. _this.manifestVersionFound = manifestFile.version;
  14141. }
  14142. if (_this.callbackManifestChecked) {
  14143. _this.callbackManifestChecked(true);
  14144. }
  14145. }
  14146. catch (ex) {
  14147. noManifestFile();
  14148. }
  14149. }
  14150. else {
  14151. noManifestFile();
  14152. }
  14153. }, false);
  14154. xhr.addEventListener("error", function (event) {
  14155. noManifestFile();
  14156. }, false);
  14157. try {
  14158. xhr.send();
  14159. }
  14160. catch (ex) {
  14161. BABYLON.Tools.Error("Error on XHR send request.");
  14162. that.callbackManifestChecked(false);
  14163. }
  14164. };
  14165. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14166. var _this = this;
  14167. function handleError() {
  14168. that.isSupported = false;
  14169. if (errorCallback)
  14170. errorCallback();
  14171. }
  14172. var that = this;
  14173. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14174. // Your browser doesn't support IndexedDB
  14175. this.isSupported = false;
  14176. if (errorCallback)
  14177. errorCallback();
  14178. }
  14179. else {
  14180. // If the DB hasn't been opened or created yet
  14181. if (!this.db) {
  14182. this.hasReachedQuota = false;
  14183. this.isSupported = true;
  14184. var request = this.idbFactory.open("babylonjs", 1);
  14185. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14186. request.onerror = function (event) {
  14187. handleError();
  14188. };
  14189. // executes when a version change transaction cannot complete due to other active transactions
  14190. request.onblocked = function (event) {
  14191. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14192. handleError();
  14193. };
  14194. // DB has been opened successfully
  14195. request.onsuccess = function (event) {
  14196. _this.db = request.result;
  14197. successCallback();
  14198. };
  14199. // Initialization of the DB. Creating Scenes & Textures stores
  14200. request.onupgradeneeded = function (event) {
  14201. _this.db = (event.target).result;
  14202. try {
  14203. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14204. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14205. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14206. }
  14207. catch (ex) {
  14208. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14209. handleError();
  14210. }
  14211. };
  14212. }
  14213. else {
  14214. if (successCallback)
  14215. successCallback();
  14216. }
  14217. }
  14218. };
  14219. Database.prototype.loadImageFromDB = function (url, image) {
  14220. var _this = this;
  14221. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14222. var saveAndLoadImage = function () {
  14223. if (!_this.hasReachedQuota && _this.db !== null) {
  14224. // the texture is not yet in the DB, let's try to save it
  14225. _this._saveImageIntoDBAsync(completeURL, image);
  14226. }
  14227. else {
  14228. image.src = url;
  14229. }
  14230. };
  14231. if (!this.mustUpdateRessources) {
  14232. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14233. }
  14234. else {
  14235. saveAndLoadImage();
  14236. }
  14237. };
  14238. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14239. if (this.isSupported && this.db !== null) {
  14240. var texture;
  14241. var transaction = this.db.transaction(["textures"]);
  14242. transaction.onabort = function (event) {
  14243. image.src = url;
  14244. };
  14245. transaction.oncomplete = function (event) {
  14246. var blobTextureURL;
  14247. if (texture) {
  14248. var URL = window.URL || window.webkitURL;
  14249. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14250. image.onerror = function () {
  14251. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14252. image.src = url;
  14253. };
  14254. image.src = blobTextureURL;
  14255. }
  14256. else {
  14257. notInDBCallback();
  14258. }
  14259. };
  14260. var getRequest = transaction.objectStore("textures").get(url);
  14261. getRequest.onsuccess = function (event) {
  14262. texture = (event.target).result;
  14263. };
  14264. getRequest.onerror = function (event) {
  14265. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14266. image.src = url;
  14267. };
  14268. }
  14269. else {
  14270. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14271. image.src = url;
  14272. }
  14273. };
  14274. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14275. var _this = this;
  14276. if (this.isSupported) {
  14277. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14278. var generateBlobUrl = function () {
  14279. var blobTextureURL;
  14280. if (blob) {
  14281. var URL = window.URL || window.webkitURL;
  14282. try {
  14283. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14284. }
  14285. catch (ex) {
  14286. blobTextureURL = URL.createObjectURL(blob);
  14287. }
  14288. }
  14289. image.src = blobTextureURL;
  14290. };
  14291. if (BABYLON.Database.isUASupportingBlobStorage) {
  14292. var xhr = new XMLHttpRequest(), blob;
  14293. xhr.open("GET", url, true);
  14294. xhr.responseType = "blob";
  14295. xhr.addEventListener("load", function () {
  14296. if (xhr.status === 200) {
  14297. // Blob as response (XHR2)
  14298. blob = xhr.response;
  14299. var transaction = _this.db.transaction(["textures"], "readwrite");
  14300. // the transaction could abort because of a QuotaExceededError error
  14301. transaction.onabort = function (event) {
  14302. try {
  14303. if (event.srcElement.error.name === "QuotaExceededError") {
  14304. this.hasReachedQuota = true;
  14305. }
  14306. }
  14307. catch (ex) {
  14308. }
  14309. generateBlobUrl();
  14310. };
  14311. transaction.oncomplete = function (event) {
  14312. generateBlobUrl();
  14313. };
  14314. var newTexture = { textureUrl: url, data: blob };
  14315. try {
  14316. // Put the blob into the dabase
  14317. var addRequest = transaction.objectStore("textures").put(newTexture);
  14318. addRequest.onsuccess = function (event) {
  14319. };
  14320. addRequest.onerror = function (event) {
  14321. generateBlobUrl();
  14322. };
  14323. }
  14324. catch (ex) {
  14325. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14326. if (ex.code === 25) {
  14327. BABYLON.Database.isUASupportingBlobStorage = false;
  14328. }
  14329. image.src = url;
  14330. }
  14331. }
  14332. else {
  14333. image.src = url;
  14334. }
  14335. }, false);
  14336. xhr.addEventListener("error", function (event) {
  14337. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14338. image.src = url;
  14339. }, false);
  14340. xhr.send();
  14341. }
  14342. else {
  14343. image.src = url;
  14344. }
  14345. }
  14346. else {
  14347. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14348. image.src = url;
  14349. }
  14350. };
  14351. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14352. var _this = this;
  14353. var updateVersion = function (event) {
  14354. // the version is not yet in the DB or we need to update it
  14355. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14356. };
  14357. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14358. };
  14359. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14360. var _this = this;
  14361. if (this.isSupported) {
  14362. var version;
  14363. try {
  14364. var transaction = this.db.transaction(["versions"]);
  14365. transaction.oncomplete = function (event) {
  14366. if (version) {
  14367. // If the version in the JSON file is > than the version in DB
  14368. if (_this.manifestVersionFound > version.data) {
  14369. _this.mustUpdateRessources = true;
  14370. updateInDBCallback();
  14371. }
  14372. else {
  14373. callback(version.data);
  14374. }
  14375. }
  14376. else {
  14377. _this.mustUpdateRessources = true;
  14378. updateInDBCallback();
  14379. }
  14380. };
  14381. transaction.onabort = function (event) {
  14382. callback(-1);
  14383. };
  14384. var getRequest = transaction.objectStore("versions").get(url);
  14385. getRequest.onsuccess = function (event) {
  14386. version = (event.target).result;
  14387. };
  14388. getRequest.onerror = function (event) {
  14389. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14390. callback(-1);
  14391. };
  14392. }
  14393. catch (ex) {
  14394. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14395. callback(-1);
  14396. }
  14397. }
  14398. else {
  14399. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14400. callback(-1);
  14401. }
  14402. };
  14403. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14404. var _this = this;
  14405. if (this.isSupported && !this.hasReachedQuota) {
  14406. try {
  14407. // Open a transaction to the database
  14408. var transaction = this.db.transaction(["versions"], "readwrite");
  14409. // the transaction could abort because of a QuotaExceededError error
  14410. transaction.onabort = function (event) {
  14411. try {
  14412. if (event.srcElement.error.name === "QuotaExceededError") {
  14413. _this.hasReachedQuota = true;
  14414. }
  14415. }
  14416. catch (ex) {
  14417. }
  14418. callback(-1);
  14419. };
  14420. transaction.oncomplete = function (event) {
  14421. callback(_this.manifestVersionFound);
  14422. };
  14423. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14424. // Put the scene into the database
  14425. var addRequest = transaction.objectStore("versions").put(newVersion);
  14426. addRequest.onsuccess = function (event) {
  14427. };
  14428. addRequest.onerror = function (event) {
  14429. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14430. };
  14431. }
  14432. catch (ex) {
  14433. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14434. callback(-1);
  14435. }
  14436. }
  14437. else {
  14438. callback(-1);
  14439. }
  14440. };
  14441. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14442. var _this = this;
  14443. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14444. var saveAndLoadFile = function (event) {
  14445. // the scene is not yet in the DB, let's try to save it
  14446. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14447. };
  14448. this._checkVersionFromDB(completeUrl, function (version) {
  14449. if (version !== -1) {
  14450. if (!_this.mustUpdateRessources) {
  14451. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14452. }
  14453. else {
  14454. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14455. }
  14456. }
  14457. else {
  14458. errorCallback();
  14459. }
  14460. });
  14461. };
  14462. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14463. if (this.isSupported) {
  14464. var targetStore;
  14465. if (url.indexOf(".babylon") !== -1) {
  14466. targetStore = "scenes";
  14467. }
  14468. else {
  14469. targetStore = "textures";
  14470. }
  14471. var file;
  14472. var transaction = this.db.transaction([targetStore]);
  14473. transaction.oncomplete = function (event) {
  14474. if (file) {
  14475. callback(file.data);
  14476. }
  14477. else {
  14478. notInDBCallback();
  14479. }
  14480. };
  14481. transaction.onabort = function (event) {
  14482. notInDBCallback();
  14483. };
  14484. var getRequest = transaction.objectStore(targetStore).get(url);
  14485. getRequest.onsuccess = function (event) {
  14486. file = (event.target).result;
  14487. };
  14488. getRequest.onerror = function (event) {
  14489. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14490. notInDBCallback();
  14491. };
  14492. }
  14493. else {
  14494. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14495. callback();
  14496. }
  14497. };
  14498. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14499. var _this = this;
  14500. if (this.isSupported) {
  14501. var targetStore;
  14502. if (url.indexOf(".babylon") !== -1) {
  14503. targetStore = "scenes";
  14504. }
  14505. else {
  14506. targetStore = "textures";
  14507. }
  14508. // Create XHR
  14509. var xhr = new XMLHttpRequest(), fileData;
  14510. xhr.open("GET", url, true);
  14511. if (useArrayBuffer) {
  14512. xhr.responseType = "arraybuffer";
  14513. }
  14514. xhr.onprogress = progressCallback;
  14515. xhr.addEventListener("load", function () {
  14516. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14517. // Blob as response (XHR2)
  14518. //fileData = xhr.responseText;
  14519. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14520. if (!_this.hasReachedQuota) {
  14521. // Open a transaction to the database
  14522. var transaction = _this.db.transaction([targetStore], "readwrite");
  14523. // the transaction could abort because of a QuotaExceededError error
  14524. transaction.onabort = function (event) {
  14525. try {
  14526. if (event.srcElement.error.name === "QuotaExceededError") {
  14527. this.hasReachedQuota = true;
  14528. }
  14529. }
  14530. catch (ex) {
  14531. }
  14532. callback(fileData);
  14533. };
  14534. transaction.oncomplete = function (event) {
  14535. callback(fileData);
  14536. };
  14537. var newFile;
  14538. if (targetStore === "scenes") {
  14539. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14540. }
  14541. else {
  14542. newFile = { textureUrl: url, data: fileData };
  14543. }
  14544. try {
  14545. // Put the scene into the database
  14546. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14547. addRequest.onsuccess = function (event) {
  14548. };
  14549. addRequest.onerror = function (event) {
  14550. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14551. };
  14552. }
  14553. catch (ex) {
  14554. callback(fileData);
  14555. }
  14556. }
  14557. else {
  14558. callback(fileData);
  14559. }
  14560. }
  14561. else {
  14562. callback();
  14563. }
  14564. }, false);
  14565. xhr.addEventListener("error", function (event) {
  14566. BABYLON.Tools.Error("error on XHR request.");
  14567. callback();
  14568. }, false);
  14569. xhr.send();
  14570. }
  14571. else {
  14572. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14573. callback();
  14574. }
  14575. };
  14576. Database.isUASupportingBlobStorage = true;
  14577. Database.parseURL = function (url) {
  14578. var a = document.createElement('a');
  14579. a.href = url;
  14580. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14581. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14582. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14583. return absLocation;
  14584. };
  14585. Database.ReturnFullUrlLocation = function (url) {
  14586. if (url.indexOf("http:/") === -1) {
  14587. return (BABYLON.Database.parseURL(window.location.href) + url);
  14588. }
  14589. else {
  14590. return url;
  14591. }
  14592. };
  14593. return Database;
  14594. })();
  14595. BABYLON.Database = Database;
  14596. })(BABYLON || (BABYLON = {}));
  14597. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14598. (function (BABYLON) {
  14599. var SpriteManager = (function () {
  14600. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14601. this.name = name;
  14602. this.cellSize = cellSize;
  14603. this.sprites = new Array();
  14604. this.renderingGroupId = 0;
  14605. this.fogEnabled = true;
  14606. this._vertexDeclaration = [3, 4, 4, 4];
  14607. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14608. this._capacity = capacity;
  14609. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14610. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14611. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14612. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14613. this._scene = scene;
  14614. this._scene.spriteManagers.push(this);
  14615. // VBO
  14616. this._vertexDeclaration = [3, 4, 4, 4];
  14617. this._vertexStrideSize = 15 * 4;
  14618. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14619. var indices = [];
  14620. var index = 0;
  14621. for (var count = 0; count < capacity; count++) {
  14622. indices.push(index);
  14623. indices.push(index + 1);
  14624. indices.push(index + 2);
  14625. indices.push(index);
  14626. indices.push(index + 2);
  14627. indices.push(index + 3);
  14628. index += 4;
  14629. }
  14630. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14631. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14632. // Effects
  14633. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14634. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14635. }
  14636. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14637. var arrayOffset = index * 15;
  14638. if (offsetX == 0)
  14639. offsetX = this._epsilon;
  14640. else if (offsetX == 1)
  14641. offsetX = 1 - this._epsilon;
  14642. if (offsetY == 0)
  14643. offsetY = this._epsilon;
  14644. else if (offsetY == 1)
  14645. offsetY = 1 - this._epsilon;
  14646. this._vertices[arrayOffset] = sprite.position.x;
  14647. this._vertices[arrayOffset + 1] = sprite.position.y;
  14648. this._vertices[arrayOffset + 2] = sprite.position.z;
  14649. this._vertices[arrayOffset + 3] = sprite.angle;
  14650. this._vertices[arrayOffset + 4] = sprite.size;
  14651. this._vertices[arrayOffset + 5] = offsetX;
  14652. this._vertices[arrayOffset + 6] = offsetY;
  14653. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14654. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14655. var offset = (sprite.cellIndex / rowSize) >> 0;
  14656. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14657. this._vertices[arrayOffset + 10] = offset;
  14658. // Color
  14659. this._vertices[arrayOffset + 11] = sprite.color.r;
  14660. this._vertices[arrayOffset + 12] = sprite.color.g;
  14661. this._vertices[arrayOffset + 13] = sprite.color.b;
  14662. this._vertices[arrayOffset + 14] = sprite.color.a;
  14663. };
  14664. SpriteManager.prototype.render = function () {
  14665. // Check
  14666. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14667. return;
  14668. var engine = this._scene.getEngine();
  14669. var baseSize = this._spriteTexture.getBaseSize();
  14670. // Sprites
  14671. var deltaTime = engine.getDeltaTime();
  14672. var max = Math.min(this._capacity, this.sprites.length);
  14673. var rowSize = baseSize.width / this.cellSize;
  14674. var offset = 0;
  14675. for (var index = 0; index < max; index++) {
  14676. var sprite = this.sprites[index];
  14677. if (!sprite) {
  14678. continue;
  14679. }
  14680. sprite._animate(deltaTime);
  14681. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14682. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14683. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14684. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14685. }
  14686. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14687. // Render
  14688. var effect = this._effectBase;
  14689. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14690. effect = this._effectFog;
  14691. }
  14692. engine.enableEffect(effect);
  14693. var viewMatrix = this._scene.getViewMatrix();
  14694. effect.setTexture("diffuseSampler", this._spriteTexture);
  14695. effect.setMatrix("view", viewMatrix);
  14696. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14697. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14698. // Fog
  14699. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14700. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14701. effect.setColor3("vFogColor", this._scene.fogColor);
  14702. }
  14703. // VBOs
  14704. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14705. // Draw order
  14706. effect.setBool("alphaTest", true);
  14707. engine.setColorWrite(false);
  14708. engine.draw(true, 0, max * 6);
  14709. engine.setColorWrite(true);
  14710. effect.setBool("alphaTest", false);
  14711. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14712. engine.draw(true, 0, max * 6);
  14713. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14714. };
  14715. SpriteManager.prototype.dispose = function () {
  14716. if (this._vertexBuffer) {
  14717. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14718. this._vertexBuffer = null;
  14719. }
  14720. if (this._indexBuffer) {
  14721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14722. this._indexBuffer = null;
  14723. }
  14724. if (this._spriteTexture) {
  14725. this._spriteTexture.dispose();
  14726. this._spriteTexture = null;
  14727. }
  14728. // Remove from scene
  14729. var index = this._scene.spriteManagers.indexOf(this);
  14730. this._scene.spriteManagers.splice(index, 1);
  14731. // Callback
  14732. if (this.onDispose) {
  14733. this.onDispose();
  14734. }
  14735. };
  14736. return SpriteManager;
  14737. })();
  14738. BABYLON.SpriteManager = SpriteManager;
  14739. })(BABYLON || (BABYLON = {}));
  14740. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14741. (function (BABYLON) {
  14742. var Sprite = (function () {
  14743. function Sprite(name, manager) {
  14744. this.name = name;
  14745. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14746. this.size = 1.0;
  14747. this.angle = 0;
  14748. this.cellIndex = 0;
  14749. this.invertU = 0;
  14750. this.invertV = 0;
  14751. this.animations = new Array();
  14752. this._animationStarted = false;
  14753. this._loopAnimation = false;
  14754. this._fromIndex = 0;
  14755. this._toIndex = 0;
  14756. this._delay = 0;
  14757. this._direction = 1;
  14758. this._frameCount = 0;
  14759. this._time = 0;
  14760. this._manager = manager;
  14761. this._manager.sprites.push(this);
  14762. this.position = BABYLON.Vector3.Zero();
  14763. }
  14764. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14765. this._fromIndex = from;
  14766. this._toIndex = to;
  14767. this._loopAnimation = loop;
  14768. this._delay = delay;
  14769. this._animationStarted = true;
  14770. this._direction = from < to ? 1 : -1;
  14771. this.cellIndex = from;
  14772. this._time = 0;
  14773. };
  14774. Sprite.prototype.stopAnimation = function () {
  14775. this._animationStarted = false;
  14776. };
  14777. Sprite.prototype._animate = function (deltaTime) {
  14778. if (!this._animationStarted)
  14779. return;
  14780. this._time += deltaTime;
  14781. if (this._time > this._delay) {
  14782. this._time = this._time % this._delay;
  14783. this.cellIndex += this._direction;
  14784. if (this.cellIndex == this._toIndex) {
  14785. if (this._loopAnimation) {
  14786. this.cellIndex = this._fromIndex;
  14787. }
  14788. else {
  14789. this._animationStarted = false;
  14790. if (this.disposeWhenFinishedAnimating) {
  14791. this.dispose();
  14792. }
  14793. }
  14794. }
  14795. }
  14796. };
  14797. Sprite.prototype.dispose = function () {
  14798. for (var i = 0; i < this._manager.sprites.length; i++) {
  14799. if (this._manager.sprites[i] == this) {
  14800. this._manager.sprites.splice(i, 1);
  14801. }
  14802. }
  14803. };
  14804. return Sprite;
  14805. })();
  14806. BABYLON.Sprite = Sprite;
  14807. })(BABYLON || (BABYLON = {}));
  14808. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14809. (function (BABYLON) {
  14810. var Layer = (function () {
  14811. function Layer(name, imgUrl, scene, isBackground, color) {
  14812. this.name = name;
  14813. this._vertexDeclaration = [2];
  14814. this._vertexStrideSize = 2 * 4;
  14815. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14816. this.isBackground = isBackground === undefined ? true : isBackground;
  14817. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14818. this._scene = scene;
  14819. this._scene.layers.push(this);
  14820. // VBO
  14821. var vertices = [];
  14822. vertices.push(1, 1);
  14823. vertices.push(-1, 1);
  14824. vertices.push(-1, -1);
  14825. vertices.push(1, -1);
  14826. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14827. // Indices
  14828. var indices = [];
  14829. indices.push(0);
  14830. indices.push(1);
  14831. indices.push(2);
  14832. indices.push(0);
  14833. indices.push(2);
  14834. indices.push(3);
  14835. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14836. // Effects
  14837. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14838. }
  14839. Layer.prototype.render = function () {
  14840. // Check
  14841. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14842. return;
  14843. var engine = this._scene.getEngine();
  14844. // Render
  14845. engine.enableEffect(this._effect);
  14846. engine.setState(false);
  14847. // Texture
  14848. this._effect.setTexture("textureSampler", this.texture);
  14849. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14850. // Color
  14851. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14852. // VBOs
  14853. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14854. // Draw order
  14855. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14856. engine.draw(true, 0, 6);
  14857. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14858. };
  14859. Layer.prototype.dispose = function () {
  14860. if (this._vertexBuffer) {
  14861. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14862. this._vertexBuffer = null;
  14863. }
  14864. if (this._indexBuffer) {
  14865. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14866. this._indexBuffer = null;
  14867. }
  14868. if (this.texture) {
  14869. this.texture.dispose();
  14870. this.texture = null;
  14871. }
  14872. // Remove from scene
  14873. var index = this._scene.layers.indexOf(this);
  14874. this._scene.layers.splice(index, 1);
  14875. // Callback
  14876. if (this.onDispose) {
  14877. this.onDispose();
  14878. }
  14879. };
  14880. return Layer;
  14881. })();
  14882. BABYLON.Layer = Layer;
  14883. })(BABYLON || (BABYLON = {}));
  14884. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14885. (function (BABYLON) {
  14886. var Particle = (function () {
  14887. function Particle() {
  14888. this.position = BABYLON.Vector3.Zero();
  14889. this.direction = BABYLON.Vector3.Zero();
  14890. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14891. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14892. this.lifeTime = 1.0;
  14893. this.age = 0;
  14894. this.size = 0;
  14895. this.angle = 0;
  14896. this.angularSpeed = 0;
  14897. }
  14898. Particle.prototype.copyTo = function (other) {
  14899. other.position.copyFrom(this.position);
  14900. other.direction.copyFrom(this.direction);
  14901. other.color.copyFrom(this.color);
  14902. other.colorStep.copyFrom(this.colorStep);
  14903. other.lifeTime = this.lifeTime;
  14904. other.age = this.age;
  14905. other.size = this.size;
  14906. other.angle = this.angle;
  14907. other.angularSpeed = this.angularSpeed;
  14908. };
  14909. return Particle;
  14910. })();
  14911. BABYLON.Particle = Particle;
  14912. })(BABYLON || (BABYLON = {}));
  14913. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14914. (function (BABYLON) {
  14915. var randomNumber = function (min, max) {
  14916. if (min === max) {
  14917. return (min);
  14918. }
  14919. var random = Math.random();
  14920. return ((random * (max - min)) + min);
  14921. };
  14922. var ParticleSystem = (function () {
  14923. function ParticleSystem(name, capacity, scene, customEffect) {
  14924. var _this = this;
  14925. this.name = name;
  14926. this.renderingGroupId = 0;
  14927. this.emitter = null;
  14928. this.emitRate = 10;
  14929. this.manualEmitCount = -1;
  14930. this.updateSpeed = 0.01;
  14931. this.targetStopDuration = 0;
  14932. this.disposeOnStop = false;
  14933. this.minEmitPower = 1;
  14934. this.maxEmitPower = 1;
  14935. this.minLifeTime = 1;
  14936. this.maxLifeTime = 1;
  14937. this.minSize = 1;
  14938. this.maxSize = 1;
  14939. this.minAngularSpeed = 0;
  14940. this.maxAngularSpeed = 0;
  14941. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14942. this.forceDepthWrite = false;
  14943. this.gravity = BABYLON.Vector3.Zero();
  14944. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14945. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14946. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14947. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14948. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14949. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14950. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14951. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14952. this.particles = new Array();
  14953. this._vertexDeclaration = [3, 4, 4];
  14954. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14955. this._stockParticles = new Array();
  14956. this._newPartsExcess = 0;
  14957. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14958. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14959. this._scaledDirection = BABYLON.Vector3.Zero();
  14960. this._scaledGravity = BABYLON.Vector3.Zero();
  14961. this._currentRenderId = -1;
  14962. this._started = false;
  14963. this._stopped = false;
  14964. this._actualFrame = 0;
  14965. this.id = name;
  14966. this._capacity = capacity;
  14967. this._scene = scene;
  14968. this._customEffect = customEffect;
  14969. scene.particleSystems.push(this);
  14970. // VBO
  14971. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14972. var indices = [];
  14973. var index = 0;
  14974. for (var count = 0; count < capacity; count++) {
  14975. indices.push(index);
  14976. indices.push(index + 1);
  14977. indices.push(index + 2);
  14978. indices.push(index);
  14979. indices.push(index + 2);
  14980. indices.push(index + 3);
  14981. index += 4;
  14982. }
  14983. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14984. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14985. // Default behaviors
  14986. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14987. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14988. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14989. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14990. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14991. };
  14992. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14993. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14994. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14995. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14997. };
  14998. this.updateFunction = function (particles) {
  14999. for (var index = 0; index < particles.length; index++) {
  15000. var particle = particles[index];
  15001. particle.age += _this._scaledUpdateSpeed;
  15002. if (particle.age >= particle.lifeTime) {
  15003. _this.recycleParticle(particle);
  15004. index--;
  15005. continue;
  15006. }
  15007. else {
  15008. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15009. particle.color.addInPlace(_this._scaledColorStep);
  15010. if (particle.color.a < 0)
  15011. particle.color.a = 0;
  15012. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15013. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15014. particle.position.addInPlace(_this._scaledDirection);
  15015. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15016. particle.direction.addInPlace(_this._scaledGravity);
  15017. }
  15018. }
  15019. };
  15020. }
  15021. ParticleSystem.prototype.recycleParticle = function (particle) {
  15022. var lastParticle = this.particles.pop();
  15023. if (lastParticle !== particle) {
  15024. lastParticle.copyTo(particle);
  15025. this._stockParticles.push(lastParticle);
  15026. }
  15027. };
  15028. ParticleSystem.prototype.getCapacity = function () {
  15029. return this._capacity;
  15030. };
  15031. ParticleSystem.prototype.isAlive = function () {
  15032. return this._alive;
  15033. };
  15034. ParticleSystem.prototype.isStarted = function () {
  15035. return this._started;
  15036. };
  15037. ParticleSystem.prototype.start = function () {
  15038. this._started = true;
  15039. this._stopped = false;
  15040. this._actualFrame = 0;
  15041. };
  15042. ParticleSystem.prototype.stop = function () {
  15043. this._stopped = true;
  15044. };
  15045. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15046. var offset = index * 11;
  15047. this._vertices[offset] = particle.position.x;
  15048. this._vertices[offset + 1] = particle.position.y;
  15049. this._vertices[offset + 2] = particle.position.z;
  15050. this._vertices[offset + 3] = particle.color.r;
  15051. this._vertices[offset + 4] = particle.color.g;
  15052. this._vertices[offset + 5] = particle.color.b;
  15053. this._vertices[offset + 6] = particle.color.a;
  15054. this._vertices[offset + 7] = particle.angle;
  15055. this._vertices[offset + 8] = particle.size;
  15056. this._vertices[offset + 9] = offsetX;
  15057. this._vertices[offset + 10] = offsetY;
  15058. };
  15059. ParticleSystem.prototype._update = function (newParticles) {
  15060. // Update current
  15061. this._alive = this.particles.length > 0;
  15062. this.updateFunction(this.particles);
  15063. // Add new ones
  15064. var worldMatrix;
  15065. if (this.emitter.position) {
  15066. worldMatrix = this.emitter.getWorldMatrix();
  15067. }
  15068. else {
  15069. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15070. }
  15071. for (var index = 0; index < newParticles; index++) {
  15072. if (this.particles.length === this._capacity) {
  15073. break;
  15074. }
  15075. if (this._stockParticles.length !== 0) {
  15076. var particle = this._stockParticles.pop();
  15077. particle.age = 0;
  15078. }
  15079. else {
  15080. particle = new BABYLON.Particle();
  15081. }
  15082. this.particles.push(particle);
  15083. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15084. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15085. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15086. particle.size = randomNumber(this.minSize, this.maxSize);
  15087. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15088. this.startPositionFunction(worldMatrix, particle.position);
  15089. var step = randomNumber(0, 1.0);
  15090. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15091. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15092. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15093. }
  15094. };
  15095. ParticleSystem.prototype._getEffect = function () {
  15096. if (this._customEffect) {
  15097. return this._customEffect;
  15098. }
  15099. ;
  15100. var defines = [];
  15101. if (this._scene.clipPlane) {
  15102. defines.push("#define CLIPPLANE");
  15103. }
  15104. // Effect
  15105. var join = defines.join("\n");
  15106. if (this._cachedDefines !== join) {
  15107. this._cachedDefines = join;
  15108. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15109. }
  15110. return this._effect;
  15111. };
  15112. ParticleSystem.prototype.animate = function () {
  15113. if (!this._started)
  15114. return;
  15115. var effect = this._getEffect();
  15116. // Check
  15117. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15118. return;
  15119. if (this._currentRenderId === this._scene.getRenderId()) {
  15120. return;
  15121. }
  15122. this._currentRenderId = this._scene.getRenderId();
  15123. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15124. // determine the number of particles we need to create
  15125. var emitCout;
  15126. if (this.manualEmitCount > -1) {
  15127. emitCout = this.manualEmitCount;
  15128. this.manualEmitCount = 0;
  15129. }
  15130. else {
  15131. emitCout = this.emitRate;
  15132. }
  15133. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15134. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15135. if (this._newPartsExcess > 1.0) {
  15136. newParticles += this._newPartsExcess >> 0;
  15137. this._newPartsExcess -= this._newPartsExcess >> 0;
  15138. }
  15139. this._alive = false;
  15140. if (!this._stopped) {
  15141. this._actualFrame += this._scaledUpdateSpeed;
  15142. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15143. this.stop();
  15144. }
  15145. else {
  15146. newParticles = 0;
  15147. }
  15148. this._update(newParticles);
  15149. // Stopped?
  15150. if (this._stopped) {
  15151. if (!this._alive) {
  15152. this._started = false;
  15153. if (this.disposeOnStop) {
  15154. this._scene._toBeDisposed.push(this);
  15155. }
  15156. }
  15157. }
  15158. // Update VBO
  15159. var offset = 0;
  15160. for (var index = 0; index < this.particles.length; index++) {
  15161. var particle = this.particles[index];
  15162. this._appendParticleVertex(offset++, particle, 0, 0);
  15163. this._appendParticleVertex(offset++, particle, 1, 0);
  15164. this._appendParticleVertex(offset++, particle, 1, 1);
  15165. this._appendParticleVertex(offset++, particle, 0, 1);
  15166. }
  15167. var engine = this._scene.getEngine();
  15168. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15169. };
  15170. ParticleSystem.prototype.render = function () {
  15171. var effect = this._getEffect();
  15172. // Check
  15173. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15174. return 0;
  15175. var engine = this._scene.getEngine();
  15176. // Render
  15177. engine.enableEffect(effect);
  15178. engine.setState(false);
  15179. var viewMatrix = this._scene.getViewMatrix();
  15180. effect.setTexture("diffuseSampler", this.particleTexture);
  15181. effect.setMatrix("view", viewMatrix);
  15182. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15183. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15184. if (this._scene.clipPlane) {
  15185. var clipPlane = this._scene.clipPlane;
  15186. var invView = viewMatrix.clone();
  15187. invView.invert();
  15188. effect.setMatrix("invView", invView);
  15189. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15190. }
  15191. // VBOs
  15192. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15193. // Draw order
  15194. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15195. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15196. }
  15197. else {
  15198. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15199. }
  15200. if (this.forceDepthWrite) {
  15201. engine.setDepthWrite(true);
  15202. }
  15203. engine.draw(true, 0, this.particles.length * 6);
  15204. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15205. return this.particles.length;
  15206. };
  15207. ParticleSystem.prototype.dispose = function () {
  15208. if (this._vertexBuffer) {
  15209. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15210. this._vertexBuffer = null;
  15211. }
  15212. if (this._indexBuffer) {
  15213. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15214. this._indexBuffer = null;
  15215. }
  15216. if (this.particleTexture) {
  15217. this.particleTexture.dispose();
  15218. this.particleTexture = null;
  15219. }
  15220. // Remove from scene
  15221. var index = this._scene.particleSystems.indexOf(this);
  15222. this._scene.particleSystems.splice(index, 1);
  15223. // Callback
  15224. if (this.onDispose) {
  15225. this.onDispose();
  15226. }
  15227. };
  15228. // Clone
  15229. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15230. var result = new ParticleSystem(name, this._capacity, this._scene);
  15231. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15232. if (newEmitter === undefined) {
  15233. newEmitter = this.emitter;
  15234. }
  15235. result.emitter = newEmitter;
  15236. if (this.particleTexture) {
  15237. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15238. }
  15239. result.start();
  15240. return result;
  15241. };
  15242. // Statics
  15243. ParticleSystem.BLENDMODE_ONEONE = 0;
  15244. ParticleSystem.BLENDMODE_STANDARD = 1;
  15245. return ParticleSystem;
  15246. })();
  15247. BABYLON.ParticleSystem = ParticleSystem;
  15248. })(BABYLON || (BABYLON = {}));
  15249. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15250. (function (BABYLON) {
  15251. var Animation = (function () {
  15252. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15253. this.name = name;
  15254. this.targetProperty = targetProperty;
  15255. this.framePerSecond = framePerSecond;
  15256. this.dataType = dataType;
  15257. this.loopMode = loopMode;
  15258. this._offsetsCache = {};
  15259. this._highLimitsCache = {};
  15260. this._stopped = false;
  15261. this.targetPropertyPath = targetProperty.split(".");
  15262. this.dataType = dataType;
  15263. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15264. }
  15265. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15266. var dataType = undefined;
  15267. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15268. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15269. }
  15270. else if (from instanceof BABYLON.Quaternion) {
  15271. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15272. }
  15273. else if (from instanceof BABYLON.Vector3) {
  15274. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15275. }
  15276. else if (from instanceof BABYLON.Vector2) {
  15277. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15278. }
  15279. else if (from instanceof BABYLON.Color3) {
  15280. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15281. }
  15282. if (dataType == undefined) {
  15283. return;
  15284. }
  15285. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15286. var keys = [];
  15287. keys.push({ frame: 0, value: from });
  15288. keys.push({ frame: totalFrame, value: to });
  15289. animation.setKeys(keys);
  15290. mesh.animations.push(animation);
  15291. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15292. };
  15293. // Methods
  15294. Animation.prototype.isStopped = function () {
  15295. return this._stopped;
  15296. };
  15297. Animation.prototype.getKeys = function () {
  15298. return this._keys;
  15299. };
  15300. Animation.prototype.getEasingFunction = function () {
  15301. return this._easingFunction;
  15302. };
  15303. Animation.prototype.setEasingFunction = function (easingFunction) {
  15304. this._easingFunction = easingFunction;
  15305. };
  15306. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15307. return startValue + (endValue - startValue) * gradient;
  15308. };
  15309. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15310. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15311. };
  15312. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15313. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15314. };
  15315. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15316. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15317. };
  15318. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15319. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15320. };
  15321. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15322. var startScale = new BABYLON.Vector3(0, 0, 0);
  15323. var startRotation = new BABYLON.Quaternion();
  15324. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15325. startValue.decompose(startScale, startRotation, startTranslation);
  15326. var endScale = new BABYLON.Vector3(0, 0, 0);
  15327. var endRotation = new BABYLON.Quaternion();
  15328. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15329. endValue.decompose(endScale, endRotation, endTranslation);
  15330. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15331. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15332. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15333. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15334. return result;
  15335. };
  15336. Animation.prototype.clone = function () {
  15337. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15338. clone.setKeys(this._keys);
  15339. return clone;
  15340. };
  15341. Animation.prototype.setKeys = function (values) {
  15342. this._keys = values.slice(0);
  15343. this._offsetsCache = {};
  15344. this._highLimitsCache = {};
  15345. };
  15346. Animation.prototype._getKeyValue = function (value) {
  15347. if (typeof value === "function") {
  15348. return value();
  15349. }
  15350. return value;
  15351. };
  15352. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15353. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15354. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15355. }
  15356. this.currentFrame = currentFrame;
  15357. for (var key = 0; key < this._keys.length; key++) {
  15358. // for each frame, we need the key just before the frame superior
  15359. if (this._keys[key + 1].frame >= currentFrame) {
  15360. var startValue = this._getKeyValue(this._keys[key].value);
  15361. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15362. // gradient : percent of currentFrame between the frame inf and the frame sup
  15363. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15364. // check for easingFunction and correction of gradient
  15365. if (this._easingFunction != null) {
  15366. gradient = this._easingFunction.ease(gradient);
  15367. }
  15368. switch (this.dataType) {
  15369. case Animation.ANIMATIONTYPE_FLOAT:
  15370. switch (loopMode) {
  15371. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15372. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15373. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15374. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15375. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15376. }
  15377. break;
  15378. case Animation.ANIMATIONTYPE_QUATERNION:
  15379. var quaternion = null;
  15380. switch (loopMode) {
  15381. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15382. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15383. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15384. break;
  15385. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15386. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15387. break;
  15388. }
  15389. return quaternion;
  15390. case Animation.ANIMATIONTYPE_VECTOR3:
  15391. switch (loopMode) {
  15392. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15393. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15394. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15395. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15396. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15397. }
  15398. case Animation.ANIMATIONTYPE_VECTOR2:
  15399. switch (loopMode) {
  15400. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15401. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15402. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15403. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15404. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15405. }
  15406. case Animation.ANIMATIONTYPE_COLOR3:
  15407. switch (loopMode) {
  15408. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15409. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15410. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15411. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15412. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15413. }
  15414. case Animation.ANIMATIONTYPE_MATRIX:
  15415. switch (loopMode) {
  15416. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15417. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15418. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15419. return startValue;
  15420. }
  15421. default:
  15422. break;
  15423. }
  15424. break;
  15425. }
  15426. }
  15427. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15428. };
  15429. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15430. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15431. this._stopped = true;
  15432. return false;
  15433. }
  15434. var returnValue = true;
  15435. // Adding a start key at frame 0 if missing
  15436. if (this._keys[0].frame !== 0) {
  15437. var newKey = { frame: 0, value: this._keys[0].value };
  15438. this._keys.splice(0, 0, newKey);
  15439. }
  15440. // Check limits
  15441. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15442. from = this._keys[0].frame;
  15443. }
  15444. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15445. to = this._keys[this._keys.length - 1].frame;
  15446. }
  15447. // Compute ratio
  15448. var range = to - from;
  15449. var offsetValue;
  15450. // ratio represents the frame delta between from and to
  15451. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15452. var highLimitValue = 0;
  15453. if (ratio > range && !loop) {
  15454. returnValue = false;
  15455. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15456. }
  15457. else {
  15458. // Get max value if required
  15459. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15460. var keyOffset = to.toString() + from.toString();
  15461. if (!this._offsetsCache[keyOffset]) {
  15462. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15463. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15464. switch (this.dataType) {
  15465. case Animation.ANIMATIONTYPE_FLOAT:
  15466. this._offsetsCache[keyOffset] = toValue - fromValue;
  15467. break;
  15468. case Animation.ANIMATIONTYPE_QUATERNION:
  15469. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15470. break;
  15471. case Animation.ANIMATIONTYPE_VECTOR3:
  15472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15473. case Animation.ANIMATIONTYPE_VECTOR2:
  15474. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15475. case Animation.ANIMATIONTYPE_COLOR3:
  15476. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15477. default:
  15478. break;
  15479. }
  15480. this._highLimitsCache[keyOffset] = toValue;
  15481. }
  15482. highLimitValue = this._highLimitsCache[keyOffset];
  15483. offsetValue = this._offsetsCache[keyOffset];
  15484. }
  15485. }
  15486. if (offsetValue === undefined) {
  15487. switch (this.dataType) {
  15488. case Animation.ANIMATIONTYPE_FLOAT:
  15489. offsetValue = 0;
  15490. break;
  15491. case Animation.ANIMATIONTYPE_QUATERNION:
  15492. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15493. break;
  15494. case Animation.ANIMATIONTYPE_VECTOR3:
  15495. offsetValue = BABYLON.Vector3.Zero();
  15496. break;
  15497. case Animation.ANIMATIONTYPE_VECTOR2:
  15498. offsetValue = BABYLON.Vector2.Zero();
  15499. break;
  15500. case Animation.ANIMATIONTYPE_COLOR3:
  15501. offsetValue = BABYLON.Color3.Black();
  15502. }
  15503. }
  15504. // Compute value
  15505. var repeatCount = (ratio / range) >> 0;
  15506. var currentFrame = returnValue ? from + ratio % range : to;
  15507. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15508. // Set value
  15509. if (this.targetPropertyPath.length > 1) {
  15510. var property = this._target[this.targetPropertyPath[0]];
  15511. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15512. property = property[this.targetPropertyPath[index]];
  15513. }
  15514. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15515. }
  15516. else {
  15517. this._target[this.targetPropertyPath[0]] = currentValue;
  15518. }
  15519. if (this._target.markAsDirty) {
  15520. this._target.markAsDirty(this.targetProperty);
  15521. }
  15522. if (!returnValue) {
  15523. this._stopped = true;
  15524. }
  15525. return returnValue;
  15526. };
  15527. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15528. get: function () {
  15529. return Animation._ANIMATIONTYPE_FLOAT;
  15530. },
  15531. enumerable: true,
  15532. configurable: true
  15533. });
  15534. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15535. get: function () {
  15536. return Animation._ANIMATIONTYPE_VECTOR3;
  15537. },
  15538. enumerable: true,
  15539. configurable: true
  15540. });
  15541. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15542. get: function () {
  15543. return Animation._ANIMATIONTYPE_VECTOR2;
  15544. },
  15545. enumerable: true,
  15546. configurable: true
  15547. });
  15548. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15549. get: function () {
  15550. return Animation._ANIMATIONTYPE_QUATERNION;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15556. get: function () {
  15557. return Animation._ANIMATIONTYPE_MATRIX;
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15563. get: function () {
  15564. return Animation._ANIMATIONTYPE_COLOR3;
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15570. get: function () {
  15571. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15577. get: function () {
  15578. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15584. get: function () {
  15585. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. // Statics
  15591. Animation._ANIMATIONTYPE_FLOAT = 0;
  15592. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15593. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15594. Animation._ANIMATIONTYPE_MATRIX = 3;
  15595. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15596. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15597. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15598. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15599. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15600. return Animation;
  15601. })();
  15602. BABYLON.Animation = Animation;
  15603. })(BABYLON || (BABYLON = {}));
  15604. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15605. (function (BABYLON) {
  15606. var Animatable = (function () {
  15607. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15608. if (fromFrame === void 0) { fromFrame = 0; }
  15609. if (toFrame === void 0) { toFrame = 100; }
  15610. if (loopAnimation === void 0) { loopAnimation = false; }
  15611. if (speedRatio === void 0) { speedRatio = 1.0; }
  15612. this.target = target;
  15613. this.fromFrame = fromFrame;
  15614. this.toFrame = toFrame;
  15615. this.loopAnimation = loopAnimation;
  15616. this.speedRatio = speedRatio;
  15617. this.onAnimationEnd = onAnimationEnd;
  15618. this._animations = new Array();
  15619. this._paused = false;
  15620. this.animationStarted = false;
  15621. if (animations) {
  15622. this.appendAnimations(target, animations);
  15623. }
  15624. this._scene = scene;
  15625. scene._activeAnimatables.push(this);
  15626. }
  15627. // Methods
  15628. Animatable.prototype.appendAnimations = function (target, animations) {
  15629. for (var index = 0; index < animations.length; index++) {
  15630. var animation = animations[index];
  15631. animation._target = target;
  15632. this._animations.push(animation);
  15633. }
  15634. };
  15635. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15636. var animations = this._animations;
  15637. for (var index = 0; index < animations.length; index++) {
  15638. if (animations[index].targetProperty === property) {
  15639. return animations[index];
  15640. }
  15641. }
  15642. return null;
  15643. };
  15644. Animatable.prototype.pause = function () {
  15645. if (this._paused) {
  15646. return;
  15647. }
  15648. this._paused = true;
  15649. };
  15650. Animatable.prototype.restart = function () {
  15651. this._paused = false;
  15652. };
  15653. Animatable.prototype.stop = function () {
  15654. var index = this._scene._activeAnimatables.indexOf(this);
  15655. if (index > -1) {
  15656. this._scene._activeAnimatables.splice(index, 1);
  15657. }
  15658. if (this.onAnimationEnd) {
  15659. this.onAnimationEnd();
  15660. }
  15661. };
  15662. Animatable.prototype._animate = function (delay) {
  15663. if (this._paused) {
  15664. if (!this._pausedDelay) {
  15665. this._pausedDelay = delay;
  15666. }
  15667. return true;
  15668. }
  15669. if (!this._localDelayOffset) {
  15670. this._localDelayOffset = delay;
  15671. }
  15672. else if (this._pausedDelay) {
  15673. this._localDelayOffset += delay - this._pausedDelay;
  15674. this._pausedDelay = null;
  15675. }
  15676. // Animating
  15677. var running = false;
  15678. var animations = this._animations;
  15679. for (var index = 0; index < animations.length; index++) {
  15680. var animation = animations[index];
  15681. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15682. running = running || isRunning;
  15683. }
  15684. if (!running && this.onAnimationEnd) {
  15685. this.onAnimationEnd();
  15686. }
  15687. return running;
  15688. };
  15689. return Animatable;
  15690. })();
  15691. BABYLON.Animatable = Animatable;
  15692. })(BABYLON || (BABYLON = {}));
  15693. //# sourceMappingURL=babylon.animatable.js.map
  15694. var BABYLON;
  15695. (function (BABYLON) {
  15696. var EasingFunction = (function () {
  15697. function EasingFunction() {
  15698. // Properties
  15699. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15700. }
  15701. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15702. get: function () {
  15703. return EasingFunction._EASINGMODE_EASEIN;
  15704. },
  15705. enumerable: true,
  15706. configurable: true
  15707. });
  15708. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15709. get: function () {
  15710. return EasingFunction._EASINGMODE_EASEOUT;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15716. get: function () {
  15717. return EasingFunction._EASINGMODE_EASEINOUT;
  15718. },
  15719. enumerable: true,
  15720. configurable: true
  15721. });
  15722. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15723. var n = Math.min(Math.max(easingMode, 0), 2);
  15724. this._easingMode = n;
  15725. };
  15726. EasingFunction.prototype.getEasingMode = function () {
  15727. return this._easingMode;
  15728. };
  15729. EasingFunction.prototype.easeInCore = function (gradient) {
  15730. throw new Error('You must implement this method');
  15731. };
  15732. EasingFunction.prototype.ease = function (gradient) {
  15733. switch (this._easingMode) {
  15734. case EasingFunction.EASINGMODE_EASEIN:
  15735. return this.easeInCore(gradient);
  15736. case EasingFunction.EASINGMODE_EASEOUT:
  15737. return (1 - this.easeInCore(1 - gradient));
  15738. }
  15739. if (gradient >= 0.5) {
  15740. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15741. }
  15742. return (this.easeInCore(gradient * 2) * 0.5);
  15743. };
  15744. //Statics
  15745. EasingFunction._EASINGMODE_EASEIN = 0;
  15746. EasingFunction._EASINGMODE_EASEOUT = 1;
  15747. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15748. return EasingFunction;
  15749. })();
  15750. BABYLON.EasingFunction = EasingFunction;
  15751. var CircleEase = (function (_super) {
  15752. __extends(CircleEase, _super);
  15753. function CircleEase() {
  15754. _super.apply(this, arguments);
  15755. }
  15756. CircleEase.prototype.easeInCore = function (gradient) {
  15757. gradient = Math.max(0, Math.min(1, gradient));
  15758. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15759. };
  15760. return CircleEase;
  15761. })(EasingFunction);
  15762. BABYLON.CircleEase = CircleEase;
  15763. var BackEase = (function (_super) {
  15764. __extends(BackEase, _super);
  15765. function BackEase(amplitude) {
  15766. if (amplitude === void 0) { amplitude = 1; }
  15767. _super.call(this);
  15768. this.amplitude = amplitude;
  15769. }
  15770. BackEase.prototype.easeInCore = function (gradient) {
  15771. var num = Math.max(0, this.amplitude);
  15772. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15773. };
  15774. return BackEase;
  15775. })(EasingFunction);
  15776. BABYLON.BackEase = BackEase;
  15777. var BounceEase = (function (_super) {
  15778. __extends(BounceEase, _super);
  15779. function BounceEase(bounces, bounciness) {
  15780. if (bounces === void 0) { bounces = 3; }
  15781. if (bounciness === void 0) { bounciness = 2; }
  15782. _super.call(this);
  15783. this.bounces = bounces;
  15784. this.bounciness = bounciness;
  15785. }
  15786. BounceEase.prototype.easeInCore = function (gradient) {
  15787. var y = Math.max(0.0, this.bounces);
  15788. var bounciness = this.bounciness;
  15789. if (bounciness <= 1.0) {
  15790. bounciness = 1.001;
  15791. }
  15792. var num9 = Math.pow(bounciness, y);
  15793. var num5 = 1.0 - bounciness;
  15794. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15795. var num15 = gradient * num4;
  15796. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15797. var num3 = Math.floor(num65);
  15798. var num13 = num3 + 1.0;
  15799. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15800. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15801. var num7 = (num8 + num12) * 0.5;
  15802. var num6 = gradient - num7;
  15803. var num2 = num7 - num8;
  15804. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15805. };
  15806. return BounceEase;
  15807. })(EasingFunction);
  15808. BABYLON.BounceEase = BounceEase;
  15809. var CubicEase = (function (_super) {
  15810. __extends(CubicEase, _super);
  15811. function CubicEase() {
  15812. _super.apply(this, arguments);
  15813. }
  15814. CubicEase.prototype.easeInCore = function (gradient) {
  15815. return (gradient * gradient * gradient);
  15816. };
  15817. return CubicEase;
  15818. })(EasingFunction);
  15819. BABYLON.CubicEase = CubicEase;
  15820. var ElasticEase = (function (_super) {
  15821. __extends(ElasticEase, _super);
  15822. function ElasticEase(oscillations, springiness) {
  15823. if (oscillations === void 0) { oscillations = 3; }
  15824. if (springiness === void 0) { springiness = 3; }
  15825. _super.call(this);
  15826. this.oscillations = oscillations;
  15827. this.springiness = springiness;
  15828. }
  15829. ElasticEase.prototype.easeInCore = function (gradient) {
  15830. var num2;
  15831. var num3 = Math.max(0.0, this.oscillations);
  15832. var num = Math.max(0.0, this.springiness);
  15833. if (num == 0) {
  15834. num2 = gradient;
  15835. }
  15836. else {
  15837. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15838. }
  15839. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15840. };
  15841. return ElasticEase;
  15842. })(EasingFunction);
  15843. BABYLON.ElasticEase = ElasticEase;
  15844. var ExponentialEase = (function (_super) {
  15845. __extends(ExponentialEase, _super);
  15846. function ExponentialEase(exponent) {
  15847. if (exponent === void 0) { exponent = 2; }
  15848. _super.call(this);
  15849. this.exponent = exponent;
  15850. }
  15851. ExponentialEase.prototype.easeInCore = function (gradient) {
  15852. if (this.exponent <= 0) {
  15853. return gradient;
  15854. }
  15855. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15856. };
  15857. return ExponentialEase;
  15858. })(EasingFunction);
  15859. BABYLON.ExponentialEase = ExponentialEase;
  15860. var PowerEase = (function (_super) {
  15861. __extends(PowerEase, _super);
  15862. function PowerEase(power) {
  15863. if (power === void 0) { power = 2; }
  15864. _super.call(this);
  15865. this.power = power;
  15866. }
  15867. PowerEase.prototype.easeInCore = function (gradient) {
  15868. var y = Math.max(0.0, this.power);
  15869. return Math.pow(gradient, y);
  15870. };
  15871. return PowerEase;
  15872. })(EasingFunction);
  15873. BABYLON.PowerEase = PowerEase;
  15874. var QuadraticEase = (function (_super) {
  15875. __extends(QuadraticEase, _super);
  15876. function QuadraticEase() {
  15877. _super.apply(this, arguments);
  15878. }
  15879. QuadraticEase.prototype.easeInCore = function (gradient) {
  15880. return (gradient * gradient);
  15881. };
  15882. return QuadraticEase;
  15883. })(EasingFunction);
  15884. BABYLON.QuadraticEase = QuadraticEase;
  15885. var QuarticEase = (function (_super) {
  15886. __extends(QuarticEase, _super);
  15887. function QuarticEase() {
  15888. _super.apply(this, arguments);
  15889. }
  15890. QuarticEase.prototype.easeInCore = function (gradient) {
  15891. return (gradient * gradient * gradient * gradient);
  15892. };
  15893. return QuarticEase;
  15894. })(EasingFunction);
  15895. BABYLON.QuarticEase = QuarticEase;
  15896. var QuinticEase = (function (_super) {
  15897. __extends(QuinticEase, _super);
  15898. function QuinticEase() {
  15899. _super.apply(this, arguments);
  15900. }
  15901. QuinticEase.prototype.easeInCore = function (gradient) {
  15902. return (gradient * gradient * gradient * gradient * gradient);
  15903. };
  15904. return QuinticEase;
  15905. })(EasingFunction);
  15906. BABYLON.QuinticEase = QuinticEase;
  15907. var SineEase = (function (_super) {
  15908. __extends(SineEase, _super);
  15909. function SineEase() {
  15910. _super.apply(this, arguments);
  15911. }
  15912. SineEase.prototype.easeInCore = function (gradient) {
  15913. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15914. };
  15915. return SineEase;
  15916. })(EasingFunction);
  15917. BABYLON.SineEase = SineEase;
  15918. var BezierCurveEase = (function (_super) {
  15919. __extends(BezierCurveEase, _super);
  15920. function BezierCurveEase(x1, y1, x2, y2) {
  15921. if (x1 === void 0) { x1 = 0; }
  15922. if (y1 === void 0) { y1 = 0; }
  15923. if (x2 === void 0) { x2 = 1; }
  15924. if (y2 === void 0) { y2 = 1; }
  15925. _super.call(this);
  15926. this.x1 = x1;
  15927. this.y1 = y1;
  15928. this.x2 = x2;
  15929. this.y2 = y2;
  15930. }
  15931. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15932. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15933. };
  15934. return BezierCurveEase;
  15935. })(EasingFunction);
  15936. BABYLON.BezierCurveEase = BezierCurveEase;
  15937. })(BABYLON || (BABYLON = {}));
  15938. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15939. (function (BABYLON) {
  15940. var Octree = (function () {
  15941. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15942. if (maxDepth === void 0) { maxDepth = 2; }
  15943. this.maxDepth = maxDepth;
  15944. this.dynamicContent = new Array();
  15945. this._maxBlockCapacity = maxBlockCapacity || 64;
  15946. this._selectionContent = new BABYLON.SmartArray(1024);
  15947. this._creationFunc = creationFunc;
  15948. }
  15949. // Methods
  15950. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15951. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15952. };
  15953. Octree.prototype.addMesh = function (entry) {
  15954. for (var index = 0; index < this.blocks.length; index++) {
  15955. var block = this.blocks[index];
  15956. block.addEntry(entry);
  15957. }
  15958. };
  15959. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15960. this._selectionContent.reset();
  15961. for (var index = 0; index < this.blocks.length; index++) {
  15962. var block = this.blocks[index];
  15963. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15964. }
  15965. if (allowDuplicate) {
  15966. this._selectionContent.concat(this.dynamicContent);
  15967. }
  15968. else {
  15969. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15970. }
  15971. return this._selectionContent;
  15972. };
  15973. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15974. this._selectionContent.reset();
  15975. for (var index = 0; index < this.blocks.length; index++) {
  15976. var block = this.blocks[index];
  15977. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15978. }
  15979. if (allowDuplicate) {
  15980. this._selectionContent.concat(this.dynamicContent);
  15981. }
  15982. else {
  15983. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15984. }
  15985. return this._selectionContent;
  15986. };
  15987. Octree.prototype.intersectsRay = function (ray) {
  15988. this._selectionContent.reset();
  15989. for (var index = 0; index < this.blocks.length; index++) {
  15990. var block = this.blocks[index];
  15991. block.intersectsRay(ray, this._selectionContent);
  15992. }
  15993. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15994. return this._selectionContent;
  15995. };
  15996. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15997. target.blocks = new Array();
  15998. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15999. for (var x = 0; x < 2; x++) {
  16000. for (var y = 0; y < 2; y++) {
  16001. for (var z = 0; z < 2; z++) {
  16002. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16003. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16004. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16005. block.addEntries(entries);
  16006. target.blocks.push(block);
  16007. }
  16008. }
  16009. }
  16010. };
  16011. Octree.CreationFuncForMeshes = function (entry, block) {
  16012. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16013. block.entries.push(entry);
  16014. }
  16015. };
  16016. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16017. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16018. block.entries.push(entry);
  16019. }
  16020. };
  16021. return Octree;
  16022. })();
  16023. BABYLON.Octree = Octree;
  16024. })(BABYLON || (BABYLON = {}));
  16025. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16026. (function (BABYLON) {
  16027. var OctreeBlock = (function () {
  16028. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16029. this.entries = new Array();
  16030. this._boundingVectors = new Array();
  16031. this._capacity = capacity;
  16032. this._depth = depth;
  16033. this._maxDepth = maxDepth;
  16034. this._creationFunc = creationFunc;
  16035. this._minPoint = minPoint;
  16036. this._maxPoint = maxPoint;
  16037. this._boundingVectors.push(minPoint.clone());
  16038. this._boundingVectors.push(maxPoint.clone());
  16039. this._boundingVectors.push(minPoint.clone());
  16040. this._boundingVectors[2].x = maxPoint.x;
  16041. this._boundingVectors.push(minPoint.clone());
  16042. this._boundingVectors[3].y = maxPoint.y;
  16043. this._boundingVectors.push(minPoint.clone());
  16044. this._boundingVectors[4].z = maxPoint.z;
  16045. this._boundingVectors.push(maxPoint.clone());
  16046. this._boundingVectors[5].z = minPoint.z;
  16047. this._boundingVectors.push(maxPoint.clone());
  16048. this._boundingVectors[6].x = minPoint.x;
  16049. this._boundingVectors.push(maxPoint.clone());
  16050. this._boundingVectors[7].y = minPoint.y;
  16051. }
  16052. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16053. // Property
  16054. get: function () {
  16055. return this._capacity;
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16061. get: function () {
  16062. return this._minPoint;
  16063. },
  16064. enumerable: true,
  16065. configurable: true
  16066. });
  16067. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16068. get: function () {
  16069. return this._maxPoint;
  16070. },
  16071. enumerable: true,
  16072. configurable: true
  16073. });
  16074. // Methods
  16075. OctreeBlock.prototype.addEntry = function (entry) {
  16076. if (this.blocks) {
  16077. for (var index = 0; index < this.blocks.length; index++) {
  16078. var block = this.blocks[index];
  16079. block.addEntry(entry);
  16080. }
  16081. return;
  16082. }
  16083. this._creationFunc(entry, this);
  16084. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16085. this.createInnerBlocks();
  16086. }
  16087. };
  16088. OctreeBlock.prototype.addEntries = function (entries) {
  16089. for (var index = 0; index < entries.length; index++) {
  16090. var mesh = entries[index];
  16091. this.addEntry(mesh);
  16092. }
  16093. };
  16094. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16095. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16096. if (this.blocks) {
  16097. for (var index = 0; index < this.blocks.length; index++) {
  16098. var block = this.blocks[index];
  16099. block.select(frustumPlanes, selection, allowDuplicate);
  16100. }
  16101. return;
  16102. }
  16103. if (allowDuplicate) {
  16104. selection.concat(this.entries);
  16105. }
  16106. else {
  16107. selection.concatWithNoDuplicate(this.entries);
  16108. }
  16109. }
  16110. };
  16111. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16112. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16113. if (this.blocks) {
  16114. for (var index = 0; index < this.blocks.length; index++) {
  16115. var block = this.blocks[index];
  16116. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16117. }
  16118. return;
  16119. }
  16120. if (allowDuplicate) {
  16121. selection.concat(this.entries);
  16122. }
  16123. else {
  16124. selection.concatWithNoDuplicate(this.entries);
  16125. }
  16126. }
  16127. };
  16128. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16129. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16130. if (this.blocks) {
  16131. for (var index = 0; index < this.blocks.length; index++) {
  16132. var block = this.blocks[index];
  16133. block.intersectsRay(ray, selection);
  16134. }
  16135. return;
  16136. }
  16137. selection.concatWithNoDuplicate(this.entries);
  16138. }
  16139. };
  16140. OctreeBlock.prototype.createInnerBlocks = function () {
  16141. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16142. };
  16143. return OctreeBlock;
  16144. })();
  16145. BABYLON.OctreeBlock = OctreeBlock;
  16146. })(BABYLON || (BABYLON = {}));
  16147. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16148. (function (BABYLON) {
  16149. var Bone = (function () {
  16150. function Bone(name, skeleton, parentBone, matrix) {
  16151. this.name = name;
  16152. this.children = new Array();
  16153. this.animations = new Array();
  16154. this._worldTransform = new BABYLON.Matrix();
  16155. this._absoluteTransform = new BABYLON.Matrix();
  16156. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16157. this._skeleton = skeleton;
  16158. this._matrix = matrix;
  16159. this._baseMatrix = matrix;
  16160. skeleton.bones.push(this);
  16161. if (parentBone) {
  16162. this._parent = parentBone;
  16163. parentBone.children.push(this);
  16164. }
  16165. else {
  16166. this._parent = null;
  16167. }
  16168. this._updateDifferenceMatrix();
  16169. }
  16170. // Members
  16171. Bone.prototype.getParent = function () {
  16172. return this._parent;
  16173. };
  16174. Bone.prototype.getLocalMatrix = function () {
  16175. return this._matrix;
  16176. };
  16177. Bone.prototype.getBaseMatrix = function () {
  16178. return this._baseMatrix;
  16179. };
  16180. Bone.prototype.getWorldMatrix = function () {
  16181. return this._worldTransform;
  16182. };
  16183. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16184. return this._invertedAbsoluteTransform;
  16185. };
  16186. Bone.prototype.getAbsoluteMatrix = function () {
  16187. var matrix = this._matrix.clone();
  16188. var parent = this._parent;
  16189. while (parent) {
  16190. matrix = matrix.multiply(parent.getLocalMatrix());
  16191. parent = parent.getParent();
  16192. }
  16193. return matrix;
  16194. };
  16195. // Methods
  16196. Bone.prototype.updateMatrix = function (matrix) {
  16197. this._matrix = matrix;
  16198. this._skeleton._markAsDirty();
  16199. this._updateDifferenceMatrix();
  16200. };
  16201. Bone.prototype._updateDifferenceMatrix = function () {
  16202. if (this._parent) {
  16203. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16204. }
  16205. else {
  16206. this._absoluteTransform.copyFrom(this._matrix);
  16207. }
  16208. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16209. for (var index = 0; index < this.children.length; index++) {
  16210. this.children[index]._updateDifferenceMatrix();
  16211. }
  16212. };
  16213. Bone.prototype.markAsDirty = function () {
  16214. this._skeleton._markAsDirty();
  16215. };
  16216. return Bone;
  16217. })();
  16218. BABYLON.Bone = Bone;
  16219. })(BABYLON || (BABYLON = {}));
  16220. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16221. (function (BABYLON) {
  16222. var Skeleton = (function () {
  16223. function Skeleton(name, id, scene) {
  16224. this.name = name;
  16225. this.id = id;
  16226. this.bones = new Array();
  16227. this._isDirty = true;
  16228. this._identity = BABYLON.Matrix.Identity();
  16229. this.bones = [];
  16230. this._scene = scene;
  16231. scene.skeletons.push(this);
  16232. }
  16233. // Members
  16234. Skeleton.prototype.getTransformMatrices = function () {
  16235. return this._transformMatrices;
  16236. };
  16237. // Methods
  16238. Skeleton.prototype._markAsDirty = function () {
  16239. this._isDirty = true;
  16240. };
  16241. Skeleton.prototype.prepare = function () {
  16242. if (!this._isDirty) {
  16243. return;
  16244. }
  16245. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16246. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16247. }
  16248. for (var index = 0; index < this.bones.length; index++) {
  16249. var bone = this.bones[index];
  16250. var parentBone = bone.getParent();
  16251. if (parentBone) {
  16252. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16253. }
  16254. else {
  16255. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16256. }
  16257. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16258. }
  16259. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16260. this._isDirty = false;
  16261. };
  16262. Skeleton.prototype.getAnimatables = function () {
  16263. if (!this._animatables || this._animatables.length != this.bones.length) {
  16264. this._animatables = [];
  16265. for (var index = 0; index < this.bones.length; index++) {
  16266. this._animatables.push(this.bones[index]);
  16267. }
  16268. }
  16269. return this._animatables;
  16270. };
  16271. Skeleton.prototype.clone = function (name, id) {
  16272. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16273. for (var index = 0; index < this.bones.length; index++) {
  16274. var source = this.bones[index];
  16275. var parentBone = null;
  16276. if (source.getParent()) {
  16277. var parentIndex = this.bones.indexOf(source.getParent());
  16278. parentBone = result.bones[parentIndex];
  16279. }
  16280. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16281. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16282. }
  16283. return result;
  16284. };
  16285. return Skeleton;
  16286. })();
  16287. BABYLON.Skeleton = Skeleton;
  16288. })(BABYLON || (BABYLON = {}));
  16289. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16290. (function (BABYLON) {
  16291. var PostProcess = (function () {
  16292. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16293. this.name = name;
  16294. this.width = -1;
  16295. this.height = -1;
  16296. this._reusable = false;
  16297. this._textures = new BABYLON.SmartArray(2);
  16298. this._currentRenderTextureInd = 0;
  16299. if (camera != null) {
  16300. this._camera = camera;
  16301. this._scene = camera.getScene();
  16302. camera.attachPostProcess(this);
  16303. this._engine = this._scene.getEngine();
  16304. }
  16305. else {
  16306. this._engine = engine;
  16307. }
  16308. this._renderRatio = ratio;
  16309. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16310. this._reusable = reusable || false;
  16311. samplers = samplers || [];
  16312. samplers.push("textureSampler");
  16313. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16314. }
  16315. PostProcess.prototype.isReusable = function () {
  16316. return this._reusable;
  16317. };
  16318. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16319. camera = camera || this._camera;
  16320. var scene = camera.getScene();
  16321. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16322. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16323. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16324. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16325. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16326. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16327. if (this._textures.length > 0) {
  16328. for (var i = 0; i < this._textures.length; i++) {
  16329. this._engine._releaseTexture(this._textures.data[i]);
  16330. }
  16331. this._textures.reset();
  16332. }
  16333. this.width = desiredWidth;
  16334. this.height = desiredHeight;
  16335. 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 }));
  16336. if (this._reusable) {
  16337. 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 }));
  16338. }
  16339. if (this.onSizeChanged) {
  16340. this.onSizeChanged();
  16341. }
  16342. }
  16343. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16344. if (this.onActivate) {
  16345. this.onActivate(camera);
  16346. }
  16347. // Clear
  16348. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16349. if (this._reusable) {
  16350. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16351. }
  16352. };
  16353. PostProcess.prototype.apply = function () {
  16354. // Check
  16355. if (!this._effect.isReady())
  16356. return null;
  16357. // States
  16358. this._engine.enableEffect(this._effect);
  16359. this._engine.setState(false);
  16360. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16361. this._engine.setDepthBuffer(false);
  16362. this._engine.setDepthWrite(false);
  16363. // Texture
  16364. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16365. // Parameters
  16366. if (this.onApply) {
  16367. this.onApply(this._effect);
  16368. }
  16369. return this._effect;
  16370. };
  16371. PostProcess.prototype.dispose = function (camera) {
  16372. camera = camera || this._camera;
  16373. if (this._textures.length > 0) {
  16374. for (var i = 0; i < this._textures.length; i++) {
  16375. this._engine._releaseTexture(this._textures.data[i]);
  16376. }
  16377. this._textures.reset();
  16378. }
  16379. camera.detachPostProcess(this);
  16380. var index = camera._postProcesses.indexOf(this);
  16381. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16382. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16383. }
  16384. };
  16385. return PostProcess;
  16386. })();
  16387. BABYLON.PostProcess = PostProcess;
  16388. })(BABYLON || (BABYLON = {}));
  16389. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16390. (function (BABYLON) {
  16391. var PostProcessManager = (function () {
  16392. function PostProcessManager(scene) {
  16393. this._vertexDeclaration = [2];
  16394. this._vertexStrideSize = 2 * 4;
  16395. this._scene = scene;
  16396. // VBO
  16397. var vertices = [];
  16398. vertices.push(1, 1);
  16399. vertices.push(-1, 1);
  16400. vertices.push(-1, -1);
  16401. vertices.push(1, -1);
  16402. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16403. // Indices
  16404. var indices = [];
  16405. indices.push(0);
  16406. indices.push(1);
  16407. indices.push(2);
  16408. indices.push(0);
  16409. indices.push(2);
  16410. indices.push(3);
  16411. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16412. }
  16413. // Methods
  16414. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16415. var postProcesses = this._scene.activeCamera._postProcesses;
  16416. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16417. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16418. return false;
  16419. }
  16420. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16421. return true;
  16422. };
  16423. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16424. var postProcesses = this._scene.activeCamera._postProcesses;
  16425. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16426. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16427. return;
  16428. }
  16429. var engine = this._scene.getEngine();
  16430. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16431. if (index < postProcessesTakenIndices.length - 1) {
  16432. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16433. }
  16434. else {
  16435. if (targetTexture) {
  16436. engine.bindFramebuffer(targetTexture);
  16437. }
  16438. else {
  16439. engine.restoreDefaultFramebuffer();
  16440. }
  16441. }
  16442. if (doNotPresent) {
  16443. break;
  16444. }
  16445. var pp = postProcesses[postProcessesTakenIndices[index]];
  16446. var effect = pp.apply();
  16447. if (effect) {
  16448. if (pp.onBeforeRender) {
  16449. pp.onBeforeRender(effect);
  16450. }
  16451. // VBOs
  16452. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16453. // Draw order
  16454. engine.draw(true, 0, 6);
  16455. }
  16456. }
  16457. // Restore depth buffer
  16458. engine.setDepthBuffer(true);
  16459. engine.setDepthWrite(true);
  16460. };
  16461. PostProcessManager.prototype.dispose = function () {
  16462. if (this._vertexBuffer) {
  16463. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16464. this._vertexBuffer = null;
  16465. }
  16466. if (this._indexBuffer) {
  16467. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16468. this._indexBuffer = null;
  16469. }
  16470. };
  16471. return PostProcessManager;
  16472. })();
  16473. BABYLON.PostProcessManager = PostProcessManager;
  16474. })(BABYLON || (BABYLON = {}));
  16475. //# sourceMappingURL=babylon.postProcessManager.js.map
  16476. var BABYLON;
  16477. (function (BABYLON) {
  16478. var PassPostProcess = (function (_super) {
  16479. __extends(PassPostProcess, _super);
  16480. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16481. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16482. }
  16483. return PassPostProcess;
  16484. })(BABYLON.PostProcess);
  16485. BABYLON.PassPostProcess = PassPostProcess;
  16486. })(BABYLON || (BABYLON = {}));
  16487. //# sourceMappingURL=babylon.passPostProcess.js.map
  16488. var BABYLON;
  16489. (function (BABYLON) {
  16490. var BlurPostProcess = (function (_super) {
  16491. __extends(BlurPostProcess, _super);
  16492. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16493. var _this = this;
  16494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16495. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16496. this.direction = direction;
  16497. this.blurWidth = blurWidth;
  16498. this.onApply = function (effect) {
  16499. effect.setFloat2("screenSize", _this.width, _this.height);
  16500. effect.setVector2("direction", _this.direction);
  16501. effect.setFloat("blurWidth", _this.blurWidth);
  16502. };
  16503. }
  16504. return BlurPostProcess;
  16505. })(BABYLON.PostProcess);
  16506. BABYLON.BlurPostProcess = BlurPostProcess;
  16507. })(BABYLON || (BABYLON = {}));
  16508. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16509. var BABYLON;
  16510. (function (BABYLON) {
  16511. var FilterPostProcess = (function (_super) {
  16512. __extends(FilterPostProcess, _super);
  16513. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16514. var _this = this;
  16515. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16516. this.kernelMatrix = kernelMatrix;
  16517. this.onApply = function (effect) {
  16518. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16519. };
  16520. }
  16521. return FilterPostProcess;
  16522. })(BABYLON.PostProcess);
  16523. BABYLON.FilterPostProcess = FilterPostProcess;
  16524. })(BABYLON || (BABYLON = {}));
  16525. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16526. var BABYLON;
  16527. (function (BABYLON) {
  16528. var RefractionPostProcess = (function (_super) {
  16529. __extends(RefractionPostProcess, _super);
  16530. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16531. var _this = this;
  16532. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16533. this.color = color;
  16534. this.depth = depth;
  16535. this.colorLevel = colorLevel;
  16536. this.onActivate = function (cam) {
  16537. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16538. };
  16539. this.onApply = function (effect) {
  16540. effect.setColor3("baseColor", _this.color);
  16541. effect.setFloat("depth", _this.depth);
  16542. effect.setFloat("colorLevel", _this.colorLevel);
  16543. effect.setTexture("refractionSampler", _this._refRexture);
  16544. };
  16545. }
  16546. // Methods
  16547. RefractionPostProcess.prototype.dispose = function (camera) {
  16548. if (this._refRexture) {
  16549. this._refRexture.dispose();
  16550. }
  16551. _super.prototype.dispose.call(this, camera);
  16552. };
  16553. return RefractionPostProcess;
  16554. })(BABYLON.PostProcess);
  16555. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16556. })(BABYLON || (BABYLON = {}));
  16557. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16558. var BABYLON;
  16559. (function (BABYLON) {
  16560. var BlackAndWhitePostProcess = (function (_super) {
  16561. __extends(BlackAndWhitePostProcess, _super);
  16562. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16563. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16564. }
  16565. return BlackAndWhitePostProcess;
  16566. })(BABYLON.PostProcess);
  16567. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16568. })(BABYLON || (BABYLON = {}));
  16569. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16570. var BABYLON;
  16571. (function (BABYLON) {
  16572. var ConvolutionPostProcess = (function (_super) {
  16573. __extends(ConvolutionPostProcess, _super);
  16574. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16575. var _this = this;
  16576. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16577. this.kernel = kernel;
  16578. this.onApply = function (effect) {
  16579. effect.setFloat2("screenSize", _this.width, _this.height);
  16580. effect.setArray("kernel", _this.kernel);
  16581. };
  16582. }
  16583. // Statics
  16584. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16585. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16586. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16587. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16588. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16589. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16590. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16591. return ConvolutionPostProcess;
  16592. })(BABYLON.PostProcess);
  16593. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16594. })(BABYLON || (BABYLON = {}));
  16595. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16596. var BABYLON;
  16597. (function (BABYLON) {
  16598. var FxaaPostProcess = (function (_super) {
  16599. __extends(FxaaPostProcess, _super);
  16600. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16601. var _this = this;
  16602. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16603. this.onSizeChanged = function () {
  16604. _this.texelWidth = 1.0 / _this.width;
  16605. _this.texelHeight = 1.0 / _this.height;
  16606. };
  16607. this.onApply = function (effect) {
  16608. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16609. };
  16610. }
  16611. return FxaaPostProcess;
  16612. })(BABYLON.PostProcess);
  16613. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16614. })(BABYLON || (BABYLON = {}));
  16615. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16616. (function (BABYLON) {
  16617. var LensFlare = (function () {
  16618. function LensFlare(size, position, color, imgUrl, system) {
  16619. this.size = size;
  16620. this.position = position;
  16621. this.dispose = function () {
  16622. if (this.texture) {
  16623. this.texture.dispose();
  16624. }
  16625. // Remove from scene
  16626. var index = this._system.lensFlares.indexOf(this);
  16627. this._system.lensFlares.splice(index, 1);
  16628. };
  16629. this.color = color || new BABYLON.Color3(1, 1, 1);
  16630. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16631. this._system = system;
  16632. system.lensFlares.push(this);
  16633. }
  16634. return LensFlare;
  16635. })();
  16636. BABYLON.LensFlare = LensFlare;
  16637. })(BABYLON || (BABYLON = {}));
  16638. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16639. (function (BABYLON) {
  16640. var LensFlareSystem = (function () {
  16641. function LensFlareSystem(name, emitter, scene) {
  16642. this.name = name;
  16643. this.lensFlares = new Array();
  16644. this.borderLimit = 300;
  16645. this._vertexDeclaration = [2];
  16646. this._vertexStrideSize = 2 * 4;
  16647. this._isEnabled = true;
  16648. this._scene = scene;
  16649. this._emitter = emitter;
  16650. scene.lensFlareSystems.push(this);
  16651. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16652. // VBO
  16653. var vertices = [];
  16654. vertices.push(1, 1);
  16655. vertices.push(-1, 1);
  16656. vertices.push(-1, -1);
  16657. vertices.push(1, -1);
  16658. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16659. // Indices
  16660. var indices = [];
  16661. indices.push(0);
  16662. indices.push(1);
  16663. indices.push(2);
  16664. indices.push(0);
  16665. indices.push(2);
  16666. indices.push(3);
  16667. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16668. // Effects
  16669. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16670. }
  16671. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16672. get: function () {
  16673. return this._isEnabled;
  16674. },
  16675. set: function (value) {
  16676. this._isEnabled = value;
  16677. },
  16678. enumerable: true,
  16679. configurable: true
  16680. });
  16681. LensFlareSystem.prototype.getScene = function () {
  16682. return this._scene;
  16683. };
  16684. LensFlareSystem.prototype.getEmitter = function () {
  16685. return this._emitter;
  16686. };
  16687. LensFlareSystem.prototype.getEmitterPosition = function () {
  16688. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16689. };
  16690. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16691. var position = this.getEmitterPosition();
  16692. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16693. this._positionX = position.x;
  16694. this._positionY = position.y;
  16695. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16696. if (position.z > 0) {
  16697. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16698. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16699. return true;
  16700. }
  16701. }
  16702. return false;
  16703. };
  16704. LensFlareSystem.prototype._isVisible = function () {
  16705. if (!this._isEnabled) {
  16706. return false;
  16707. }
  16708. var emitterPosition = this.getEmitterPosition();
  16709. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16710. var distance = direction.length();
  16711. direction.normalize();
  16712. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16713. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16714. return !pickInfo.hit || pickInfo.distance > distance;
  16715. };
  16716. LensFlareSystem.prototype.render = function () {
  16717. if (!this._effect.isReady())
  16718. return false;
  16719. var engine = this._scene.getEngine();
  16720. var viewport = this._scene.activeCamera.viewport;
  16721. var globalViewport = viewport.toGlobal(engine);
  16722. // Position
  16723. if (!this.computeEffectivePosition(globalViewport)) {
  16724. return false;
  16725. }
  16726. // Visibility
  16727. if (!this._isVisible()) {
  16728. return false;
  16729. }
  16730. // Intensity
  16731. var awayX;
  16732. var awayY;
  16733. if (this._positionX < this.borderLimit + globalViewport.x) {
  16734. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16735. }
  16736. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16737. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16738. }
  16739. else {
  16740. awayX = 0;
  16741. }
  16742. if (this._positionY < this.borderLimit + globalViewport.y) {
  16743. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16744. }
  16745. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16746. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16747. }
  16748. else {
  16749. awayY = 0;
  16750. }
  16751. var away = (awayX > awayY) ? awayX : awayY;
  16752. if (away > this.borderLimit) {
  16753. away = this.borderLimit;
  16754. }
  16755. var intensity = 1.0 - (away / this.borderLimit);
  16756. if (intensity < 0) {
  16757. return false;
  16758. }
  16759. if (intensity > 1.0) {
  16760. intensity = 1.0;
  16761. }
  16762. // Position
  16763. var centerX = globalViewport.x + globalViewport.width / 2;
  16764. var centerY = globalViewport.y + globalViewport.height / 2;
  16765. var distX = centerX - this._positionX;
  16766. var distY = centerY - this._positionY;
  16767. // Effects
  16768. engine.enableEffect(this._effect);
  16769. engine.setState(false);
  16770. engine.setDepthBuffer(false);
  16771. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16772. // VBOs
  16773. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16774. for (var index = 0; index < this.lensFlares.length; index++) {
  16775. var flare = this.lensFlares[index];
  16776. var x = centerX - (distX * flare.position);
  16777. var y = centerY - (distY * flare.position);
  16778. var cw = flare.size;
  16779. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16780. var cx = 2 * (x / globalViewport.width) - 1.0;
  16781. var cy = 1.0 - 2 * (y / globalViewport.height);
  16782. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16783. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16784. // Texture
  16785. this._effect.setTexture("textureSampler", flare.texture);
  16786. // Color
  16787. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16788. // Draw order
  16789. engine.draw(true, 0, 6);
  16790. }
  16791. engine.setDepthBuffer(true);
  16792. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16793. return true;
  16794. };
  16795. LensFlareSystem.prototype.dispose = function () {
  16796. if (this._vertexBuffer) {
  16797. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16798. this._vertexBuffer = null;
  16799. }
  16800. if (this._indexBuffer) {
  16801. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16802. this._indexBuffer = null;
  16803. }
  16804. while (this.lensFlares.length) {
  16805. this.lensFlares[0].dispose();
  16806. }
  16807. // Remove from scene
  16808. var index = this._scene.lensFlareSystems.indexOf(this);
  16809. this._scene.lensFlareSystems.splice(index, 1);
  16810. };
  16811. return LensFlareSystem;
  16812. })();
  16813. BABYLON.LensFlareSystem = LensFlareSystem;
  16814. })(BABYLON || (BABYLON = {}));
  16815. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16816. (function (BABYLON) {
  16817. var IntersectionInfo = (function () {
  16818. function IntersectionInfo(bu, bv, distance) {
  16819. this.bu = bu;
  16820. this.bv = bv;
  16821. this.distance = distance;
  16822. this.faceId = 0;
  16823. }
  16824. return IntersectionInfo;
  16825. })();
  16826. BABYLON.IntersectionInfo = IntersectionInfo;
  16827. var PickingInfo = (function () {
  16828. function PickingInfo() {
  16829. this.hit = false;
  16830. this.distance = 0;
  16831. this.pickedPoint = null;
  16832. this.pickedMesh = null;
  16833. this.bu = 0;
  16834. this.bv = 0;
  16835. this.faceId = -1;
  16836. }
  16837. // Methods
  16838. PickingInfo.prototype.getNormal = function () {
  16839. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16840. return null;
  16841. }
  16842. var indices = this.pickedMesh.getIndices();
  16843. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16844. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16845. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16846. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16847. normal0 = normal0.scale(this.bu);
  16848. normal1 = normal1.scale(this.bv);
  16849. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16850. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16851. };
  16852. PickingInfo.prototype.getTextureCoordinates = function () {
  16853. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16854. return null;
  16855. }
  16856. var indices = this.pickedMesh.getIndices();
  16857. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16858. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16859. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16860. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16861. uv0 = uv0.scale(this.bu);
  16862. uv1 = uv1.scale(this.bv);
  16863. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16864. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16865. };
  16866. return PickingInfo;
  16867. })();
  16868. BABYLON.PickingInfo = PickingInfo;
  16869. })(BABYLON || (BABYLON = {}));
  16870. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16871. (function (BABYLON) {
  16872. var FilesInput = (function () {
  16873. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16874. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16875. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16876. this.engine = p_engine;
  16877. this.canvas = p_canvas;
  16878. this.currentScene = p_scene;
  16879. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16880. this.progressCallback = p_progressCallback;
  16881. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16882. this.textureLoadingCallback = p_textureLoadingCallback;
  16883. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16884. }
  16885. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16886. var _this = this;
  16887. if (p_elementToMonitor) {
  16888. this.elementToMonitor = p_elementToMonitor;
  16889. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16890. _this.drag(e);
  16891. }, false);
  16892. this.elementToMonitor.addEventListener("dragover", function (e) {
  16893. _this.drag(e);
  16894. }, false);
  16895. this.elementToMonitor.addEventListener("drop", function (e) {
  16896. _this.drop(e);
  16897. }, false);
  16898. }
  16899. };
  16900. FilesInput.prototype.renderFunction = function () {
  16901. if (this.additionnalRenderLoopLogicCallback) {
  16902. this.additionnalRenderLoopLogicCallback();
  16903. }
  16904. if (this.currentScene) {
  16905. if (this.textureLoadingCallback) {
  16906. var remaining = this.currentScene.getWaitingItemsCount();
  16907. if (remaining > 0) {
  16908. this.textureLoadingCallback(remaining);
  16909. }
  16910. }
  16911. this.currentScene.render();
  16912. }
  16913. };
  16914. FilesInput.prototype.drag = function (e) {
  16915. e.stopPropagation();
  16916. e.preventDefault();
  16917. };
  16918. FilesInput.prototype.drop = function (eventDrop) {
  16919. eventDrop.stopPropagation();
  16920. eventDrop.preventDefault();
  16921. this.loadFiles(eventDrop);
  16922. };
  16923. FilesInput.prototype.loadFiles = function (event) {
  16924. var _this = this;
  16925. var that = this;
  16926. if (this.startingProcessingFilesCallback)
  16927. this.startingProcessingFilesCallback();
  16928. var sceneFileToLoad;
  16929. var filesToLoad;
  16930. // Handling data transfer via drag'n'drop
  16931. if (event && event.dataTransfer && event.dataTransfer.files) {
  16932. filesToLoad = event.dataTransfer.files;
  16933. }
  16934. // Handling files from input files
  16935. if (event && event.target && event.target.files) {
  16936. filesToLoad = event.target.files;
  16937. }
  16938. if (filesToLoad && filesToLoad.length > 0) {
  16939. for (var i = 0; i < filesToLoad.length; i++) {
  16940. switch (filesToLoad[i].type) {
  16941. case "image/jpeg":
  16942. case "image/png":
  16943. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16944. break;
  16945. case "image/targa":
  16946. case "image/vnd.ms-dds":
  16947. case "audio/wav":
  16948. case "audio/x-wav":
  16949. case "audio/mpeg":
  16950. case "audio/mpeg3":
  16951. case "audio/x-mpeg-3":
  16952. case "audio/ogg":
  16953. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16954. break;
  16955. default:
  16956. 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) {
  16957. sceneFileToLoad = filesToLoad[i];
  16958. }
  16959. break;
  16960. }
  16961. }
  16962. // If a ".babylon" file has been provided
  16963. if (sceneFileToLoad) {
  16964. if (this.currentScene) {
  16965. this.engine.stopRenderLoop();
  16966. this.currentScene.dispose();
  16967. }
  16968. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16969. that.currentScene = newScene;
  16970. // Wait for textures and shaders to be ready
  16971. that.currentScene.executeWhenReady(function () {
  16972. // Attach camera to canvas inputs
  16973. if (that.currentScene.activeCamera) {
  16974. that.currentScene.activeCamera.attachControl(that.canvas);
  16975. }
  16976. if (that.sceneLoadedCallback) {
  16977. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16978. }
  16979. that.engine.runRenderLoop(function () {
  16980. that.renderFunction();
  16981. });
  16982. });
  16983. }, function (progress) {
  16984. if (_this.progressCallback) {
  16985. _this.progressCallback(progress);
  16986. }
  16987. });
  16988. }
  16989. else {
  16990. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16991. }
  16992. }
  16993. };
  16994. FilesInput.FilesTextures = new Array();
  16995. FilesInput.FilesToLoad = new Array();
  16996. return FilesInput;
  16997. })();
  16998. BABYLON.FilesInput = FilesInput;
  16999. })(BABYLON || (BABYLON = {}));
  17000. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17001. (function (BABYLON) {
  17002. var OimoJSPlugin = (function () {
  17003. function OimoJSPlugin() {
  17004. this._registeredMeshes = [];
  17005. /**
  17006. * Update the body position according to the mesh position
  17007. * @param mesh
  17008. */
  17009. this.updateBodyPosition = function (mesh) {
  17010. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17011. var registeredMesh = this._registeredMeshes[index];
  17012. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17013. var body = registeredMesh.body.body;
  17014. mesh.computeWorldMatrix(true);
  17015. var center = mesh.getBoundingInfo().boundingBox.center;
  17016. body.setPosition(center.x, center.y, center.z);
  17017. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17018. return;
  17019. }
  17020. // Case where the parent has been updated
  17021. if (registeredMesh.mesh.parent === mesh) {
  17022. mesh.computeWorldMatrix(true);
  17023. registeredMesh.mesh.computeWorldMatrix(true);
  17024. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17025. var absoluteRotation = mesh.rotation;
  17026. body = registeredMesh.body.body;
  17027. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17028. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17029. return;
  17030. }
  17031. }
  17032. };
  17033. }
  17034. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17035. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17036. };
  17037. OimoJSPlugin.prototype.initialize = function (iterations) {
  17038. this._world = new OIMO.World();
  17039. this._world.clear();
  17040. };
  17041. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17042. this._world.gravity = gravity;
  17043. };
  17044. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17045. var body = null;
  17046. this.unregisterMesh(mesh);
  17047. mesh.computeWorldMatrix(true);
  17048. switch (impostor) {
  17049. case BABYLON.PhysicsEngine.SphereImpostor:
  17050. var initialRotation = null;
  17051. if (mesh.rotationQuaternion) {
  17052. initialRotation = mesh.rotationQuaternion.clone();
  17053. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17054. mesh.computeWorldMatrix(true);
  17055. }
  17056. var bbox = mesh.getBoundingInfo().boundingBox;
  17057. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17058. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17059. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17060. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17061. // The delta between the mesh position and the mesh bounding box center
  17062. var deltaPosition = mesh.position.subtract(bbox.center);
  17063. // Transform delta position with the rotation
  17064. if (initialRotation) {
  17065. var m = new BABYLON.Matrix();
  17066. initialRotation.toRotationMatrix(m);
  17067. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17068. }
  17069. body = new OIMO.Body({
  17070. type: 'sphere',
  17071. size: [size],
  17072. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17073. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17074. move: options.mass != 0,
  17075. config: [options.mass, options.friction, options.restitution],
  17076. world: this._world
  17077. });
  17078. // Restore rotation
  17079. if (initialRotation) {
  17080. body.setQuaternion(initialRotation);
  17081. }
  17082. this._registeredMeshes.push({
  17083. mesh: mesh,
  17084. body: body,
  17085. delta: deltaPosition
  17086. });
  17087. break;
  17088. case BABYLON.PhysicsEngine.PlaneImpostor:
  17089. case BABYLON.PhysicsEngine.BoxImpostor:
  17090. initialRotation = null;
  17091. if (mesh.rotationQuaternion) {
  17092. initialRotation = mesh.rotationQuaternion.clone();
  17093. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17094. mesh.computeWorldMatrix(true);
  17095. }
  17096. bbox = mesh.getBoundingInfo().boundingBox;
  17097. var min = bbox.minimumWorld;
  17098. var max = bbox.maximumWorld;
  17099. var box = max.subtract(min);
  17100. var sizeX = this._checkWithEpsilon(box.x);
  17101. var sizeY = this._checkWithEpsilon(box.y);
  17102. var sizeZ = this._checkWithEpsilon(box.z);
  17103. // The delta between the mesh position and the mesh boudning box center
  17104. deltaPosition = mesh.position.subtract(bbox.center);
  17105. // Transform delta position with the rotation
  17106. if (initialRotation) {
  17107. m = new BABYLON.Matrix();
  17108. initialRotation.toRotationMatrix(m);
  17109. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17110. }
  17111. body = new OIMO.Body({
  17112. type: 'box',
  17113. size: [sizeX, sizeY, sizeZ],
  17114. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17115. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17116. move: options.mass != 0,
  17117. config: [options.mass, options.friction, options.restitution],
  17118. world: this._world
  17119. });
  17120. if (initialRotation) {
  17121. body.setQuaternion(initialRotation);
  17122. }
  17123. this._registeredMeshes.push({
  17124. mesh: mesh,
  17125. body: body,
  17126. delta: deltaPosition
  17127. });
  17128. break;
  17129. }
  17130. return body;
  17131. };
  17132. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17133. var types = [], sizes = [], positions = [], rotations = [];
  17134. var initialMesh = parts[0].mesh;
  17135. for (var index = 0; index < parts.length; index++) {
  17136. var part = parts[index];
  17137. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17138. types.push(bodyParameters.type);
  17139. sizes.push.apply(sizes, bodyParameters.size);
  17140. positions.push.apply(positions, bodyParameters.pos);
  17141. rotations.push.apply(rotations, bodyParameters.rot);
  17142. }
  17143. var body = new OIMO.Body({
  17144. type: types,
  17145. size: sizes,
  17146. pos: positions,
  17147. rot: rotations,
  17148. move: options.mass != 0,
  17149. config: [options.mass, options.friction, options.restitution],
  17150. world: this._world
  17151. });
  17152. this._registeredMeshes.push({
  17153. mesh: initialMesh,
  17154. body: body
  17155. });
  17156. return body;
  17157. };
  17158. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17159. var bodyParameters = null;
  17160. var mesh = part.mesh;
  17161. // We need the bounding box/sphere info to compute the physics body
  17162. mesh.computeWorldMatrix();
  17163. switch (part.impostor) {
  17164. case BABYLON.PhysicsEngine.SphereImpostor:
  17165. var bbox = mesh.getBoundingInfo().boundingBox;
  17166. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17167. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17168. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17169. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17170. bodyParameters = {
  17171. type: 'sphere',
  17172. /* bug with oimo : sphere needs 3 sizes in this case */
  17173. size: [size, -1, -1],
  17174. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17175. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17176. };
  17177. break;
  17178. case BABYLON.PhysicsEngine.PlaneImpostor:
  17179. case BABYLON.PhysicsEngine.BoxImpostor:
  17180. bbox = mesh.getBoundingInfo().boundingBox;
  17181. var min = bbox.minimumWorld;
  17182. var max = bbox.maximumWorld;
  17183. var box = max.subtract(min);
  17184. var sizeX = this._checkWithEpsilon(box.x);
  17185. var sizeY = this._checkWithEpsilon(box.y);
  17186. var sizeZ = this._checkWithEpsilon(box.z);
  17187. var relativePosition = mesh.position;
  17188. bodyParameters = {
  17189. type: 'box',
  17190. size: [sizeX, sizeY, sizeZ],
  17191. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17192. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17193. };
  17194. break;
  17195. }
  17196. return bodyParameters;
  17197. };
  17198. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17199. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17200. var registeredMesh = this._registeredMeshes[index];
  17201. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17202. if (registeredMesh.body) {
  17203. this._world.removeRigidBody(registeredMesh.body.body);
  17204. this._unbindBody(registeredMesh.body);
  17205. }
  17206. this._registeredMeshes.splice(index, 1);
  17207. return;
  17208. }
  17209. }
  17210. };
  17211. OimoJSPlugin.prototype._unbindBody = function (body) {
  17212. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17213. var registeredMesh = this._registeredMeshes[index];
  17214. if (registeredMesh.body === body) {
  17215. registeredMesh.body = null;
  17216. }
  17217. }
  17218. };
  17219. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17220. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17221. var registeredMesh = this._registeredMeshes[index];
  17222. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17223. // Get object mass to have a behaviour similar to cannon.js
  17224. var mass = registeredMesh.body.body.massInfo.mass;
  17225. // The force is scaled with the mass of object
  17226. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17227. return;
  17228. }
  17229. }
  17230. };
  17231. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17232. var body1 = null, body2 = null;
  17233. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17234. var registeredMesh = this._registeredMeshes[index];
  17235. if (registeredMesh.mesh === mesh1) {
  17236. body1 = registeredMesh.body.body;
  17237. }
  17238. else if (registeredMesh.mesh === mesh2) {
  17239. body2 = registeredMesh.body.body;
  17240. }
  17241. }
  17242. if (!body1 || !body2) {
  17243. return false;
  17244. }
  17245. if (!options) {
  17246. options = {};
  17247. }
  17248. new OIMO.Link({
  17249. type: options.type,
  17250. body1: body1,
  17251. body2: body2,
  17252. min: options.min,
  17253. max: options.max,
  17254. axe1: options.axe1,
  17255. axe2: options.axe2,
  17256. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17257. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17258. collision: options.collision,
  17259. spring: options.spring,
  17260. world: this._world
  17261. });
  17262. return true;
  17263. };
  17264. OimoJSPlugin.prototype.dispose = function () {
  17265. this._world.clear();
  17266. while (this._registeredMeshes.length) {
  17267. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17268. }
  17269. };
  17270. OimoJSPlugin.prototype.isSupported = function () {
  17271. return OIMO !== undefined;
  17272. };
  17273. OimoJSPlugin.prototype._getLastShape = function (body) {
  17274. var lastShape = body.shapes;
  17275. while (lastShape.next) {
  17276. lastShape = lastShape.next;
  17277. }
  17278. return lastShape;
  17279. };
  17280. OimoJSPlugin.prototype.runOneStep = function (time) {
  17281. this._world.step();
  17282. // Update the position of all registered meshes
  17283. var i = this._registeredMeshes.length;
  17284. var m;
  17285. while (i--) {
  17286. var body = this._registeredMeshes[i].body.body;
  17287. var mesh = this._registeredMeshes[i].mesh;
  17288. var delta = this._registeredMeshes[i].delta;
  17289. if (!body.sleeping) {
  17290. if (body.shapes.next) {
  17291. var parentShape = this._getLastShape(body);
  17292. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17293. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17294. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17295. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17296. if (!mesh.rotationQuaternion) {
  17297. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17298. }
  17299. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17300. mesh.computeWorldMatrix();
  17301. }
  17302. else {
  17303. m = body.getMatrix();
  17304. mtx = BABYLON.Matrix.FromArray(m);
  17305. // Body position
  17306. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17307. if (!delta) {
  17308. mesh.position.x = bodyX;
  17309. mesh.position.y = bodyY;
  17310. mesh.position.z = bodyZ;
  17311. }
  17312. else {
  17313. mesh.position.x = bodyX + delta.x;
  17314. mesh.position.y = bodyY + delta.y;
  17315. mesh.position.z = bodyZ + delta.z;
  17316. }
  17317. if (!mesh.rotationQuaternion) {
  17318. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17319. }
  17320. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17321. mesh.computeWorldMatrix();
  17322. }
  17323. }
  17324. }
  17325. };
  17326. return OimoJSPlugin;
  17327. })();
  17328. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17329. })(BABYLON || (BABYLON = {}));
  17330. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17331. (function (BABYLON) {
  17332. var PhysicsEngine = (function () {
  17333. function PhysicsEngine(plugin) {
  17334. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17335. }
  17336. PhysicsEngine.prototype._initialize = function (gravity) {
  17337. this._currentPlugin.initialize();
  17338. this._setGravity(gravity);
  17339. };
  17340. PhysicsEngine.prototype._runOneStep = function (delta) {
  17341. if (delta > 0.1) {
  17342. delta = 0.1;
  17343. }
  17344. else if (delta <= 0) {
  17345. delta = 1.0 / 60.0;
  17346. }
  17347. this._currentPlugin.runOneStep(delta);
  17348. };
  17349. PhysicsEngine.prototype._setGravity = function (gravity) {
  17350. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17351. this._currentPlugin.setGravity(this.gravity);
  17352. };
  17353. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17354. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17355. };
  17356. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17357. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17358. };
  17359. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17360. this._currentPlugin.unregisterMesh(mesh);
  17361. };
  17362. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17363. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17364. };
  17365. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17366. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17367. };
  17368. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17369. this._currentPlugin.updateBodyPosition(mesh);
  17370. };
  17371. PhysicsEngine.prototype.dispose = function () {
  17372. this._currentPlugin.dispose();
  17373. };
  17374. PhysicsEngine.prototype.isSupported = function () {
  17375. return this._currentPlugin.isSupported();
  17376. };
  17377. // Statics
  17378. PhysicsEngine.NoImpostor = 0;
  17379. PhysicsEngine.SphereImpostor = 1;
  17380. PhysicsEngine.BoxImpostor = 2;
  17381. PhysicsEngine.PlaneImpostor = 3;
  17382. PhysicsEngine.MeshImpostor = 4;
  17383. PhysicsEngine.CapsuleImpostor = 5;
  17384. PhysicsEngine.ConeImpostor = 6;
  17385. PhysicsEngine.CylinderImpostor = 7;
  17386. PhysicsEngine.ConvexHullImpostor = 8;
  17387. PhysicsEngine.Epsilon = 0.001;
  17388. return PhysicsEngine;
  17389. })();
  17390. BABYLON.PhysicsEngine = PhysicsEngine;
  17391. })(BABYLON || (BABYLON = {}));
  17392. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17393. (function (BABYLON) {
  17394. var serializeLight = function (light) {
  17395. var serializationObject = {};
  17396. serializationObject.name = light.name;
  17397. serializationObject.id = light.id;
  17398. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17399. if (light instanceof BABYLON.PointLight) {
  17400. serializationObject.type = 0;
  17401. serializationObject.position = light.position.asArray();
  17402. }
  17403. else if (light instanceof BABYLON.DirectionalLight) {
  17404. serializationObject.type = 1;
  17405. var directionalLight = light;
  17406. serializationObject.position = directionalLight.position.asArray();
  17407. serializationObject.direction = directionalLight.direction.asArray();
  17408. }
  17409. else if (light instanceof BABYLON.SpotLight) {
  17410. serializationObject.type = 2;
  17411. var spotLight = light;
  17412. serializationObject.position = spotLight.position.asArray();
  17413. serializationObject.direction = spotLight.position.asArray();
  17414. serializationObject.angle = spotLight.angle;
  17415. serializationObject.exponent = spotLight.exponent;
  17416. }
  17417. else if (light instanceof BABYLON.HemisphericLight) {
  17418. serializationObject.type = 3;
  17419. var hemisphericLight = light;
  17420. serializationObject.direction = hemisphericLight.direction.asArray();
  17421. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17422. }
  17423. if (light.intensity) {
  17424. serializationObject.intensity = light.intensity;
  17425. }
  17426. serializationObject.range = light.range;
  17427. serializationObject.diffuse = light.diffuse.asArray();
  17428. serializationObject.specular = light.specular.asArray();
  17429. return serializationObject;
  17430. };
  17431. var serializeFresnelParameter = function (fresnelParameter) {
  17432. var serializationObject = {};
  17433. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17434. serializationObject.leftColor = fresnelParameter.leftColor;
  17435. serializationObject.rightColor = fresnelParameter.rightColor;
  17436. serializationObject.bias = fresnelParameter.bias;
  17437. serializationObject.power = fresnelParameter.power;
  17438. return serializationObject;
  17439. };
  17440. var serializeCamera = function (camera) {
  17441. var serializationObject = {};
  17442. serializationObject.name = camera.name;
  17443. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17444. serializationObject.id = camera.id;
  17445. serializationObject.position = camera.position.asArray();
  17446. // Parent
  17447. if (camera.parent) {
  17448. serializationObject.parentId = camera.parent.id;
  17449. }
  17450. // Target
  17451. serializationObject.rotation = camera.rotation.asArray();
  17452. // Locked target
  17453. if (camera.lockedTarget && camera.lockedTarget.id) {
  17454. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17455. }
  17456. serializationObject.fov = camera.fov;
  17457. serializationObject.minZ = camera.minZ;
  17458. serializationObject.maxZ = camera.maxZ;
  17459. serializationObject.speed = camera.speed;
  17460. serializationObject.inertia = camera.inertia;
  17461. serializationObject.checkCollisions = camera.checkCollisions;
  17462. serializationObject.applyGravity = camera.applyGravity;
  17463. if (camera.ellipsoid) {
  17464. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17465. }
  17466. // Animations
  17467. appendAnimations(camera, serializationObject);
  17468. // Layer mask
  17469. serializationObject.layerMask = camera.layerMask;
  17470. return serializationObject;
  17471. };
  17472. var appendAnimations = function (source, destination) {
  17473. if (source.animations) {
  17474. destination.animations = [];
  17475. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17476. var animation = source.animations[animationIndex];
  17477. destination.animations.push(serializeAnimation(animation));
  17478. }
  17479. }
  17480. };
  17481. var serializeAnimation = function (animation) {
  17482. var serializationObject = {};
  17483. serializationObject.name = animation.name;
  17484. serializationObject.property = animation.targetProperty;
  17485. serializationObject.framePerSecond = animation.framePerSecond;
  17486. serializationObject.dataType = animation.dataType;
  17487. serializationObject.loopBehavior = animation.loopMode;
  17488. var dataType = animation.dataType;
  17489. serializationObject.keys = [];
  17490. var keys = animation.getKeys();
  17491. for (var index = 0; index < keys.length; index++) {
  17492. var animationKey = keys[index];
  17493. var key = {};
  17494. key.frame = animationKey.frame;
  17495. switch (dataType) {
  17496. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17497. key.values = [animationKey.value];
  17498. break;
  17499. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17500. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17501. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17502. key.values = animationKey.value.asArray();
  17503. break;
  17504. }
  17505. serializationObject.keys.push(key);
  17506. }
  17507. return serializationObject;
  17508. };
  17509. var serializeMultiMaterial = function (material) {
  17510. var serializationObject = {};
  17511. serializationObject.name = material.name;
  17512. serializationObject.id = material.id;
  17513. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17514. serializationObject.materials = [];
  17515. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17516. var subMat = material.subMaterials[matIndex];
  17517. if (subMat) {
  17518. serializationObject.materials.push(subMat.id);
  17519. }
  17520. else {
  17521. serializationObject.materials.push(null);
  17522. }
  17523. }
  17524. return serializationObject;
  17525. };
  17526. var serializeMaterial = function (material) {
  17527. var serializationObject = {};
  17528. serializationObject.name = material.name;
  17529. serializationObject.ambient = material.ambientColor.asArray();
  17530. serializationObject.diffuse = material.diffuseColor.asArray();
  17531. serializationObject.specular = material.specularColor.asArray();
  17532. serializationObject.specularPower = material.specularPower;
  17533. serializationObject.emissive = material.emissiveColor.asArray();
  17534. serializationObject.alpha = material.alpha;
  17535. serializationObject.id = material.id;
  17536. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17537. serializationObject.backFaceCulling = material.backFaceCulling;
  17538. if (material.diffuseTexture) {
  17539. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17540. }
  17541. if (material.diffuseFresnelParameters) {
  17542. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17543. }
  17544. if (material.ambientTexture) {
  17545. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17546. }
  17547. if (material.opacityTexture) {
  17548. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17549. }
  17550. if (material.opacityFresnelParameters) {
  17551. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17552. }
  17553. if (material.reflectionTexture) {
  17554. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17555. }
  17556. if (material.reflectionFresnelParameters) {
  17557. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17558. }
  17559. if (material.emissiveTexture) {
  17560. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17561. }
  17562. if (material.emissiveFresnelParameters) {
  17563. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17564. }
  17565. if (material.specularTexture) {
  17566. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17567. }
  17568. if (material.bumpTexture) {
  17569. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17570. }
  17571. return serializationObject;
  17572. };
  17573. var serializeTexture = function (texture) {
  17574. var serializationObject = {};
  17575. if (!texture.name) {
  17576. return null;
  17577. }
  17578. if (texture instanceof BABYLON.CubeTexture) {
  17579. serializationObject.name = texture.name;
  17580. serializationObject.hasAlpha = texture.hasAlpha;
  17581. serializationObject.level = texture.level;
  17582. serializationObject.coordinatesMode = texture.coordinatesMode;
  17583. return serializationObject;
  17584. }
  17585. if (texture instanceof BABYLON.MirrorTexture) {
  17586. var mirrorTexture = texture;
  17587. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17588. serializationObject.renderList = [];
  17589. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17590. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17591. }
  17592. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17593. }
  17594. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17595. var renderTargetTexture = texture;
  17596. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17597. serializationObject.renderList = [];
  17598. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17599. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17600. }
  17601. }
  17602. var regularTexture = texture;
  17603. serializationObject.name = texture.name;
  17604. serializationObject.hasAlpha = texture.hasAlpha;
  17605. serializationObject.level = texture.level;
  17606. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17607. serializationObject.coordinatesMode = texture.coordinatesMode;
  17608. serializationObject.uOffset = regularTexture.uOffset;
  17609. serializationObject.vOffset = regularTexture.vOffset;
  17610. serializationObject.uScale = regularTexture.uScale;
  17611. serializationObject.vScale = regularTexture.vScale;
  17612. serializationObject.uAng = regularTexture.uAng;
  17613. serializationObject.vAng = regularTexture.vAng;
  17614. serializationObject.wAng = regularTexture.wAng;
  17615. serializationObject.wrapU = texture.wrapU;
  17616. serializationObject.wrapV = texture.wrapV;
  17617. // Animations
  17618. appendAnimations(texture, serializationObject);
  17619. return serializationObject;
  17620. };
  17621. var serializeSkeleton = function (skeleton) {
  17622. var serializationObject = {};
  17623. serializationObject.name = skeleton.name;
  17624. serializationObject.id = skeleton.id;
  17625. serializationObject.bones = [];
  17626. for (var index = 0; index < skeleton.bones.length; index++) {
  17627. var bone = skeleton.bones[index];
  17628. var serializedBone = {
  17629. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17630. name: bone.name,
  17631. matrix: bone.getLocalMatrix().toArray()
  17632. };
  17633. serializationObject.bones.push(serializedBone);
  17634. if (bone.animations && bone.animations.length > 0) {
  17635. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17636. }
  17637. }
  17638. return serializationObject;
  17639. };
  17640. var serializeParticleSystem = function (particleSystem) {
  17641. var serializationObject = {};
  17642. serializationObject.emitterId = particleSystem.emitter.id;
  17643. serializationObject.capacity = particleSystem.getCapacity();
  17644. if (particleSystem.particleTexture) {
  17645. serializationObject.textureName = particleSystem.particleTexture.name;
  17646. }
  17647. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17648. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17649. serializationObject.minSize = particleSystem.minSize;
  17650. serializationObject.maxSize = particleSystem.maxSize;
  17651. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17652. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17653. serializationObject.emitRate = particleSystem.emitRate;
  17654. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17655. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17656. serializationObject.gravity = particleSystem.gravity.asArray();
  17657. serializationObject.direction1 = particleSystem.direction1.asArray();
  17658. serializationObject.direction2 = particleSystem.direction2.asArray();
  17659. serializationObject.color1 = particleSystem.color1.asArray();
  17660. serializationObject.color2 = particleSystem.color2.asArray();
  17661. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17662. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17663. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17664. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17665. serializationObject.blendMode = particleSystem.blendMode;
  17666. return serializationObject;
  17667. };
  17668. var serializeLensFlareSystem = function (lensFlareSystem) {
  17669. var serializationObject = {};
  17670. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17671. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17672. serializationObject.flares = [];
  17673. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17674. var flare = lensFlareSystem.lensFlares[index];
  17675. serializationObject.flares.push({
  17676. size: flare.size,
  17677. position: flare.position,
  17678. color: flare.color.asArray(),
  17679. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17680. });
  17681. }
  17682. return serializationObject;
  17683. };
  17684. var serializeShadowGenerator = function (light) {
  17685. var serializationObject = {};
  17686. var shadowGenerator = light.getShadowGenerator();
  17687. serializationObject.lightId = light.id;
  17688. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17689. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17690. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17691. serializationObject.renderList = [];
  17692. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17693. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17694. serializationObject.renderList.push(mesh.id);
  17695. }
  17696. return serializationObject;
  17697. };
  17698. var serializedGeometries = [];
  17699. var serializeGeometry = function (geometry, serializationGeometries) {
  17700. if (serializedGeometries[geometry.id]) {
  17701. return;
  17702. }
  17703. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17704. serializationGeometries.boxes.push(serializeBox(geometry));
  17705. }
  17706. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17707. serializationGeometries.spheres.push(serializeSphere(geometry));
  17708. }
  17709. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17710. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17711. }
  17712. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17713. serializationGeometries.toruses.push(serializeTorus(geometry));
  17714. }
  17715. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17716. serializationGeometries.grounds.push(serializeGround(geometry));
  17717. }
  17718. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17719. serializationGeometries.planes.push(serializePlane(geometry));
  17720. }
  17721. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17722. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17723. }
  17724. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17725. throw new Error("Unknow primitive type");
  17726. }
  17727. else {
  17728. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17729. }
  17730. serializedGeometries[geometry.id] = true;
  17731. };
  17732. var serializeGeometryBase = function (geometry) {
  17733. var serializationObject = {};
  17734. serializationObject.id = geometry.id;
  17735. if (BABYLON.Tags.HasTags(geometry)) {
  17736. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17737. }
  17738. return serializationObject;
  17739. };
  17740. var serializeVertexData = function (vertexData) {
  17741. var serializationObject = serializeGeometryBase(vertexData);
  17742. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17743. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17744. }
  17745. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17746. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17747. }
  17748. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17749. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17750. }
  17751. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17752. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17753. }
  17754. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17755. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17756. }
  17757. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17758. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17759. serializationObject.matricesIndices._isExpanded = true;
  17760. }
  17761. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17762. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17763. }
  17764. serializationObject.indices = vertexData.getIndices();
  17765. return serializationObject;
  17766. };
  17767. var serializePrimitive = function (primitive) {
  17768. var serializationObject = serializeGeometryBase(primitive);
  17769. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17770. return serializationObject;
  17771. };
  17772. var serializeBox = function (box) {
  17773. var serializationObject = serializePrimitive(box);
  17774. serializationObject.size = box.size;
  17775. return serializationObject;
  17776. };
  17777. var serializeSphere = function (sphere) {
  17778. var serializationObject = serializePrimitive(sphere);
  17779. serializationObject.segments = sphere.segments;
  17780. serializationObject.diameter = sphere.diameter;
  17781. return serializationObject;
  17782. };
  17783. var serializeCylinder = function (cylinder) {
  17784. var serializationObject = serializePrimitive(cylinder);
  17785. serializationObject.height = cylinder.height;
  17786. serializationObject.diameterTop = cylinder.diameterTop;
  17787. serializationObject.diameterBottom = cylinder.diameterBottom;
  17788. serializationObject.tessellation = cylinder.tessellation;
  17789. return serializationObject;
  17790. };
  17791. var serializeTorus = function (torus) {
  17792. var serializationObject = serializePrimitive(torus);
  17793. serializationObject.diameter = torus.diameter;
  17794. serializationObject.thickness = torus.thickness;
  17795. serializationObject.tessellation = torus.tessellation;
  17796. return serializationObject;
  17797. };
  17798. var serializeGround = function (ground) {
  17799. var serializationObject = serializePrimitive(ground);
  17800. serializationObject.width = ground.width;
  17801. serializationObject.height = ground.height;
  17802. serializationObject.subdivisions = ground.subdivisions;
  17803. return serializationObject;
  17804. };
  17805. var serializePlane = function (plane) {
  17806. var serializationObject = serializePrimitive(plane);
  17807. serializationObject.size = plane.size;
  17808. return serializationObject;
  17809. };
  17810. var serializeTorusKnot = function (torusKnot) {
  17811. var serializationObject = serializePrimitive(torusKnot);
  17812. serializationObject.radius = torusKnot.radius;
  17813. serializationObject.tube = torusKnot.tube;
  17814. serializationObject.radialSegments = torusKnot.radialSegments;
  17815. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17816. serializationObject.p = torusKnot.p;
  17817. serializationObject.q = torusKnot.q;
  17818. return serializationObject;
  17819. };
  17820. var serializeMesh = function (mesh, serializationScene) {
  17821. var serializationObject = {};
  17822. serializationObject.name = mesh.name;
  17823. serializationObject.id = mesh.id;
  17824. if (BABYLON.Tags.HasTags(mesh)) {
  17825. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17826. }
  17827. serializationObject.position = mesh.position.asArray();
  17828. if (mesh.rotationQuaternion) {
  17829. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17830. }
  17831. else if (mesh.rotation) {
  17832. serializationObject.rotation = mesh.rotation.asArray();
  17833. }
  17834. serializationObject.scaling = mesh.scaling.asArray();
  17835. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17836. serializationObject.isEnabled = mesh.isEnabled();
  17837. serializationObject.isVisible = mesh.isVisible;
  17838. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17839. serializationObject.pickable = mesh.isPickable;
  17840. serializationObject.receiveShadows = mesh.receiveShadows;
  17841. serializationObject.billboardMode = mesh.billboardMode;
  17842. serializationObject.visibility = mesh.visibility;
  17843. serializationObject.checkCollisions = mesh.checkCollisions;
  17844. // Parent
  17845. if (mesh.parent) {
  17846. serializationObject.parentId = mesh.parent.id;
  17847. }
  17848. // Geometry
  17849. var geometry = mesh._geometry;
  17850. if (geometry) {
  17851. var geometryId = geometry.id;
  17852. serializationObject.geometryId = geometryId;
  17853. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17854. // 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
  17855. serializeGeometry(geometry, serializationScene.geometries);
  17856. }
  17857. // SubMeshes
  17858. serializationObject.subMeshes = [];
  17859. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17860. var subMesh = mesh.subMeshes[subIndex];
  17861. serializationObject.subMeshes.push({
  17862. materialIndex: subMesh.materialIndex,
  17863. verticesStart: subMesh.verticesStart,
  17864. verticesCount: subMesh.verticesCount,
  17865. indexStart: subMesh.indexStart,
  17866. indexCount: subMesh.indexCount
  17867. });
  17868. }
  17869. }
  17870. // Material
  17871. if (mesh.material) {
  17872. serializationObject.materialId = mesh.material.id;
  17873. }
  17874. else {
  17875. mesh.material = null;
  17876. }
  17877. // Skeleton
  17878. if (mesh.skeleton) {
  17879. serializationObject.skeletonId = mesh.skeleton.id;
  17880. }
  17881. // Physics
  17882. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17883. serializationObject.physicsMass = mesh.getPhysicsMass();
  17884. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17885. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17886. switch (mesh.getPhysicsImpostor()) {
  17887. case BABYLON.PhysicsEngine.BoxImpostor:
  17888. serializationObject.physicsImpostor = 1;
  17889. break;
  17890. case BABYLON.PhysicsEngine.SphereImpostor:
  17891. serializationObject.physicsImpostor = 2;
  17892. break;
  17893. }
  17894. }
  17895. // Instances
  17896. serializationObject.instances = [];
  17897. for (var index = 0; index < mesh.instances.length; index++) {
  17898. var instance = mesh.instances[index];
  17899. var serializationInstance = {
  17900. name: instance.name,
  17901. position: instance.position,
  17902. rotation: instance.rotation,
  17903. rotationQuaternion: instance.rotationQuaternion,
  17904. scaling: instance.scaling
  17905. };
  17906. serializationObject.instances.push(serializationInstance);
  17907. // Animations
  17908. appendAnimations(instance, serializationInstance);
  17909. }
  17910. // Animations
  17911. appendAnimations(mesh, serializationObject);
  17912. // Layer mask
  17913. serializationObject.layerMask = mesh.layerMask;
  17914. return serializationObject;
  17915. };
  17916. var SceneSerializer = (function () {
  17917. function SceneSerializer() {
  17918. }
  17919. SceneSerializer.Serialize = function (scene) {
  17920. var serializationObject = {};
  17921. // Scene
  17922. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17923. serializationObject.autoClear = scene.autoClear;
  17924. serializationObject.clearColor = scene.clearColor.asArray();
  17925. serializationObject.ambientColor = scene.ambientColor.asArray();
  17926. serializationObject.gravity = scene.gravity.asArray();
  17927. // Fog
  17928. if (scene.fogMode && scene.fogMode !== 0) {
  17929. serializationObject.fogMode = scene.fogMode;
  17930. serializationObject.fogColor = scene.fogColor.asArray();
  17931. serializationObject.fogStart = scene.fogStart;
  17932. serializationObject.fogEnd = scene.fogEnd;
  17933. serializationObject.fogDensity = scene.fogDensity;
  17934. }
  17935. // Lights
  17936. serializationObject.lights = [];
  17937. for (var index = 0; index < scene.lights.length; index++) {
  17938. var light = scene.lights[index];
  17939. serializationObject.lights.push(serializeLight(light));
  17940. }
  17941. // Cameras
  17942. serializationObject.cameras = [];
  17943. for (index = 0; index < scene.cameras.length; index++) {
  17944. var camera = scene.cameras[index];
  17945. if (camera instanceof BABYLON.FreeCamera) {
  17946. serializationObject.cameras.push(serializeCamera(camera));
  17947. }
  17948. }
  17949. if (scene.activeCamera) {
  17950. serializationObject.activeCameraID = scene.activeCamera.id;
  17951. }
  17952. // Materials
  17953. serializationObject.materials = [];
  17954. serializationObject.multiMaterials = [];
  17955. for (index = 0; index < scene.materials.length; index++) {
  17956. var material = scene.materials[index];
  17957. if (material instanceof BABYLON.StandardMaterial) {
  17958. serializationObject.materials.push(serializeMaterial(material));
  17959. }
  17960. else if (material instanceof BABYLON.MultiMaterial) {
  17961. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17962. }
  17963. }
  17964. // Skeletons
  17965. serializationObject.skeletons = [];
  17966. for (index = 0; index < scene.skeletons.length; index++) {
  17967. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17968. }
  17969. // Geometries
  17970. serializationObject.geometries = {};
  17971. serializationObject.geometries.boxes = [];
  17972. serializationObject.geometries.spheres = [];
  17973. serializationObject.geometries.cylinders = [];
  17974. serializationObject.geometries.toruses = [];
  17975. serializationObject.geometries.grounds = [];
  17976. serializationObject.geometries.planes = [];
  17977. serializationObject.geometries.torusKnots = [];
  17978. serializationObject.geometries.vertexData = [];
  17979. serializedGeometries = [];
  17980. var geometries = scene.getGeometries();
  17981. for (var index = 0; index < geometries.length; index++) {
  17982. var geometry = geometries[index];
  17983. if (geometry.isReady()) {
  17984. serializeGeometry(geometry, serializationObject.geometries);
  17985. }
  17986. }
  17987. // Meshes
  17988. serializationObject.meshes = [];
  17989. for (index = 0; index < scene.meshes.length; index++) {
  17990. var abstractMesh = scene.meshes[index];
  17991. if (abstractMesh instanceof BABYLON.Mesh) {
  17992. var mesh = abstractMesh;
  17993. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17994. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17995. }
  17996. }
  17997. }
  17998. // Particles Systems
  17999. serializationObject.particleSystems = [];
  18000. for (index = 0; index < scene.particleSystems.length; index++) {
  18001. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18002. }
  18003. // Lens flares
  18004. serializationObject.lensFlareSystems = [];
  18005. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18006. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18007. }
  18008. // Shadows
  18009. serializationObject.shadowGenerators = [];
  18010. for (index = 0; index < scene.lights.length; index++) {
  18011. light = scene.lights[index];
  18012. if (light.getShadowGenerator()) {
  18013. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18014. }
  18015. }
  18016. return serializationObject;
  18017. };
  18018. return SceneSerializer;
  18019. })();
  18020. BABYLON.SceneSerializer = SceneSerializer;
  18021. })(BABYLON || (BABYLON = {}));
  18022. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18023. (function (BABYLON) {
  18024. var SceneLoader = (function () {
  18025. function SceneLoader() {
  18026. }
  18027. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18028. get: function () {
  18029. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18030. },
  18031. set: function (value) {
  18032. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18033. },
  18034. enumerable: true,
  18035. configurable: true
  18036. });
  18037. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18038. get: function () {
  18039. return SceneLoader._ShowLoadingScreen;
  18040. },
  18041. set: function (value) {
  18042. SceneLoader._ShowLoadingScreen = value;
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18048. var dotPosition = sceneFilename.lastIndexOf(".");
  18049. var queryStringPosition = sceneFilename.indexOf("?");
  18050. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18051. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18052. var plugin = this._registeredPlugins[index];
  18053. if (plugin.extensions.indexOf(extension) !== -1) {
  18054. return plugin;
  18055. }
  18056. }
  18057. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18058. };
  18059. // Public functions
  18060. SceneLoader.RegisterPlugin = function (plugin) {
  18061. plugin.extensions = plugin.extensions.toLowerCase();
  18062. SceneLoader._registeredPlugins.push(plugin);
  18063. };
  18064. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18065. var manifestChecked = function (success) {
  18066. scene.database = database;
  18067. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18068. var importMeshFromData = function (data) {
  18069. var meshes = [];
  18070. var particleSystems = [];
  18071. var skeletons = [];
  18072. try {
  18073. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18074. if (onerror) {
  18075. onerror(scene, 'unable to load the scene');
  18076. }
  18077. return;
  18078. }
  18079. }
  18080. catch (e) {
  18081. if (onerror) {
  18082. onerror(scene, e);
  18083. }
  18084. return;
  18085. }
  18086. if (onsuccess) {
  18087. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18088. onsuccess(meshes, particleSystems, skeletons);
  18089. }
  18090. };
  18091. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18092. // Direct load
  18093. importMeshFromData(sceneFilename.substr(5));
  18094. return;
  18095. }
  18096. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18097. importMeshFromData(data);
  18098. }, progressCallBack, database);
  18099. };
  18100. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18101. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18102. };
  18103. /**
  18104. * Load a scene
  18105. * @param rootUrl a string that defines the root url for scene and resources
  18106. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18107. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18108. */
  18109. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18110. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18111. };
  18112. /**
  18113. * Append a scene
  18114. * @param rootUrl a string that defines the root url for scene and resources
  18115. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18116. * @param scene is the instance of BABYLON.Scene to append to
  18117. */
  18118. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18119. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18120. var database;
  18121. if (SceneLoader.ShowLoadingScreen) {
  18122. scene.getEngine().displayLoadingUI();
  18123. }
  18124. var loadSceneFromData = function (data) {
  18125. scene.database = database;
  18126. if (!plugin.load(scene, data, rootUrl)) {
  18127. if (onerror) {
  18128. onerror(scene);
  18129. }
  18130. scene.getEngine().hideLoadingUI();
  18131. return;
  18132. }
  18133. if (onsuccess) {
  18134. onsuccess(scene);
  18135. }
  18136. if (SceneLoader.ShowLoadingScreen) {
  18137. scene.executeWhenReady(function () {
  18138. scene.getEngine().hideLoadingUI();
  18139. });
  18140. }
  18141. };
  18142. var manifestChecked = function (success) {
  18143. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18144. };
  18145. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18146. // Direct load
  18147. loadSceneFromData(sceneFilename.substr(5));
  18148. return;
  18149. }
  18150. if (rootUrl.indexOf("file:") === -1) {
  18151. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18152. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18153. }
  18154. else {
  18155. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18156. }
  18157. };
  18158. // Flags
  18159. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18160. SceneLoader._ShowLoadingScreen = true;
  18161. // Members
  18162. SceneLoader._registeredPlugins = new Array();
  18163. return SceneLoader;
  18164. })();
  18165. BABYLON.SceneLoader = SceneLoader;
  18166. ;
  18167. })(BABYLON || (BABYLON = {}));
  18168. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18169. (function (BABYLON) {
  18170. var Internals;
  18171. (function (Internals) {
  18172. var checkColors4 = function (colors, count) {
  18173. // Check if color3 was used
  18174. if (colors.length === count * 3) {
  18175. var colors4 = [];
  18176. for (var index = 0; index < colors.length; index += 3) {
  18177. var newIndex = (index / 3) * 4;
  18178. colors4[newIndex] = colors[index];
  18179. colors4[newIndex + 1] = colors[index + 1];
  18180. colors4[newIndex + 2] = colors[index + 2];
  18181. colors4[newIndex + 3] = 1.0;
  18182. }
  18183. return colors4;
  18184. }
  18185. return colors;
  18186. };
  18187. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18188. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18189. texture.name = parsedTexture.name;
  18190. texture.hasAlpha = parsedTexture.hasAlpha;
  18191. texture.level = parsedTexture.level;
  18192. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18193. return texture;
  18194. };
  18195. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18196. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18197. return null;
  18198. }
  18199. if (parsedTexture.isCube) {
  18200. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18201. }
  18202. var texture;
  18203. if (parsedTexture.mirrorPlane) {
  18204. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18205. texture._waitingRenderList = parsedTexture.renderList;
  18206. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18207. }
  18208. else if (parsedTexture.isRenderTarget) {
  18209. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18210. texture._waitingRenderList = parsedTexture.renderList;
  18211. }
  18212. else {
  18213. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18214. }
  18215. texture.name = parsedTexture.name;
  18216. texture.hasAlpha = parsedTexture.hasAlpha;
  18217. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18218. texture.level = parsedTexture.level;
  18219. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18220. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18221. texture.uOffset = parsedTexture.uOffset;
  18222. texture.vOffset = parsedTexture.vOffset;
  18223. texture.uScale = parsedTexture.uScale;
  18224. texture.vScale = parsedTexture.vScale;
  18225. texture.uAng = parsedTexture.uAng;
  18226. texture.vAng = parsedTexture.vAng;
  18227. texture.wAng = parsedTexture.wAng;
  18228. texture.wrapU = parsedTexture.wrapU;
  18229. texture.wrapV = parsedTexture.wrapV;
  18230. // Animations
  18231. if (parsedTexture.animations) {
  18232. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18233. var parsedAnimation = parsedTexture.animations[animationIndex];
  18234. texture.animations.push(parseAnimation(parsedAnimation));
  18235. }
  18236. }
  18237. return texture;
  18238. };
  18239. var parseSkeleton = function (parsedSkeleton, scene) {
  18240. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18241. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18242. var parsedBone = parsedSkeleton.bones[index];
  18243. var parentBone = null;
  18244. if (parsedBone.parentBoneIndex > -1) {
  18245. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18246. }
  18247. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18248. if (parsedBone.animation) {
  18249. bone.animations.push(parseAnimation(parsedBone.animation));
  18250. }
  18251. }
  18252. return skeleton;
  18253. };
  18254. var parseFresnelParameters = function (parsedFresnelParameters) {
  18255. var fresnelParameters = new BABYLON.FresnelParameters();
  18256. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18257. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18258. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18259. fresnelParameters.bias = parsedFresnelParameters.bias;
  18260. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18261. return fresnelParameters;
  18262. };
  18263. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18264. var material;
  18265. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18266. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18267. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18268. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18269. material.specularPower = parsedMaterial.specularPower;
  18270. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18271. material.alpha = parsedMaterial.alpha;
  18272. material.id = parsedMaterial.id;
  18273. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18274. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18275. material.wireframe = parsedMaterial.wireframe;
  18276. if (parsedMaterial.diffuseTexture) {
  18277. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18278. }
  18279. if (parsedMaterial.diffuseFresnelParameters) {
  18280. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18281. }
  18282. if (parsedMaterial.ambientTexture) {
  18283. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18284. }
  18285. if (parsedMaterial.opacityTexture) {
  18286. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18287. }
  18288. if (parsedMaterial.opacityFresnelParameters) {
  18289. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18290. }
  18291. if (parsedMaterial.reflectionTexture) {
  18292. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18293. }
  18294. if (parsedMaterial.reflectionFresnelParameters) {
  18295. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18296. }
  18297. if (parsedMaterial.emissiveTexture) {
  18298. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18299. }
  18300. if (parsedMaterial.emissiveFresnelParameters) {
  18301. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18302. }
  18303. if (parsedMaterial.specularTexture) {
  18304. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18305. }
  18306. if (parsedMaterial.bumpTexture) {
  18307. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18308. }
  18309. return material;
  18310. };
  18311. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18312. for (var index = 0; index < parsedData.materials.length; index++) {
  18313. var parsedMaterial = parsedData.materials[index];
  18314. if (parsedMaterial.id === id) {
  18315. return parseMaterial(parsedMaterial, scene, rootUrl);
  18316. }
  18317. }
  18318. return null;
  18319. };
  18320. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18321. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18322. multiMaterial.id = parsedMultiMaterial.id;
  18323. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18324. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18325. var subMatId = parsedMultiMaterial.materials[matIndex];
  18326. if (subMatId) {
  18327. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18328. }
  18329. else {
  18330. multiMaterial.subMaterials.push(null);
  18331. }
  18332. }
  18333. return multiMaterial;
  18334. };
  18335. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18336. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18337. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18338. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18339. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18340. var parsedFlare = parsedLensFlareSystem.flares[index];
  18341. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18342. }
  18343. return lensFlareSystem;
  18344. };
  18345. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18346. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18347. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18348. if (parsedParticleSystem.textureName) {
  18349. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18350. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18351. }
  18352. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18353. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18354. particleSystem.minSize = parsedParticleSystem.minSize;
  18355. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18356. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18357. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18358. particleSystem.emitter = emitter;
  18359. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18360. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18361. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18362. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18363. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18364. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18365. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18366. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18367. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18368. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18369. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18370. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18371. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18372. particleSystem.start();
  18373. return particleSystem;
  18374. };
  18375. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18376. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18377. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18378. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18379. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18380. shadowGenerator.getShadowMap().renderList.push(mesh);
  18381. }
  18382. if (parsedShadowGenerator.usePoissonSampling) {
  18383. shadowGenerator.usePoissonSampling = true;
  18384. }
  18385. else {
  18386. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18387. }
  18388. return shadowGenerator;
  18389. };
  18390. var parseAnimation = function (parsedAnimation) {
  18391. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18392. var dataType = parsedAnimation.dataType;
  18393. var keys = [];
  18394. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18395. var key = parsedAnimation.keys[index];
  18396. var data;
  18397. switch (dataType) {
  18398. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18399. data = key.values[0];
  18400. break;
  18401. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18402. data = BABYLON.Quaternion.FromArray(key.values);
  18403. break;
  18404. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18405. data = BABYLON.Matrix.FromArray(key.values);
  18406. break;
  18407. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18408. default:
  18409. data = BABYLON.Vector3.FromArray(key.values);
  18410. break;
  18411. }
  18412. keys.push({
  18413. frame: key.frame,
  18414. value: data
  18415. });
  18416. }
  18417. animation.setKeys(keys);
  18418. return animation;
  18419. };
  18420. var parseLight = function (parsedLight, scene) {
  18421. var light;
  18422. switch (parsedLight.type) {
  18423. case 0:
  18424. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18425. break;
  18426. case 1:
  18427. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18428. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18429. break;
  18430. case 2:
  18431. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18432. break;
  18433. case 3:
  18434. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18435. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18436. break;
  18437. }
  18438. light.id = parsedLight.id;
  18439. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18440. if (parsedLight.intensity !== undefined) {
  18441. light.intensity = parsedLight.intensity;
  18442. }
  18443. if (parsedLight.range) {
  18444. light.range = parsedLight.range;
  18445. }
  18446. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18447. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18448. if (parsedLight.excludedMeshesIds) {
  18449. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18450. }
  18451. // Parent
  18452. if (parsedLight.parentId) {
  18453. light._waitingParentId = parsedLight.parentId;
  18454. }
  18455. if (parsedLight.includedOnlyMeshesIds) {
  18456. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18457. }
  18458. // Animations
  18459. if (parsedLight.animations) {
  18460. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18461. var parsedAnimation = parsedLight.animations[animationIndex];
  18462. light.animations.push(parseAnimation(parsedAnimation));
  18463. }
  18464. }
  18465. if (parsedLight.autoAnimate) {
  18466. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18467. }
  18468. };
  18469. var parseCamera = function (parsedCamera, scene) {
  18470. var camera;
  18471. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18472. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18473. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18474. var alpha = parsedCamera.alpha;
  18475. var beta = parsedCamera.beta;
  18476. var radius = parsedCamera.radius;
  18477. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18478. var eye_space = parsedCamera.eye_space;
  18479. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18480. }
  18481. else {
  18482. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18483. }
  18484. }
  18485. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18486. eye_space = parsedCamera.eye_space;
  18487. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18488. }
  18489. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18490. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18491. }
  18492. else if (parsedCamera.type === "FollowCamera") {
  18493. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18494. camera.heightOffset = parsedCamera.heightOffset;
  18495. camera.radius = parsedCamera.radius;
  18496. camera.rotationOffset = parsedCamera.rotationOffset;
  18497. if (lockedTargetMesh)
  18498. camera.target = lockedTargetMesh;
  18499. }
  18500. else if (parsedCamera.type === "GamepadCamera") {
  18501. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18502. }
  18503. else if (parsedCamera.type === "OculusCamera") {
  18504. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18505. }
  18506. else if (parsedCamera.type === "OculusGamepadCamera") {
  18507. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18508. }
  18509. else if (parsedCamera.type === "TouchCamera") {
  18510. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18511. }
  18512. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18513. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18514. }
  18515. else if (parsedCamera.type === "WebVRCamera") {
  18516. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18517. }
  18518. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18519. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18520. }
  18521. else {
  18522. // Free Camera is the default value
  18523. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18524. }
  18525. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18526. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18527. camera.lockedTarget = lockedTargetMesh;
  18528. }
  18529. camera.id = parsedCamera.id;
  18530. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18531. // Parent
  18532. if (parsedCamera.parentId) {
  18533. camera._waitingParentId = parsedCamera.parentId;
  18534. }
  18535. // Target
  18536. if (parsedCamera.target) {
  18537. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18538. }
  18539. else {
  18540. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18541. }
  18542. camera.fov = parsedCamera.fov;
  18543. camera.minZ = parsedCamera.minZ;
  18544. camera.maxZ = parsedCamera.maxZ;
  18545. camera.speed = parsedCamera.speed;
  18546. camera.inertia = parsedCamera.inertia;
  18547. camera.checkCollisions = parsedCamera.checkCollisions;
  18548. camera.applyGravity = parsedCamera.applyGravity;
  18549. if (parsedCamera.ellipsoid) {
  18550. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18551. }
  18552. // Animations
  18553. if (parsedCamera.animations) {
  18554. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18555. var parsedAnimation = parsedCamera.animations[animationIndex];
  18556. camera.animations.push(parseAnimation(parsedAnimation));
  18557. }
  18558. }
  18559. if (parsedCamera.autoAnimate) {
  18560. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18561. }
  18562. // Layer Mask
  18563. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18564. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18565. }
  18566. else {
  18567. camera.layerMask = 0xFFFFFFFF;
  18568. }
  18569. return camera;
  18570. };
  18571. var parseGeometry = function (parsedGeometry, scene) {
  18572. var id = parsedGeometry.id;
  18573. return scene.getGeometryByID(id);
  18574. };
  18575. var parseBox = function (parsedBox, scene) {
  18576. if (parseGeometry(parsedBox, scene)) {
  18577. return null; // null since geometry could be something else than a box...
  18578. }
  18579. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18580. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18581. scene.pushGeometry(box, true);
  18582. return box;
  18583. };
  18584. var parseSphere = function (parsedSphere, scene) {
  18585. if (parseGeometry(parsedSphere, scene)) {
  18586. return null; // null since geometry could be something else than a sphere...
  18587. }
  18588. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18589. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18590. scene.pushGeometry(sphere, true);
  18591. return sphere;
  18592. };
  18593. var parseCylinder = function (parsedCylinder, scene) {
  18594. if (parseGeometry(parsedCylinder, scene)) {
  18595. return null; // null since geometry could be something else than a cylinder...
  18596. }
  18597. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18598. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18599. scene.pushGeometry(cylinder, true);
  18600. return cylinder;
  18601. };
  18602. var parseTorus = function (parsedTorus, scene) {
  18603. if (parseGeometry(parsedTorus, scene)) {
  18604. return null; // null since geometry could be something else than a torus...
  18605. }
  18606. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18607. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18608. scene.pushGeometry(torus, true);
  18609. return torus;
  18610. };
  18611. var parseGround = function (parsedGround, scene) {
  18612. if (parseGeometry(parsedGround, scene)) {
  18613. return null; // null since geometry could be something else than a ground...
  18614. }
  18615. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18616. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18617. scene.pushGeometry(ground, true);
  18618. return ground;
  18619. };
  18620. var parsePlane = function (parsedPlane, scene) {
  18621. if (parseGeometry(parsedPlane, scene)) {
  18622. return null; // null since geometry could be something else than a plane...
  18623. }
  18624. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18625. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18626. scene.pushGeometry(plane, true);
  18627. return plane;
  18628. };
  18629. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18630. if (parseGeometry(parsedTorusKnot, scene)) {
  18631. return null; // null since geometry could be something else than a torusKnot...
  18632. }
  18633. 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);
  18634. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18635. scene.pushGeometry(torusKnot, true);
  18636. return torusKnot;
  18637. };
  18638. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18639. if (parseGeometry(parsedVertexData, scene)) {
  18640. return null; // null since geometry could be a primitive
  18641. }
  18642. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18643. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18644. if (parsedVertexData.delayLoadingFile) {
  18645. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18646. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18647. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18648. geometry._delayInfo = [];
  18649. if (parsedVertexData.hasUVs) {
  18650. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18651. }
  18652. if (parsedVertexData.hasUVs2) {
  18653. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18654. }
  18655. if (parsedVertexData.hasColors) {
  18656. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18657. }
  18658. if (parsedVertexData.hasMatricesIndices) {
  18659. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18660. }
  18661. if (parsedVertexData.hasMatricesWeights) {
  18662. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18663. }
  18664. geometry._delayLoadingFunction = importVertexData;
  18665. }
  18666. else {
  18667. importVertexData(parsedVertexData, geometry);
  18668. }
  18669. scene.pushGeometry(geometry, true);
  18670. return geometry;
  18671. };
  18672. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18673. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18674. mesh.id = parsedMesh.id;
  18675. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18676. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18677. if (parsedMesh.rotationQuaternion) {
  18678. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18679. }
  18680. else if (parsedMesh.rotation) {
  18681. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18682. }
  18683. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18684. if (parsedMesh.localMatrix) {
  18685. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18686. }
  18687. else if (parsedMesh.pivotMatrix) {
  18688. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18689. }
  18690. mesh.setEnabled(parsedMesh.isEnabled);
  18691. mesh.isVisible = parsedMesh.isVisible;
  18692. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18693. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18694. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18695. if (parsedMesh.applyFog !== undefined) {
  18696. mesh.applyFog = parsedMesh.applyFog;
  18697. }
  18698. if (parsedMesh.pickable !== undefined) {
  18699. mesh.isPickable = parsedMesh.pickable;
  18700. }
  18701. if (parsedMesh.alphaIndex !== undefined) {
  18702. mesh.alphaIndex = parsedMesh.alphaIndex;
  18703. }
  18704. mesh.receiveShadows = parsedMesh.receiveShadows;
  18705. mesh.billboardMode = parsedMesh.billboardMode;
  18706. if (parsedMesh.visibility !== undefined) {
  18707. mesh.visibility = parsedMesh.visibility;
  18708. }
  18709. mesh.checkCollisions = parsedMesh.checkCollisions;
  18710. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18711. // Parent
  18712. if (parsedMesh.parentId) {
  18713. mesh._waitingParentId = parsedMesh.parentId;
  18714. }
  18715. // Actions
  18716. if (parsedMesh.actions !== undefined) {
  18717. mesh._waitingActions = parsedMesh.actions;
  18718. }
  18719. // Geometry
  18720. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18721. if (parsedMesh.delayLoadingFile) {
  18722. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18723. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18724. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18725. if (parsedMesh._binaryInfo) {
  18726. mesh._binaryInfo = parsedMesh._binaryInfo;
  18727. }
  18728. mesh._delayInfo = [];
  18729. if (parsedMesh.hasUVs) {
  18730. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18731. }
  18732. if (parsedMesh.hasUVs2) {
  18733. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18734. }
  18735. if (parsedMesh.hasColors) {
  18736. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18737. }
  18738. if (parsedMesh.hasMatricesIndices) {
  18739. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18740. }
  18741. if (parsedMesh.hasMatricesWeights) {
  18742. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18743. }
  18744. mesh._delayLoadingFunction = importGeometry;
  18745. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18746. mesh._checkDelayState();
  18747. }
  18748. }
  18749. else {
  18750. importGeometry(parsedMesh, mesh);
  18751. }
  18752. // Material
  18753. if (parsedMesh.materialId) {
  18754. mesh.setMaterialByID(parsedMesh.materialId);
  18755. }
  18756. else {
  18757. mesh.material = null;
  18758. }
  18759. // Skeleton
  18760. if (parsedMesh.skeletonId > -1) {
  18761. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18762. }
  18763. // Physics
  18764. if (parsedMesh.physicsImpostor) {
  18765. if (!scene.isPhysicsEnabled()) {
  18766. scene.enablePhysics();
  18767. }
  18768. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18769. }
  18770. // Animations
  18771. if (parsedMesh.animations) {
  18772. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18773. var parsedAnimation = parsedMesh.animations[animationIndex];
  18774. mesh.animations.push(parseAnimation(parsedAnimation));
  18775. }
  18776. }
  18777. if (parsedMesh.autoAnimate) {
  18778. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18779. }
  18780. // Layer Mask
  18781. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18782. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18783. }
  18784. else {
  18785. mesh.layerMask = 0xFFFFFFFF;
  18786. }
  18787. // Instances
  18788. if (parsedMesh.instances) {
  18789. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18790. var parsedInstance = parsedMesh.instances[index];
  18791. var instance = mesh.createInstance(parsedInstance.name);
  18792. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18793. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18794. if (parsedInstance.rotationQuaternion) {
  18795. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18796. }
  18797. else if (parsedInstance.rotation) {
  18798. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18799. }
  18800. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18801. instance.checkCollisions = mesh.checkCollisions;
  18802. if (parsedMesh.animations) {
  18803. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18804. parsedAnimation = parsedMesh.animations[animationIndex];
  18805. instance.animations.push(parseAnimation(parsedAnimation));
  18806. }
  18807. }
  18808. }
  18809. }
  18810. return mesh;
  18811. };
  18812. var parseActions = function (parsedActions, object, scene) {
  18813. var actionManager = new BABYLON.ActionManager(scene);
  18814. if (object === null)
  18815. scene.actionManager = actionManager;
  18816. else
  18817. object.actionManager = actionManager;
  18818. // instanciate a new object
  18819. var instanciate = function (name, params) {
  18820. var newInstance = Object.create(BABYLON[name].prototype);
  18821. newInstance.constructor.apply(newInstance, params);
  18822. return newInstance;
  18823. };
  18824. var parseParameter = function (name, value, target, propertyPath) {
  18825. if (propertyPath === null) {
  18826. // String, boolean or float
  18827. var floatValue = parseFloat(value);
  18828. if (value === "true" || value === "false")
  18829. return value === "true";
  18830. else
  18831. return isNaN(floatValue) ? value : floatValue;
  18832. }
  18833. var effectiveTarget = propertyPath.split(".");
  18834. var values = value.split(",");
  18835. for (var i = 0; i < effectiveTarget.length; i++) {
  18836. target = target[effectiveTarget[i]];
  18837. }
  18838. // Return appropriate value with its type
  18839. if (target instanceof Boolean)
  18840. return values[0] === "true";
  18841. if (target instanceof String)
  18842. return values[0];
  18843. // Parameters with multiple values such as Vector3 etc.
  18844. var split = new Array();
  18845. for (var i = 0; i < values.length; i++)
  18846. split.push(parseFloat(values[i]));
  18847. if (target instanceof BABYLON.Vector3)
  18848. return BABYLON.Vector3.FromArray(split);
  18849. if (target instanceof BABYLON.Vector4)
  18850. return BABYLON.Vector4.FromArray(split);
  18851. if (target instanceof BABYLON.Color3)
  18852. return BABYLON.Color3.FromArray(split);
  18853. if (target instanceof BABYLON.Color4)
  18854. return BABYLON.Color4.FromArray(split);
  18855. return parseFloat(values[0]);
  18856. };
  18857. // traverse graph per trigger
  18858. var traverse = function (parsedAction, trigger, condition, action) {
  18859. var parameters = new Array();
  18860. var target = null;
  18861. var propertyPath = null;
  18862. // Parameters
  18863. if (parsedAction.type === 2)
  18864. parameters.push(actionManager);
  18865. else
  18866. parameters.push(trigger);
  18867. for (var i = 0; i < parsedAction.properties.length; i++) {
  18868. var value = parsedAction.properties[i].value;
  18869. var name = parsedAction.properties[i].name;
  18870. if (name === "target")
  18871. value = target = scene.getNodeByName(value);
  18872. else if (name === "parent")
  18873. value = scene.getNodeByName(value);
  18874. else if (name === "sound")
  18875. value = scene.getSoundByName(value);
  18876. else if (name !== "propertyPath") {
  18877. if (parsedAction.type === 2 && name === "operator")
  18878. value = BABYLON.ValueCondition[value];
  18879. else
  18880. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18881. }
  18882. else {
  18883. propertyPath = value;
  18884. }
  18885. parameters.push(value);
  18886. }
  18887. parameters.push(condition);
  18888. // If interpolate value action
  18889. if (parsedAction.name === "InterpolateValueAction") {
  18890. var param = parameters[parameters.length - 2];
  18891. parameters[parameters.length - 1] = param;
  18892. parameters[parameters.length - 2] = condition;
  18893. }
  18894. // Action or condition(s)
  18895. var newAction = instanciate(parsedAction.name, parameters);
  18896. if (newAction instanceof BABYLON.Condition) {
  18897. condition = newAction;
  18898. newAction = action;
  18899. }
  18900. else {
  18901. condition = null;
  18902. if (action)
  18903. action.then(newAction);
  18904. else
  18905. actionManager.registerAction(newAction);
  18906. }
  18907. for (var i = 0; i < parsedAction.children.length; i++)
  18908. traverse(parsedAction.children[i], trigger, condition, newAction);
  18909. };
  18910. for (var i = 0; i < parsedActions.children.length; i++) {
  18911. var triggerParams;
  18912. var trigger = parsedActions.children[i];
  18913. if (trigger.properties.length > 0) {
  18914. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18915. }
  18916. else
  18917. triggerParams = BABYLON.ActionManager[trigger.name];
  18918. for (var j = 0; j < trigger.children.length; j++)
  18919. traverse(trigger.children[j], triggerParams, null, null);
  18920. }
  18921. };
  18922. var parseSound = function (parsedSound, scene, rootUrl) {
  18923. var soundName = parsedSound.name;
  18924. var soundUrl = rootUrl + soundName;
  18925. var options = {
  18926. autoplay: parsedSound.autoplay,
  18927. loop: parsedSound.loop,
  18928. volume: parsedSound.volume,
  18929. spatialSound: parsedSound.spatialSound,
  18930. maxDistance: parsedSound.maxDistance,
  18931. rolloffFactor: parsedSound.rolloffFactor,
  18932. refDistance: parsedSound.refDistance,
  18933. distanceModel: parsedSound.distanceModel,
  18934. panningModel: parsedSound.panningModel,
  18935. playbackRate: parsedSound.playbackRate
  18936. };
  18937. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18938. scene._removePendingData(newSound);
  18939. }, options);
  18940. scene._addPendingData(newSound);
  18941. if (parsedSound.position) {
  18942. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18943. newSound.setPosition(soundPosition);
  18944. }
  18945. if (parsedSound.isDirectional) {
  18946. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18947. if (parsedSound.localDirectionToMesh) {
  18948. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18949. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18950. }
  18951. }
  18952. if (parsedSound.connectedMeshId) {
  18953. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18954. if (connectedMesh) {
  18955. newSound.attachToMesh(connectedMesh);
  18956. }
  18957. }
  18958. };
  18959. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18960. names = (names instanceof Array) ? names : [names];
  18961. for (var i in names) {
  18962. if (mesh.name === names[i]) {
  18963. hierarchyIds.push(mesh.id);
  18964. return true;
  18965. }
  18966. }
  18967. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18968. hierarchyIds.push(mesh.id);
  18969. return true;
  18970. }
  18971. return false;
  18972. };
  18973. var importVertexData = function (parsedVertexData, geometry) {
  18974. var vertexData = new BABYLON.VertexData();
  18975. // positions
  18976. var positions = parsedVertexData.positions;
  18977. if (positions) {
  18978. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18979. }
  18980. // normals
  18981. var normals = parsedVertexData.normals;
  18982. if (normals) {
  18983. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18984. }
  18985. // uvs
  18986. var uvs = parsedVertexData.uvs;
  18987. if (uvs) {
  18988. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18989. }
  18990. // uv2s
  18991. var uv2s = parsedVertexData.uv2s;
  18992. if (uv2s) {
  18993. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18994. }
  18995. // colors
  18996. var colors = parsedVertexData.colors;
  18997. if (colors) {
  18998. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18999. }
  19000. // matricesIndices
  19001. var matricesIndices = parsedVertexData.matricesIndices;
  19002. if (matricesIndices) {
  19003. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19004. }
  19005. // matricesWeights
  19006. var matricesWeights = parsedVertexData.matricesWeights;
  19007. if (matricesWeights) {
  19008. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19009. }
  19010. // indices
  19011. var indices = parsedVertexData.indices;
  19012. if (indices) {
  19013. vertexData.indices = indices;
  19014. }
  19015. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19016. };
  19017. var importGeometry = function (parsedGeometry, mesh) {
  19018. var scene = mesh.getScene();
  19019. // Geometry
  19020. var geometryId = parsedGeometry.geometryId;
  19021. if (geometryId) {
  19022. var geometry = scene.getGeometryByID(geometryId);
  19023. if (geometry) {
  19024. geometry.applyToMesh(mesh);
  19025. }
  19026. }
  19027. else if (parsedGeometry instanceof ArrayBuffer) {
  19028. var binaryInfo = mesh._binaryInfo;
  19029. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19030. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19031. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19032. }
  19033. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19034. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19035. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19036. }
  19037. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19038. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19039. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19040. }
  19041. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19042. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19043. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19044. }
  19045. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19046. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19047. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19048. }
  19049. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19050. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19051. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19052. }
  19053. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19054. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19055. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19056. }
  19057. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19058. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19059. mesh.setIndices(indicesData);
  19060. }
  19061. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19062. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19063. mesh.subMeshes = [];
  19064. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19065. var materialIndex = subMeshesData[(i * 5) + 0];
  19066. var verticesStart = subMeshesData[(i * 5) + 1];
  19067. var verticesCount = subMeshesData[(i * 5) + 2];
  19068. var indexStart = subMeshesData[(i * 5) + 3];
  19069. var indexCount = subMeshesData[(i * 5) + 4];
  19070. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19071. }
  19072. }
  19073. }
  19074. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19075. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19076. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19077. if (parsedGeometry.uvs) {
  19078. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19079. }
  19080. if (parsedGeometry.uvs2) {
  19081. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19082. }
  19083. if (parsedGeometry.colors) {
  19084. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19085. }
  19086. if (parsedGeometry.matricesIndices) {
  19087. if (!parsedGeometry.matricesIndices._isExpanded) {
  19088. var floatIndices = [];
  19089. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19090. var matricesIndex = parsedGeometry.matricesIndices[i];
  19091. floatIndices.push(matricesIndex & 0x000000FF);
  19092. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19093. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19094. floatIndices.push(matricesIndex >> 24);
  19095. }
  19096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19097. }
  19098. else {
  19099. delete parsedGeometry.matricesIndices._isExpanded;
  19100. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19101. }
  19102. }
  19103. if (parsedGeometry.matricesWeights) {
  19104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19105. }
  19106. mesh.setIndices(parsedGeometry.indices);
  19107. // SubMeshes
  19108. if (parsedGeometry.subMeshes) {
  19109. mesh.subMeshes = [];
  19110. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19111. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19112. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19113. }
  19114. }
  19115. }
  19116. // Flat shading
  19117. if (mesh._shouldGenerateFlatShading) {
  19118. mesh.convertToFlatShadedMesh();
  19119. delete mesh._shouldGenerateFlatShading;
  19120. }
  19121. // Update
  19122. mesh.computeWorldMatrix(true);
  19123. // Octree
  19124. if (scene._selectionOctree) {
  19125. scene._selectionOctree.addMesh(mesh);
  19126. }
  19127. };
  19128. BABYLON.SceneLoader.RegisterPlugin({
  19129. extensions: ".babylon",
  19130. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19131. var parsedData = JSON.parse(data);
  19132. var loadedSkeletonsIds = [];
  19133. var loadedMaterialsIds = [];
  19134. var hierarchyIds = [];
  19135. for (var index = 0; index < parsedData.meshes.length; index++) {
  19136. var parsedMesh = parsedData.meshes[index];
  19137. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19138. if (meshesNames instanceof Array) {
  19139. // Remove found mesh name from list.
  19140. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19141. }
  19142. // Material ?
  19143. if (parsedMesh.materialId) {
  19144. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19145. if (!materialFound) {
  19146. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19147. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19148. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19149. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19150. var subMatId = parsedMultiMaterial.materials[matIndex];
  19151. loadedMaterialsIds.push(subMatId);
  19152. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19153. }
  19154. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19155. parseMultiMaterial(parsedMultiMaterial, scene);
  19156. materialFound = true;
  19157. break;
  19158. }
  19159. }
  19160. }
  19161. if (!materialFound) {
  19162. loadedMaterialsIds.push(parsedMesh.materialId);
  19163. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19164. }
  19165. }
  19166. // Skeleton ?
  19167. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19168. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19169. if (!skeletonAlreadyLoaded) {
  19170. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19171. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19172. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19173. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19174. loadedSkeletonsIds.push(parsedSkeleton.id);
  19175. }
  19176. }
  19177. }
  19178. }
  19179. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19180. meshes.push(mesh);
  19181. }
  19182. }
  19183. for (index = 0; index < scene.meshes.length; index++) {
  19184. var currentMesh = scene.meshes[index];
  19185. if (currentMesh._waitingParentId) {
  19186. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19187. currentMesh._waitingParentId = undefined;
  19188. }
  19189. }
  19190. // Particles
  19191. if (parsedData.particleSystems) {
  19192. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19193. var parsedParticleSystem = parsedData.particleSystems[index];
  19194. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19195. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19196. }
  19197. }
  19198. }
  19199. return true;
  19200. },
  19201. load: function (scene, data, rootUrl) {
  19202. var parsedData = JSON.parse(data);
  19203. // Scene
  19204. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19205. scene.autoClear = parsedData.autoClear;
  19206. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19207. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19208. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19209. // Fog
  19210. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19211. scene.fogMode = parsedData.fogMode;
  19212. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19213. scene.fogStart = parsedData.fogStart;
  19214. scene.fogEnd = parsedData.fogEnd;
  19215. scene.fogDensity = parsedData.fogDensity;
  19216. }
  19217. for (var index = 0; index < parsedData.lights.length; index++) {
  19218. var parsedLight = parsedData.lights[index];
  19219. parseLight(parsedLight, scene);
  19220. }
  19221. // Materials
  19222. if (parsedData.materials) {
  19223. for (index = 0; index < parsedData.materials.length; index++) {
  19224. var parsedMaterial = parsedData.materials[index];
  19225. parseMaterial(parsedMaterial, scene, rootUrl);
  19226. }
  19227. }
  19228. if (parsedData.multiMaterials) {
  19229. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19230. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19231. parseMultiMaterial(parsedMultiMaterial, scene);
  19232. }
  19233. }
  19234. // Skeletons
  19235. if (parsedData.skeletons) {
  19236. for (index = 0; index < parsedData.skeletons.length; index++) {
  19237. var parsedSkeleton = parsedData.skeletons[index];
  19238. parseSkeleton(parsedSkeleton, scene);
  19239. }
  19240. }
  19241. // Geometries
  19242. var geometries = parsedData.geometries;
  19243. if (geometries) {
  19244. // Boxes
  19245. var boxes = geometries.boxes;
  19246. if (boxes) {
  19247. for (index = 0; index < boxes.length; index++) {
  19248. var parsedBox = boxes[index];
  19249. parseBox(parsedBox, scene);
  19250. }
  19251. }
  19252. // Spheres
  19253. var spheres = geometries.spheres;
  19254. if (spheres) {
  19255. for (index = 0; index < spheres.length; index++) {
  19256. var parsedSphere = spheres[index];
  19257. parseSphere(parsedSphere, scene);
  19258. }
  19259. }
  19260. // Cylinders
  19261. var cylinders = geometries.cylinders;
  19262. if (cylinders) {
  19263. for (index = 0; index < cylinders.length; index++) {
  19264. var parsedCylinder = cylinders[index];
  19265. parseCylinder(parsedCylinder, scene);
  19266. }
  19267. }
  19268. // Toruses
  19269. var toruses = geometries.toruses;
  19270. if (toruses) {
  19271. for (index = 0; index < toruses.length; index++) {
  19272. var parsedTorus = toruses[index];
  19273. parseTorus(parsedTorus, scene);
  19274. }
  19275. }
  19276. // Grounds
  19277. var grounds = geometries.grounds;
  19278. if (grounds) {
  19279. for (index = 0; index < grounds.length; index++) {
  19280. var parsedGround = grounds[index];
  19281. parseGround(parsedGround, scene);
  19282. }
  19283. }
  19284. // Planes
  19285. var planes = geometries.planes;
  19286. if (planes) {
  19287. for (index = 0; index < planes.length; index++) {
  19288. var parsedPlane = planes[index];
  19289. parsePlane(parsedPlane, scene);
  19290. }
  19291. }
  19292. // TorusKnots
  19293. var torusKnots = geometries.torusKnots;
  19294. if (torusKnots) {
  19295. for (index = 0; index < torusKnots.length; index++) {
  19296. var parsedTorusKnot = torusKnots[index];
  19297. parseTorusKnot(parsedTorusKnot, scene);
  19298. }
  19299. }
  19300. // VertexData
  19301. var vertexData = geometries.vertexData;
  19302. if (vertexData) {
  19303. for (index = 0; index < vertexData.length; index++) {
  19304. var parsedVertexData = vertexData[index];
  19305. parseVertexData(parsedVertexData, scene, rootUrl);
  19306. }
  19307. }
  19308. }
  19309. for (index = 0; index < parsedData.meshes.length; index++) {
  19310. var parsedMesh = parsedData.meshes[index];
  19311. parseMesh(parsedMesh, scene, rootUrl);
  19312. }
  19313. for (index = 0; index < parsedData.cameras.length; index++) {
  19314. var parsedCamera = parsedData.cameras[index];
  19315. parseCamera(parsedCamera, scene);
  19316. }
  19317. if (parsedData.activeCameraID) {
  19318. scene.setActiveCameraByID(parsedData.activeCameraID);
  19319. }
  19320. for (index = 0; index < scene.cameras.length; index++) {
  19321. var camera = scene.cameras[index];
  19322. if (camera._waitingParentId) {
  19323. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19324. camera._waitingParentId = undefined;
  19325. }
  19326. }
  19327. for (index = 0; index < scene.lights.length; index++) {
  19328. var light = scene.lights[index];
  19329. if (light._waitingParentId) {
  19330. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19331. light._waitingParentId = undefined;
  19332. }
  19333. }
  19334. // Sounds
  19335. if (parsedData.sounds && BABYLON.Engine.audioEngine.canUseWebAudio) {
  19336. for (index = 0; index < parsedData.sounds.length; index++) {
  19337. var parsedSound = parsedData.sounds[index];
  19338. parseSound(parsedSound, scene, rootUrl);
  19339. }
  19340. }
  19341. for (index = 0; index < scene.meshes.length; index++) {
  19342. var mesh = scene.meshes[index];
  19343. if (mesh._waitingParentId) {
  19344. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19345. mesh._waitingParentId = undefined;
  19346. }
  19347. if (mesh._waitingActions) {
  19348. parseActions(mesh._waitingActions, mesh, scene);
  19349. mesh._waitingActions = undefined;
  19350. }
  19351. }
  19352. // Particles Systems
  19353. if (parsedData.particleSystems) {
  19354. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19355. var parsedParticleSystem = parsedData.particleSystems[index];
  19356. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19357. }
  19358. }
  19359. // Lens flares
  19360. if (parsedData.lensFlareSystems) {
  19361. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19362. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19363. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19364. }
  19365. }
  19366. // Shadows
  19367. if (parsedData.shadowGenerators) {
  19368. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19369. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19370. parseShadowGenerator(parsedShadowGenerator, scene);
  19371. }
  19372. }
  19373. // Actions (scene)
  19374. if (parsedData.actions) {
  19375. parseActions(parsedData.actions, null, scene);
  19376. }
  19377. // Finish
  19378. return true;
  19379. }
  19380. });
  19381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19382. })(BABYLON || (BABYLON = {}));
  19383. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19384. (function (BABYLON) {
  19385. // Unique ID when we import meshes from Babylon to CSG
  19386. var currentCSGMeshId = 0;
  19387. // # class Vertex
  19388. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19389. // one to provide additional features like texture coordinates and vertex
  19390. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19391. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19392. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19393. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19394. // is not used anywhere else.
  19395. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19396. var Vertex = (function () {
  19397. function Vertex(pos, normal, uv) {
  19398. this.pos = pos;
  19399. this.normal = normal;
  19400. this.uv = uv;
  19401. }
  19402. Vertex.prototype.clone = function () {
  19403. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19404. };
  19405. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19406. // orientation of a polygon is flipped.
  19407. Vertex.prototype.flip = function () {
  19408. this.normal = this.normal.scale(-1);
  19409. };
  19410. // Create a new vertex between this vertex and `other` by linearly
  19411. // interpolating all properties using a parameter of `t`. Subclasses should
  19412. // override this to interpolate additional properties.
  19413. Vertex.prototype.interpolate = function (other, t) {
  19414. 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));
  19415. };
  19416. return Vertex;
  19417. })();
  19418. // # class Plane
  19419. // Represents a plane in 3D space.
  19420. var Plane = (function () {
  19421. function Plane(normal, w) {
  19422. this.normal = normal;
  19423. this.w = w;
  19424. }
  19425. Plane.FromPoints = function (a, b, c) {
  19426. var v0 = c.subtract(a);
  19427. var v1 = b.subtract(a);
  19428. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19429. return null;
  19430. }
  19431. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19432. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19433. };
  19434. Plane.prototype.clone = function () {
  19435. return new Plane(this.normal.clone(), this.w);
  19436. };
  19437. Plane.prototype.flip = function () {
  19438. this.normal.scaleInPlace(-1);
  19439. this.w = -this.w;
  19440. };
  19441. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19442. // fragments in the appropriate lists. Coplanar polygons go into either
  19443. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19444. // respect to this plane. Polygons in front or in back of this plane go into
  19445. // either `front` or `back`.
  19446. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19447. var COPLANAR = 0;
  19448. var FRONT = 1;
  19449. var BACK = 2;
  19450. var SPANNING = 3;
  19451. // Classify each point as well as the entire polygon into one of the above
  19452. // four classes.
  19453. var polygonType = 0;
  19454. var types = [];
  19455. for (var i = 0; i < polygon.vertices.length; i++) {
  19456. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19457. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19458. polygonType |= type;
  19459. types.push(type);
  19460. }
  19461. switch (polygonType) {
  19462. case COPLANAR:
  19463. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19464. break;
  19465. case FRONT:
  19466. front.push(polygon);
  19467. break;
  19468. case BACK:
  19469. back.push(polygon);
  19470. break;
  19471. case SPANNING:
  19472. var f = [], b = [];
  19473. for (i = 0; i < polygon.vertices.length; i++) {
  19474. var j = (i + 1) % polygon.vertices.length;
  19475. var ti = types[i], tj = types[j];
  19476. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19477. if (ti != BACK)
  19478. f.push(vi);
  19479. if (ti != FRONT)
  19480. b.push(ti != BACK ? vi.clone() : vi);
  19481. if ((ti | tj) == SPANNING) {
  19482. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19483. var v = vi.interpolate(vj, t);
  19484. f.push(v);
  19485. b.push(v.clone());
  19486. }
  19487. }
  19488. if (f.length >= 3) {
  19489. var poly = new Polygon(f, polygon.shared);
  19490. if (poly.plane)
  19491. front.push(poly);
  19492. }
  19493. if (b.length >= 3) {
  19494. poly = new Polygon(b, polygon.shared);
  19495. if (poly.plane)
  19496. back.push(poly);
  19497. }
  19498. break;
  19499. }
  19500. };
  19501. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19502. // point is on the plane.
  19503. Plane.EPSILON = 1e-5;
  19504. return Plane;
  19505. })();
  19506. // # class Polygon
  19507. // Represents a convex polygon. The vertices used to initialize a polygon must
  19508. // be coplanar and form a convex loop.
  19509. //
  19510. // Each convex polygon has a `shared` property, which is shared between all
  19511. // polygons that are clones of each other or were split from the same polygon.
  19512. // This can be used to define per-polygon properties (such as surface color).
  19513. var Polygon = (function () {
  19514. function Polygon(vertices, shared) {
  19515. this.vertices = vertices;
  19516. this.shared = shared;
  19517. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19518. }
  19519. Polygon.prototype.clone = function () {
  19520. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19521. return new Polygon(vertices, this.shared);
  19522. };
  19523. Polygon.prototype.flip = function () {
  19524. this.vertices.reverse().map(function (v) {
  19525. v.flip();
  19526. });
  19527. this.plane.flip();
  19528. };
  19529. return Polygon;
  19530. })();
  19531. // # class Node
  19532. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19533. // by picking a polygon to split along. That polygon (and all other coplanar
  19534. // polygons) are added directly to that node and the other polygons are added to
  19535. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19536. // no distinction between internal and leaf nodes.
  19537. var Node = (function () {
  19538. function Node(polygons) {
  19539. this.plane = null;
  19540. this.front = null;
  19541. this.back = null;
  19542. this.polygons = [];
  19543. if (polygons) {
  19544. this.build(polygons);
  19545. }
  19546. }
  19547. Node.prototype.clone = function () {
  19548. var node = new Node();
  19549. node.plane = this.plane && this.plane.clone();
  19550. node.front = this.front && this.front.clone();
  19551. node.back = this.back && this.back.clone();
  19552. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19553. return node;
  19554. };
  19555. // Convert solid space to empty space and empty space to solid space.
  19556. Node.prototype.invert = function () {
  19557. for (var i = 0; i < this.polygons.length; i++) {
  19558. this.polygons[i].flip();
  19559. }
  19560. if (this.plane) {
  19561. this.plane.flip();
  19562. }
  19563. if (this.front) {
  19564. this.front.invert();
  19565. }
  19566. if (this.back) {
  19567. this.back.invert();
  19568. }
  19569. var temp = this.front;
  19570. this.front = this.back;
  19571. this.back = temp;
  19572. };
  19573. // Recursively remove all polygons in `polygons` that are inside this BSP
  19574. // tree.
  19575. Node.prototype.clipPolygons = function (polygons) {
  19576. if (!this.plane)
  19577. return polygons.slice();
  19578. var front = [], back = [];
  19579. for (var i = 0; i < polygons.length; i++) {
  19580. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19581. }
  19582. if (this.front) {
  19583. front = this.front.clipPolygons(front);
  19584. }
  19585. if (this.back) {
  19586. back = this.back.clipPolygons(back);
  19587. }
  19588. else {
  19589. back = [];
  19590. }
  19591. return front.concat(back);
  19592. };
  19593. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19594. // `bsp`.
  19595. Node.prototype.clipTo = function (bsp) {
  19596. this.polygons = bsp.clipPolygons(this.polygons);
  19597. if (this.front)
  19598. this.front.clipTo(bsp);
  19599. if (this.back)
  19600. this.back.clipTo(bsp);
  19601. };
  19602. // Return a list of all polygons in this BSP tree.
  19603. Node.prototype.allPolygons = function () {
  19604. var polygons = this.polygons.slice();
  19605. if (this.front)
  19606. polygons = polygons.concat(this.front.allPolygons());
  19607. if (this.back)
  19608. polygons = polygons.concat(this.back.allPolygons());
  19609. return polygons;
  19610. };
  19611. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19612. // new polygons are filtered down to the bottom of the tree and become new
  19613. // nodes there. Each set of polygons is partitioned using the first polygon
  19614. // (no heuristic is used to pick a good split).
  19615. Node.prototype.build = function (polygons) {
  19616. if (!polygons.length)
  19617. return;
  19618. if (!this.plane)
  19619. this.plane = polygons[0].plane.clone();
  19620. var front = [], back = [];
  19621. for (var i = 0; i < polygons.length; i++) {
  19622. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19623. }
  19624. if (front.length) {
  19625. if (!this.front)
  19626. this.front = new Node();
  19627. this.front.build(front);
  19628. }
  19629. if (back.length) {
  19630. if (!this.back)
  19631. this.back = new Node();
  19632. this.back.build(back);
  19633. }
  19634. };
  19635. return Node;
  19636. })();
  19637. var CSG = (function () {
  19638. function CSG() {
  19639. this.polygons = new Array();
  19640. }
  19641. // Convert BABYLON.Mesh to BABYLON.CSG
  19642. CSG.FromMesh = function (mesh) {
  19643. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19644. if (mesh instanceof BABYLON.Mesh) {
  19645. mesh.computeWorldMatrix(true);
  19646. var matrix = mesh.getWorldMatrix();
  19647. var meshPosition = mesh.position.clone();
  19648. var meshRotation = mesh.rotation.clone();
  19649. var meshScaling = mesh.scaling.clone();
  19650. }
  19651. else {
  19652. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19653. }
  19654. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19655. var subMeshes = mesh.subMeshes;
  19656. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19657. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19658. vertices = [];
  19659. for (var j = 0; j < 3; j++) {
  19660. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19661. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19662. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19663. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19664. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19665. vertex = new Vertex(position, normal, uv);
  19666. vertices.push(vertex);
  19667. }
  19668. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19669. // To handle the case of degenerated triangle
  19670. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19671. if (polygon.plane)
  19672. polygons.push(polygon);
  19673. }
  19674. }
  19675. var csg = CSG.FromPolygons(polygons);
  19676. csg.matrix = matrix;
  19677. csg.position = meshPosition;
  19678. csg.rotation = meshRotation;
  19679. csg.scaling = meshScaling;
  19680. currentCSGMeshId++;
  19681. return csg;
  19682. };
  19683. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19684. CSG.FromPolygons = function (polygons) {
  19685. var csg = new BABYLON.CSG();
  19686. csg.polygons = polygons;
  19687. return csg;
  19688. };
  19689. CSG.prototype.clone = function () {
  19690. var csg = new BABYLON.CSG();
  19691. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19692. csg.copyTransformAttributes(this);
  19693. return csg;
  19694. };
  19695. CSG.prototype.toPolygons = function () {
  19696. return this.polygons;
  19697. };
  19698. CSG.prototype.union = function (csg) {
  19699. var a = new Node(this.clone().polygons);
  19700. var b = new Node(csg.clone().polygons);
  19701. a.clipTo(b);
  19702. b.clipTo(a);
  19703. b.invert();
  19704. b.clipTo(a);
  19705. b.invert();
  19706. a.build(b.allPolygons());
  19707. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19708. };
  19709. CSG.prototype.unionInPlace = function (csg) {
  19710. var a = new Node(this.polygons);
  19711. var b = new Node(csg.polygons);
  19712. a.clipTo(b);
  19713. b.clipTo(a);
  19714. b.invert();
  19715. b.clipTo(a);
  19716. b.invert();
  19717. a.build(b.allPolygons());
  19718. this.polygons = a.allPolygons();
  19719. };
  19720. CSG.prototype.subtract = function (csg) {
  19721. var a = new Node(this.clone().polygons);
  19722. var b = new Node(csg.clone().polygons);
  19723. a.invert();
  19724. a.clipTo(b);
  19725. b.clipTo(a);
  19726. b.invert();
  19727. b.clipTo(a);
  19728. b.invert();
  19729. a.build(b.allPolygons());
  19730. a.invert();
  19731. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19732. };
  19733. CSG.prototype.subtractInPlace = function (csg) {
  19734. var a = new Node(this.polygons);
  19735. var b = new Node(csg.polygons);
  19736. a.invert();
  19737. a.clipTo(b);
  19738. b.clipTo(a);
  19739. b.invert();
  19740. b.clipTo(a);
  19741. b.invert();
  19742. a.build(b.allPolygons());
  19743. a.invert();
  19744. this.polygons = a.allPolygons();
  19745. };
  19746. CSG.prototype.intersect = function (csg) {
  19747. var a = new Node(this.clone().polygons);
  19748. var b = new Node(csg.clone().polygons);
  19749. a.invert();
  19750. b.clipTo(a);
  19751. b.invert();
  19752. a.clipTo(b);
  19753. b.clipTo(a);
  19754. a.build(b.allPolygons());
  19755. a.invert();
  19756. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19757. };
  19758. CSG.prototype.intersectInPlace = function (csg) {
  19759. var a = new Node(this.polygons);
  19760. var b = new Node(csg.polygons);
  19761. a.invert();
  19762. b.clipTo(a);
  19763. b.invert();
  19764. a.clipTo(b);
  19765. b.clipTo(a);
  19766. a.build(b.allPolygons());
  19767. a.invert();
  19768. this.polygons = a.allPolygons();
  19769. };
  19770. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19771. // not modified.
  19772. CSG.prototype.inverse = function () {
  19773. var csg = this.clone();
  19774. csg.inverseInPlace();
  19775. return csg;
  19776. };
  19777. CSG.prototype.inverseInPlace = function () {
  19778. this.polygons.map(function (p) {
  19779. p.flip();
  19780. });
  19781. };
  19782. // This is used to keep meshes transformations so they can be restored
  19783. // when we build back a Babylon Mesh
  19784. // NB : All CSG operations are performed in world coordinates
  19785. CSG.prototype.copyTransformAttributes = function (csg) {
  19786. this.matrix = csg.matrix;
  19787. this.position = csg.position;
  19788. this.rotation = csg.rotation;
  19789. this.scaling = csg.scaling;
  19790. return this;
  19791. };
  19792. // Build Raw mesh from CSG
  19793. // Coordinates here are in world space
  19794. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19795. var matrix = this.matrix.clone();
  19796. matrix.invert();
  19797. 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;
  19798. if (keepSubMeshes) {
  19799. // Sort Polygons, since subMeshes are indices range
  19800. polygons.sort(function (a, b) {
  19801. if (a.shared.meshId === b.shared.meshId) {
  19802. return a.shared.subMeshId - b.shared.subMeshId;
  19803. }
  19804. else {
  19805. return a.shared.meshId - b.shared.meshId;
  19806. }
  19807. });
  19808. }
  19809. for (var i = 0, il = polygons.length; i < il; i++) {
  19810. polygon = polygons[i];
  19811. // Building SubMeshes
  19812. if (!subMesh_dict[polygon.shared.meshId]) {
  19813. subMesh_dict[polygon.shared.meshId] = {};
  19814. }
  19815. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19816. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19817. indexStart: +Infinity,
  19818. indexEnd: -Infinity,
  19819. materialIndex: polygon.shared.materialIndex
  19820. };
  19821. }
  19822. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19823. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19824. polygonIndices[0] = 0;
  19825. polygonIndices[1] = j - 1;
  19826. polygonIndices[2] = j;
  19827. for (var k = 0; k < 3; k++) {
  19828. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19829. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19830. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19831. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19832. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19833. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19834. // Check if 2 points can be merged
  19835. 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)) {
  19836. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19837. uvs.push(uv.x, uv.y);
  19838. normals.push(normal.x, normal.y, normal.z);
  19839. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19840. }
  19841. indices.push(vertex_idx);
  19842. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19843. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19844. currentIndex++;
  19845. }
  19846. }
  19847. }
  19848. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19849. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19850. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19851. mesh.setIndices(indices);
  19852. if (keepSubMeshes) {
  19853. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19854. var materialIndexOffset = 0, materialMaxIndex;
  19855. mesh.subMeshes.length = 0;
  19856. for (var m in subMesh_dict) {
  19857. materialMaxIndex = -1;
  19858. for (var sm in subMesh_dict[m]) {
  19859. subMesh_obj = subMesh_dict[m][sm];
  19860. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19861. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19862. }
  19863. materialIndexOffset += ++materialMaxIndex;
  19864. }
  19865. }
  19866. return mesh;
  19867. };
  19868. // Build Mesh from CSG taking material and transforms into account
  19869. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19870. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19871. mesh.material = material;
  19872. mesh.position.copyFrom(this.position);
  19873. mesh.rotation.copyFrom(this.rotation);
  19874. mesh.scaling.copyFrom(this.scaling);
  19875. mesh.computeWorldMatrix(true);
  19876. return mesh;
  19877. };
  19878. return CSG;
  19879. })();
  19880. BABYLON.CSG = CSG;
  19881. })(BABYLON || (BABYLON = {}));
  19882. //# sourceMappingURL=babylon.csg.js.map
  19883. var BABYLON;
  19884. (function (BABYLON) {
  19885. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19886. __extends(OculusDistortionCorrectionPostProcess, _super);
  19887. //ANY
  19888. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19889. var _this = this;
  19890. _super.call(this, name, "oculusDistortionCorrection", [
  19891. 'LensCenter',
  19892. 'Scale',
  19893. 'ScaleIn',
  19894. 'HmdWarpParam'
  19895. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19896. this._isRightEye = isRightEye;
  19897. this._distortionFactors = cameraSettings.DistortionK;
  19898. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19899. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19900. this.onSizeChanged = function () {
  19901. _this.aspectRatio = _this.width * .5 / _this.height;
  19902. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19903. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19904. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19905. };
  19906. this.onApply = function (effect) {
  19907. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19908. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19909. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19910. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19911. };
  19912. }
  19913. return OculusDistortionCorrectionPostProcess;
  19914. })(BABYLON.PostProcess);
  19915. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19916. })(BABYLON || (BABYLON = {}));
  19917. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19918. // 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
  19919. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19920. var BABYLON;
  19921. (function (BABYLON) {
  19922. (function (JoystickAxis) {
  19923. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19924. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19925. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19926. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19927. var JoystickAxis = BABYLON.JoystickAxis;
  19928. var VirtualJoystick = (function () {
  19929. function VirtualJoystick(leftJoystick) {
  19930. var _this = this;
  19931. if (leftJoystick) {
  19932. this._leftJoystick = true;
  19933. }
  19934. else {
  19935. this._leftJoystick = false;
  19936. }
  19937. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19938. VirtualJoystick._globalJoystickIndex++;
  19939. // By default left & right arrow keys are moving the X
  19940. // and up & down keys are moving the Y
  19941. this._axisTargetedByLeftAndRight = 0 /* X */;
  19942. this._axisTargetedByUpAndDown = 1 /* Y */;
  19943. this.reverseLeftRight = false;
  19944. this.reverseUpDown = false;
  19945. // collections of pointers
  19946. this._touches = new BABYLON.VirtualJoystick.Collection();
  19947. this.deltaPosition = BABYLON.Vector3.Zero();
  19948. this._joystickSensibility = 25;
  19949. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19950. this._rotationSpeed = 25;
  19951. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19952. this._rotateOnAxisRelativeToMesh = false;
  19953. // injecting a canvas element on top of the canvas 3D game
  19954. if (!VirtualJoystick.vjCanvas) {
  19955. window.addEventListener("resize", function () {
  19956. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19957. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19958. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19959. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19960. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19961. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19962. }, false);
  19963. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19964. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19965. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19966. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19967. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19968. VirtualJoystick.vjCanvas.style.width = "100%";
  19969. VirtualJoystick.vjCanvas.style.height = "100%";
  19970. VirtualJoystick.vjCanvas.style.position = "absolute";
  19971. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19972. VirtualJoystick.vjCanvas.style.top = "0px";
  19973. VirtualJoystick.vjCanvas.style.left = "0px";
  19974. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19975. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19976. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19977. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19978. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19979. document.body.appendChild(VirtualJoystick.vjCanvas);
  19980. }
  19981. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19982. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19983. this.pressed = false;
  19984. // default joystick color
  19985. this._joystickColor = "cyan";
  19986. this._joystickPointerID = -1;
  19987. // current joystick position
  19988. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19989. // origin joystick position
  19990. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19991. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19992. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19993. _this._onPointerDown(evt);
  19994. }, false);
  19995. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19996. _this._onPointerMove(evt);
  19997. }, false);
  19998. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19999. _this._onPointerUp(evt);
  20000. }, false);
  20001. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20002. _this._onPointerUp(evt);
  20003. }, false);
  20004. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20005. evt.preventDefault(); // Disables system menu
  20006. }, false);
  20007. requestAnimationFrame(function () {
  20008. _this._drawVirtualJoystick();
  20009. });
  20010. }
  20011. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20012. this._joystickSensibility = newJoystickSensibility;
  20013. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20014. };
  20015. VirtualJoystick.prototype._onPointerDown = function (e) {
  20016. var positionOnScreenCondition;
  20017. e.preventDefault();
  20018. if (this._leftJoystick === true) {
  20019. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20020. }
  20021. else {
  20022. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20023. }
  20024. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20025. // First contact will be dedicated to the virtual joystick
  20026. this._joystickPointerID = e.pointerId;
  20027. this._joystickPointerStartPos.x = e.clientX;
  20028. this._joystickPointerStartPos.y = e.clientY;
  20029. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20030. this._deltaJoystickVector.x = 0;
  20031. this._deltaJoystickVector.y = 0;
  20032. this.pressed = true;
  20033. this._touches.add(e.pointerId.toString(), e);
  20034. }
  20035. else {
  20036. // You can only trigger the action buttons with a joystick declared
  20037. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20038. this._action();
  20039. this._touches.add(e.pointerId.toString(), e);
  20040. }
  20041. }
  20042. };
  20043. VirtualJoystick.prototype._onPointerMove = function (e) {
  20044. // If the current pointer is the one associated to the joystick (first touch contact)
  20045. if (this._joystickPointerID == e.pointerId) {
  20046. this._joystickPointerPos.x = e.clientX;
  20047. this._joystickPointerPos.y = e.clientY;
  20048. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20049. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20050. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20051. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20052. switch (this._axisTargetedByLeftAndRight) {
  20053. case 0 /* X */:
  20054. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20055. break;
  20056. case 1 /* Y */:
  20057. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20058. break;
  20059. case 2 /* Z */:
  20060. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20061. break;
  20062. }
  20063. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20064. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20065. switch (this._axisTargetedByUpAndDown) {
  20066. case 0 /* X */:
  20067. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20068. break;
  20069. case 1 /* Y */:
  20070. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20071. break;
  20072. case 2 /* Z */:
  20073. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20074. break;
  20075. }
  20076. }
  20077. else {
  20078. if (this._touches.item(e.pointerId.toString())) {
  20079. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20080. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20081. }
  20082. }
  20083. };
  20084. VirtualJoystick.prototype._onPointerUp = function (e) {
  20085. this._clearCanvas();
  20086. if (this._joystickPointerID == e.pointerId) {
  20087. this._joystickPointerID = -1;
  20088. this.pressed = false;
  20089. }
  20090. this._deltaJoystickVector.x = 0;
  20091. this._deltaJoystickVector.y = 0;
  20092. this._touches.remove(e.pointerId.toString());
  20093. };
  20094. /**
  20095. * Change the color of the virtual joystick
  20096. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20097. */
  20098. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20099. this._joystickColor = newColor;
  20100. };
  20101. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20102. this._action = action;
  20103. };
  20104. // Define which axis you'd like to control for left & right
  20105. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20106. switch (axis) {
  20107. case 0 /* X */:
  20108. case 1 /* Y */:
  20109. case 2 /* Z */:
  20110. this._axisTargetedByLeftAndRight = axis;
  20111. break;
  20112. default:
  20113. this._axisTargetedByLeftAndRight = 0 /* X */;
  20114. break;
  20115. }
  20116. };
  20117. // Define which axis you'd like to control for up & down
  20118. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20119. switch (axis) {
  20120. case 0 /* X */:
  20121. case 1 /* Y */:
  20122. case 2 /* Z */:
  20123. this._axisTargetedByUpAndDown = axis;
  20124. break;
  20125. default:
  20126. this._axisTargetedByUpAndDown = 1 /* Y */;
  20127. break;
  20128. }
  20129. };
  20130. VirtualJoystick.prototype._clearCanvas = function () {
  20131. if (this._leftJoystick) {
  20132. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20133. }
  20134. else {
  20135. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20136. }
  20137. };
  20138. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20139. var _this = this;
  20140. if (this.pressed) {
  20141. this._clearCanvas();
  20142. this._touches.forEach(function (touch) {
  20143. if (touch.pointerId === _this._joystickPointerID) {
  20144. VirtualJoystick.vjCanvasContext.beginPath();
  20145. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20146. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20147. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20148. VirtualJoystick.vjCanvasContext.stroke();
  20149. VirtualJoystick.vjCanvasContext.beginPath();
  20150. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20151. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20152. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20153. VirtualJoystick.vjCanvasContext.stroke();
  20154. VirtualJoystick.vjCanvasContext.beginPath();
  20155. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20156. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20157. VirtualJoystick.vjCanvasContext.stroke();
  20158. }
  20159. else {
  20160. VirtualJoystick.vjCanvasContext.beginPath();
  20161. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20162. VirtualJoystick.vjCanvasContext.beginPath();
  20163. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20164. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20165. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20166. VirtualJoystick.vjCanvasContext.stroke();
  20167. }
  20168. ;
  20169. });
  20170. }
  20171. requestAnimationFrame(function () {
  20172. _this._drawVirtualJoystick();
  20173. });
  20174. };
  20175. VirtualJoystick.prototype.releaseCanvas = function () {
  20176. if (VirtualJoystick.vjCanvas) {
  20177. document.body.removeChild(VirtualJoystick.vjCanvas);
  20178. VirtualJoystick.vjCanvas = null;
  20179. }
  20180. };
  20181. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20182. VirtualJoystick._globalJoystickIndex = 0;
  20183. return VirtualJoystick;
  20184. })();
  20185. BABYLON.VirtualJoystick = VirtualJoystick;
  20186. })(BABYLON || (BABYLON = {}));
  20187. var BABYLON;
  20188. (function (BABYLON) {
  20189. var VirtualJoystick;
  20190. (function (VirtualJoystick) {
  20191. var Collection = (function () {
  20192. function Collection() {
  20193. this._count = 0;
  20194. this._collection = new Array();
  20195. }
  20196. Collection.prototype.Count = function () {
  20197. return this._count;
  20198. };
  20199. Collection.prototype.add = function (key, item) {
  20200. if (this._collection[key] != undefined) {
  20201. return undefined;
  20202. }
  20203. this._collection[key] = item;
  20204. return ++this._count;
  20205. };
  20206. Collection.prototype.remove = function (key) {
  20207. if (this._collection[key] == undefined) {
  20208. return undefined;
  20209. }
  20210. delete this._collection[key];
  20211. return --this._count;
  20212. };
  20213. Collection.prototype.item = function (key) {
  20214. return this._collection[key];
  20215. };
  20216. Collection.prototype.forEach = function (block) {
  20217. var key;
  20218. for (key in this._collection) {
  20219. if (this._collection.hasOwnProperty(key)) {
  20220. block(this._collection[key]);
  20221. }
  20222. }
  20223. };
  20224. return Collection;
  20225. })();
  20226. VirtualJoystick.Collection = Collection;
  20227. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20228. })(BABYLON || (BABYLON = {}));
  20229. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20230. var BABYLON;
  20231. (function (BABYLON) {
  20232. var OculusRiftDevKit2013_Metric = {
  20233. HResolution: 1280,
  20234. VResolution: 800,
  20235. HScreenSize: 0.149759993,
  20236. VScreenSize: 0.0935999975,
  20237. VScreenCenter: 0.0467999987,
  20238. EyeToScreenDistance: 0.0410000011,
  20239. LensSeparationDistance: 0.0635000020,
  20240. InterpupillaryDistance: 0.0640000030,
  20241. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20242. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20243. PostProcessScaleFactor: 1.714605507808412,
  20244. LensCenterOffset: 0.151976421
  20245. };
  20246. var _OculusInnerCamera = (function (_super) {
  20247. __extends(_OculusInnerCamera, _super);
  20248. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20249. _super.call(this, name, position, scene);
  20250. this._workMatrix = new BABYLON.Matrix();
  20251. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20252. // Constants
  20253. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20254. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20255. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20256. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20257. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20258. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20259. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20260. // Postprocess
  20261. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20262. }
  20263. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20264. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20265. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20266. return this._projectionMatrix;
  20267. };
  20268. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20269. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20270. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20271. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20272. // Computing target and final matrix
  20273. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20274. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20275. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20276. return this._viewMatrix;
  20277. };
  20278. return _OculusInnerCamera;
  20279. })(BABYLON.FreeCamera);
  20280. var OculusCamera = (function (_super) {
  20281. __extends(OculusCamera, _super);
  20282. function OculusCamera(name, position, scene) {
  20283. _super.call(this, name, position, scene);
  20284. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20285. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20286. this.subCameras.push(this._leftCamera);
  20287. this.subCameras.push(this._rightCamera);
  20288. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20289. }
  20290. OculusCamera.prototype._update = function () {
  20291. this._leftCamera.position.copyFrom(this.position);
  20292. this._rightCamera.position.copyFrom(this.position);
  20293. this._updateCamera(this._leftCamera);
  20294. this._updateCamera(this._rightCamera);
  20295. _super.prototype._update.call(this);
  20296. };
  20297. OculusCamera.prototype._updateCamera = function (camera) {
  20298. camera.minZ = this.minZ;
  20299. camera.maxZ = this.maxZ;
  20300. camera.rotation.x = this.rotation.x;
  20301. camera.rotation.y = this.rotation.y;
  20302. camera.rotation.z = this.rotation.z;
  20303. };
  20304. // Oculus events
  20305. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20306. var yaw = evt.alpha / 180 * Math.PI;
  20307. var pitch = evt.beta / 180 * Math.PI;
  20308. var roll = evt.gamma / 180 * Math.PI;
  20309. if (!this._offsetOrientation) {
  20310. this._offsetOrientation = {
  20311. yaw: yaw,
  20312. pitch: pitch,
  20313. roll: roll
  20314. };
  20315. return;
  20316. }
  20317. else {
  20318. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20319. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20320. this.rotation.z += this._offsetOrientation.roll - roll;
  20321. this._offsetOrientation.yaw = yaw;
  20322. this._offsetOrientation.pitch = pitch;
  20323. this._offsetOrientation.roll = roll;
  20324. }
  20325. };
  20326. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20327. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20328. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20329. };
  20330. OculusCamera.prototype.detachControl = function (element) {
  20331. _super.prototype.detachControl.call(this, element);
  20332. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20333. };
  20334. return OculusCamera;
  20335. })(BABYLON.FreeCamera);
  20336. BABYLON.OculusCamera = OculusCamera;
  20337. })(BABYLON || (BABYLON = {}));
  20338. //# sourceMappingURL=babylon.oculusCamera.js.map
  20339. var BABYLON;
  20340. (function (BABYLON) {
  20341. var OculusRiftDevKit2013_Metric = {
  20342. HResolution: 1280,
  20343. VResolution: 800,
  20344. HScreenSize: 0.149759993,
  20345. VScreenSize: 0.0935999975,
  20346. VScreenCenter: 0.0467999987,
  20347. EyeToScreenDistance: 0.0410000011,
  20348. LensSeparationDistance: 0.0635000020,
  20349. InterpupillaryDistance: 0.0640000030,
  20350. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20351. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20352. PostProcessScaleFactor: 1.714605507808412,
  20353. LensCenterOffset: 0.151976421
  20354. };
  20355. var _OculusInnerGamepadCamera = (function (_super) {
  20356. __extends(_OculusInnerGamepadCamera, _super);
  20357. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20358. _super.call(this, name, position, scene);
  20359. this._workMatrix = new BABYLON.Matrix();
  20360. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20361. // Constants
  20362. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20363. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20364. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20365. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20366. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20367. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20368. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20369. // Postprocess
  20370. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20371. }
  20372. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20373. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20374. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20375. return this._projectionMatrix;
  20376. };
  20377. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20378. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20379. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20380. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20381. // Computing target and final matrix
  20382. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20383. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20384. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20385. return this._viewMatrix;
  20386. };
  20387. return _OculusInnerGamepadCamera;
  20388. })(BABYLON.FreeCamera);
  20389. var OculusGamepadCamera = (function (_super) {
  20390. __extends(OculusGamepadCamera, _super);
  20391. function OculusGamepadCamera(name, position, scene) {
  20392. var _this = this;
  20393. _super.call(this, name, position, scene);
  20394. this.angularSensibility = 200;
  20395. this.moveSensibility = 75;
  20396. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20397. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20398. this.subCameras.push(this._leftCamera);
  20399. this.subCameras.push(this._rightCamera);
  20400. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20401. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20402. _this._onNewGameConnected(gamepad);
  20403. });
  20404. }
  20405. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20406. // Only the first gamepad can control the camera
  20407. if (gamepad.index === 0) {
  20408. this._gamepad = gamepad;
  20409. }
  20410. };
  20411. OculusGamepadCamera.prototype._update = function () {
  20412. this._leftCamera.position.copyFrom(this.position);
  20413. this._rightCamera.position.copyFrom(this.position);
  20414. this._updateCamera(this._leftCamera);
  20415. this._updateCamera(this._rightCamera);
  20416. _super.prototype._update.call(this);
  20417. };
  20418. OculusGamepadCamera.prototype._checkInputs = function () {
  20419. if (!this._gamepad) {
  20420. return;
  20421. }
  20422. var LSValues = this._gamepad.leftStick;
  20423. var normalizedLX = LSValues.x / this.moveSensibility;
  20424. var normalizedLY = LSValues.y / this.moveSensibility;
  20425. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20426. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20427. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20428. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20429. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20430. };
  20431. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20432. camera.minZ = this.minZ;
  20433. camera.maxZ = this.maxZ;
  20434. camera.rotation.x = this.rotation.x;
  20435. camera.rotation.y = this.rotation.y;
  20436. camera.rotation.z = this.rotation.z;
  20437. };
  20438. // Oculus events
  20439. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20440. var yaw = evt.alpha / 180 * Math.PI;
  20441. var pitch = evt.beta / 180 * Math.PI;
  20442. var roll = evt.gamma / 180 * Math.PI;
  20443. if (!this._offsetOrientation) {
  20444. this._offsetOrientation = {
  20445. yaw: yaw,
  20446. pitch: pitch,
  20447. roll: roll
  20448. };
  20449. return;
  20450. }
  20451. else {
  20452. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20453. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20454. this.rotation.z += this._offsetOrientation.roll - roll;
  20455. this._offsetOrientation.yaw = yaw;
  20456. this._offsetOrientation.pitch = pitch;
  20457. this._offsetOrientation.roll = roll;
  20458. }
  20459. };
  20460. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20461. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20462. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20463. };
  20464. OculusGamepadCamera.prototype.detachControl = function (element) {
  20465. _super.prototype.detachControl.call(this, element);
  20466. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20467. };
  20468. OculusGamepadCamera.prototype.dispose = function () {
  20469. this._gamepads.dispose();
  20470. _super.prototype.dispose.call(this);
  20471. };
  20472. return OculusGamepadCamera;
  20473. })(BABYLON.FreeCamera);
  20474. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20475. })(BABYLON || (BABYLON = {}));
  20476. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20477. var BABYLON;
  20478. (function (BABYLON) {
  20479. // We're mainly based on the logic defined into the FreeCamera code
  20480. var VirtualJoysticksCamera = (function (_super) {
  20481. __extends(VirtualJoysticksCamera, _super);
  20482. function VirtualJoysticksCamera(name, position, scene) {
  20483. _super.call(this, name, position, scene);
  20484. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20485. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20486. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20487. this._leftjoystick.setJoystickSensibility(0.15);
  20488. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20489. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20490. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20491. this._rightjoystick.reverseUpDown = true;
  20492. this._rightjoystick.setJoystickSensibility(0.05);
  20493. this._rightjoystick.setJoystickColor("yellow");
  20494. }
  20495. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20496. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20497. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20498. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20499. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20500. if (!this._leftjoystick.pressed) {
  20501. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20502. }
  20503. if (!this._rightjoystick.pressed) {
  20504. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20505. }
  20506. };
  20507. VirtualJoysticksCamera.prototype.dispose = function () {
  20508. this._leftjoystick.releaseCanvas();
  20509. _super.prototype.dispose.call(this);
  20510. };
  20511. return VirtualJoysticksCamera;
  20512. })(BABYLON.FreeCamera);
  20513. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20514. })(BABYLON || (BABYLON = {}));
  20515. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20516. var BABYLON;
  20517. (function (BABYLON) {
  20518. var ShaderMaterial = (function (_super) {
  20519. __extends(ShaderMaterial, _super);
  20520. function ShaderMaterial(name, scene, shaderPath, options) {
  20521. _super.call(this, name, scene);
  20522. this._textures = new Array();
  20523. this._floats = new Array();
  20524. this._floatsArrays = {};
  20525. this._colors3 = new Array();
  20526. this._colors4 = new Array();
  20527. this._vectors2 = new Array();
  20528. this._vectors3 = new Array();
  20529. this._matrices = new Array();
  20530. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20531. this._shaderPath = shaderPath;
  20532. options.needAlphaBlending = options.needAlphaBlending || false;
  20533. options.needAlphaTesting = options.needAlphaTesting || false;
  20534. options.attributes = options.attributes || ["position", "normal", "uv"];
  20535. options.uniforms = options.uniforms || ["worldViewProjection"];
  20536. options.samplers = options.samplers || [];
  20537. this._options = options;
  20538. }
  20539. ShaderMaterial.prototype.needAlphaBlending = function () {
  20540. return this._options.needAlphaBlending;
  20541. };
  20542. ShaderMaterial.prototype.needAlphaTesting = function () {
  20543. return this._options.needAlphaTesting;
  20544. };
  20545. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20546. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20547. this._options.uniforms.push(uniformName);
  20548. }
  20549. };
  20550. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20551. if (this._options.samplers.indexOf(name) === -1) {
  20552. this._options.samplers.push(name);
  20553. }
  20554. this._textures[name] = texture;
  20555. return this;
  20556. };
  20557. ShaderMaterial.prototype.setFloat = function (name, value) {
  20558. this._checkUniform(name);
  20559. this._floats[name] = value;
  20560. return this;
  20561. };
  20562. ShaderMaterial.prototype.setFloats = function (name, value) {
  20563. this._checkUniform(name);
  20564. this._floatsArrays[name] = value;
  20565. return this;
  20566. };
  20567. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20568. this._checkUniform(name);
  20569. this._colors3[name] = value;
  20570. return this;
  20571. };
  20572. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20573. this._checkUniform(name);
  20574. this._colors4[name] = value;
  20575. return this;
  20576. };
  20577. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20578. this._checkUniform(name);
  20579. this._vectors2[name] = value;
  20580. return this;
  20581. };
  20582. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20583. this._checkUniform(name);
  20584. this._vectors3[name] = value;
  20585. return this;
  20586. };
  20587. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20588. this._checkUniform(name);
  20589. this._matrices[name] = value;
  20590. return this;
  20591. };
  20592. ShaderMaterial.prototype.isReady = function () {
  20593. var scene = this.getScene();
  20594. var engine = scene.getEngine();
  20595. if (!this.checkReadyOnEveryCall) {
  20596. if (this._renderId === scene.getRenderId()) {
  20597. return true;
  20598. }
  20599. }
  20600. var previousEffect = this._effect;
  20601. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20602. if (!this._effect.isReady()) {
  20603. return false;
  20604. }
  20605. if (previousEffect !== this._effect) {
  20606. scene.resetCachedMaterial();
  20607. }
  20608. this._renderId = scene.getRenderId();
  20609. return true;
  20610. };
  20611. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20612. var scene = this.getScene();
  20613. if (this._options.uniforms.indexOf("world") !== -1) {
  20614. this._effect.setMatrix("world", world);
  20615. }
  20616. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20617. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20618. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20619. }
  20620. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20621. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20622. }
  20623. };
  20624. ShaderMaterial.prototype.bind = function (world) {
  20625. // Std values
  20626. this.bindOnlyWorldMatrix(world);
  20627. if (this.getScene().getCachedMaterial() !== this) {
  20628. if (this._options.uniforms.indexOf("view") !== -1) {
  20629. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20630. }
  20631. if (this._options.uniforms.indexOf("projection") !== -1) {
  20632. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20633. }
  20634. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20635. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20636. }
  20637. for (var name in this._textures) {
  20638. this._effect.setTexture(name, this._textures[name]);
  20639. }
  20640. for (name in this._floats) {
  20641. this._effect.setFloat(name, this._floats[name]);
  20642. }
  20643. for (name in this._floatsArrays) {
  20644. this._effect.setArray(name, this._floatsArrays[name]);
  20645. }
  20646. for (name in this._colors3) {
  20647. this._effect.setColor3(name, this._colors3[name]);
  20648. }
  20649. for (name in this._colors4) {
  20650. var color = this._colors4[name];
  20651. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20652. }
  20653. for (name in this._vectors2) {
  20654. this._effect.setVector2(name, this._vectors2[name]);
  20655. }
  20656. for (name in this._vectors3) {
  20657. this._effect.setVector3(name, this._vectors3[name]);
  20658. }
  20659. for (name in this._matrices) {
  20660. this._effect.setMatrix(name, this._matrices[name]);
  20661. }
  20662. }
  20663. _super.prototype.bind.call(this, world, null);
  20664. };
  20665. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20666. for (var name in this._textures) {
  20667. this._textures[name].dispose();
  20668. }
  20669. this._textures = [];
  20670. _super.prototype.dispose.call(this, forceDisposeEffect);
  20671. };
  20672. return ShaderMaterial;
  20673. })(BABYLON.Material);
  20674. BABYLON.ShaderMaterial = ShaderMaterial;
  20675. })(BABYLON || (BABYLON = {}));
  20676. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20677. (function (BABYLON) {
  20678. var VertexData = (function () {
  20679. function VertexData() {
  20680. }
  20681. VertexData.prototype.set = function (data, kind) {
  20682. switch (kind) {
  20683. case BABYLON.VertexBuffer.PositionKind:
  20684. this.positions = data;
  20685. break;
  20686. case BABYLON.VertexBuffer.NormalKind:
  20687. this.normals = data;
  20688. break;
  20689. case BABYLON.VertexBuffer.UVKind:
  20690. this.uvs = data;
  20691. break;
  20692. case BABYLON.VertexBuffer.UV2Kind:
  20693. this.uv2s = data;
  20694. break;
  20695. case BABYLON.VertexBuffer.ColorKind:
  20696. this.colors = data;
  20697. break;
  20698. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20699. this.matricesIndices = data;
  20700. break;
  20701. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20702. this.matricesWeights = data;
  20703. break;
  20704. }
  20705. };
  20706. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20707. this._applyTo(mesh, updatable);
  20708. };
  20709. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20710. this._applyTo(geometry, updatable);
  20711. };
  20712. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20713. this._update(mesh);
  20714. };
  20715. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20716. this._update(geometry);
  20717. };
  20718. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20719. if (this.positions) {
  20720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20721. }
  20722. if (this.normals) {
  20723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20724. }
  20725. if (this.uvs) {
  20726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20727. }
  20728. if (this.uv2s) {
  20729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20730. }
  20731. if (this.colors) {
  20732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20733. }
  20734. if (this.matricesIndices) {
  20735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20736. }
  20737. if (this.matricesWeights) {
  20738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20739. }
  20740. if (this.indices) {
  20741. meshOrGeometry.setIndices(this.indices);
  20742. }
  20743. };
  20744. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20745. if (this.positions) {
  20746. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20747. }
  20748. if (this.normals) {
  20749. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20750. }
  20751. if (this.uvs) {
  20752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20753. }
  20754. if (this.uv2s) {
  20755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20756. }
  20757. if (this.colors) {
  20758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20759. }
  20760. if (this.matricesIndices) {
  20761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20762. }
  20763. if (this.matricesWeights) {
  20764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20765. }
  20766. if (this.indices) {
  20767. meshOrGeometry.setIndices(this.indices);
  20768. }
  20769. };
  20770. VertexData.prototype.transform = function (matrix) {
  20771. var transformed = BABYLON.Vector3.Zero();
  20772. if (this.positions) {
  20773. var position = BABYLON.Vector3.Zero();
  20774. for (var index = 0; index < this.positions.length; index += 3) {
  20775. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20776. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20777. this.positions[index] = transformed.x;
  20778. this.positions[index + 1] = transformed.y;
  20779. this.positions[index + 2] = transformed.z;
  20780. }
  20781. }
  20782. if (this.normals) {
  20783. var normal = BABYLON.Vector3.Zero();
  20784. for (index = 0; index < this.normals.length; index += 3) {
  20785. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20786. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20787. this.normals[index] = transformed.x;
  20788. this.normals[index + 1] = transformed.y;
  20789. this.normals[index + 2] = transformed.z;
  20790. }
  20791. }
  20792. };
  20793. VertexData.prototype.merge = function (other) {
  20794. if (other.indices) {
  20795. if (!this.indices) {
  20796. this.indices = [];
  20797. }
  20798. var offset = this.positions ? this.positions.length / 3 : 0;
  20799. for (var index = 0; index < other.indices.length; index++) {
  20800. this.indices.push(other.indices[index] + offset);
  20801. }
  20802. }
  20803. if (other.positions) {
  20804. if (!this.positions) {
  20805. this.positions = [];
  20806. }
  20807. for (index = 0; index < other.positions.length; index++) {
  20808. this.positions.push(other.positions[index]);
  20809. }
  20810. }
  20811. if (other.normals) {
  20812. if (!this.normals) {
  20813. this.normals = [];
  20814. }
  20815. for (index = 0; index < other.normals.length; index++) {
  20816. this.normals.push(other.normals[index]);
  20817. }
  20818. }
  20819. if (other.uvs) {
  20820. if (!this.uvs) {
  20821. this.uvs = [];
  20822. }
  20823. for (index = 0; index < other.uvs.length; index++) {
  20824. this.uvs.push(other.uvs[index]);
  20825. }
  20826. }
  20827. if (other.uv2s) {
  20828. if (!this.uv2s) {
  20829. this.uv2s = [];
  20830. }
  20831. for (index = 0; index < other.uv2s.length; index++) {
  20832. this.uv2s.push(other.uv2s[index]);
  20833. }
  20834. }
  20835. if (other.matricesIndices) {
  20836. if (!this.matricesIndices) {
  20837. this.matricesIndices = [];
  20838. }
  20839. for (index = 0; index < other.matricesIndices.length; index++) {
  20840. this.matricesIndices.push(other.matricesIndices[index]);
  20841. }
  20842. }
  20843. if (other.matricesWeights) {
  20844. if (!this.matricesWeights) {
  20845. this.matricesWeights = [];
  20846. }
  20847. for (index = 0; index < other.matricesWeights.length; index++) {
  20848. this.matricesWeights.push(other.matricesWeights[index]);
  20849. }
  20850. }
  20851. if (other.colors) {
  20852. if (!this.colors) {
  20853. this.colors = [];
  20854. }
  20855. for (index = 0; index < other.colors.length; index++) {
  20856. this.colors.push(other.colors[index]);
  20857. }
  20858. }
  20859. };
  20860. // Statics
  20861. VertexData.ExtractFromMesh = function (mesh) {
  20862. return VertexData._ExtractFrom(mesh);
  20863. };
  20864. VertexData.ExtractFromGeometry = function (geometry) {
  20865. return VertexData._ExtractFrom(geometry);
  20866. };
  20867. VertexData._ExtractFrom = function (meshOrGeometry) {
  20868. var result = new BABYLON.VertexData();
  20869. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20870. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20871. }
  20872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20873. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20874. }
  20875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20876. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20877. }
  20878. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20879. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20880. }
  20881. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20882. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20883. }
  20884. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20885. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20886. }
  20887. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20888. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20889. }
  20890. result.indices = meshOrGeometry.getIndices();
  20891. return result;
  20892. };
  20893. VertexData.CreateBox = function (size) {
  20894. var normalsSource = [
  20895. new BABYLON.Vector3(0, 0, 1),
  20896. new BABYLON.Vector3(0, 0, -1),
  20897. new BABYLON.Vector3(1, 0, 0),
  20898. new BABYLON.Vector3(-1, 0, 0),
  20899. new BABYLON.Vector3(0, 1, 0),
  20900. new BABYLON.Vector3(0, -1, 0)
  20901. ];
  20902. var indices = [];
  20903. var positions = [];
  20904. var normals = [];
  20905. var uvs = [];
  20906. size = size || 1;
  20907. for (var index = 0; index < normalsSource.length; index++) {
  20908. var normal = normalsSource[index];
  20909. // Get two vectors perpendicular to the face normal and to each other.
  20910. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20911. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20912. // Six indices (two triangles) per face.
  20913. var verticesLength = positions.length / 3;
  20914. indices.push(verticesLength);
  20915. indices.push(verticesLength + 1);
  20916. indices.push(verticesLength + 2);
  20917. indices.push(verticesLength);
  20918. indices.push(verticesLength + 2);
  20919. indices.push(verticesLength + 3);
  20920. // Four vertices per face.
  20921. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20922. positions.push(vertex.x, vertex.y, vertex.z);
  20923. normals.push(normal.x, normal.y, normal.z);
  20924. uvs.push(1.0, 1.0);
  20925. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20926. positions.push(vertex.x, vertex.y, vertex.z);
  20927. normals.push(normal.x, normal.y, normal.z);
  20928. uvs.push(0.0, 1.0);
  20929. vertex = normal.add(side1).add(side2).scale(size / 2);
  20930. positions.push(vertex.x, vertex.y, vertex.z);
  20931. normals.push(normal.x, normal.y, normal.z);
  20932. uvs.push(0.0, 0.0);
  20933. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20934. positions.push(vertex.x, vertex.y, vertex.z);
  20935. normals.push(normal.x, normal.y, normal.z);
  20936. uvs.push(1.0, 0.0);
  20937. }
  20938. // Result
  20939. var vertexData = new BABYLON.VertexData();
  20940. vertexData.indices = indices;
  20941. vertexData.positions = positions;
  20942. vertexData.normals = normals;
  20943. vertexData.uvs = uvs;
  20944. return vertexData;
  20945. };
  20946. VertexData.CreateSphere = function (segments, diameter) {
  20947. segments = segments || 32;
  20948. diameter = diameter || 1;
  20949. var radius = diameter / 2;
  20950. var totalZRotationSteps = 2 + segments;
  20951. var totalYRotationSteps = 2 * totalZRotationSteps;
  20952. var indices = [];
  20953. var positions = [];
  20954. var normals = [];
  20955. var uvs = [];
  20956. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20957. var normalizedZ = zRotationStep / totalZRotationSteps;
  20958. var angleZ = (normalizedZ * Math.PI);
  20959. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20960. var normalizedY = yRotationStep / totalYRotationSteps;
  20961. var angleY = normalizedY * Math.PI * 2;
  20962. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20963. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20964. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20965. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20966. var vertex = complete.scale(radius);
  20967. var normal = BABYLON.Vector3.Normalize(vertex);
  20968. positions.push(vertex.x, vertex.y, vertex.z);
  20969. normals.push(normal.x, normal.y, normal.z);
  20970. uvs.push(normalizedZ, normalizedY);
  20971. }
  20972. if (zRotationStep > 0) {
  20973. var verticesCount = positions.length / 3;
  20974. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20975. indices.push((firstIndex));
  20976. indices.push((firstIndex + 1));
  20977. indices.push(firstIndex + totalYRotationSteps + 1);
  20978. indices.push((firstIndex + totalYRotationSteps + 1));
  20979. indices.push((firstIndex + 1));
  20980. indices.push((firstIndex + totalYRotationSteps + 2));
  20981. }
  20982. }
  20983. }
  20984. // Result
  20985. var vertexData = new BABYLON.VertexData();
  20986. vertexData.indices = indices;
  20987. vertexData.positions = positions;
  20988. vertexData.normals = normals;
  20989. vertexData.uvs = uvs;
  20990. return vertexData;
  20991. };
  20992. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20993. if (subdivisions === void 0) { subdivisions = 1; }
  20994. var radiusTop = diameterTop / 2;
  20995. var radiusBottom = diameterBottom / 2;
  20996. var indices = [];
  20997. var positions = [];
  20998. var normals = [];
  20999. var uvs = [];
  21000. height = height || 1;
  21001. diameterTop = diameterTop || 0.5;
  21002. diameterBottom = diameterBottom || 1;
  21003. tessellation = tessellation || 16;
  21004. subdivisions = subdivisions || 1;
  21005. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21006. var getCircleVector = function (i) {
  21007. var angle = (i * 2.0 * Math.PI / tessellation);
  21008. var dx = Math.cos(angle);
  21009. var dz = Math.sin(angle);
  21010. return new BABYLON.Vector3(dx, 0, dz);
  21011. };
  21012. var createCylinderCap = function (isTop) {
  21013. var radius = isTop ? radiusTop : radiusBottom;
  21014. if (radius == 0) {
  21015. return;
  21016. }
  21017. var vbase = positions.length / 3;
  21018. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21019. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21020. if (!isTop) {
  21021. offset.scaleInPlace(-1);
  21022. textureScale.x = -textureScale.x;
  21023. }
  21024. for (i = 0; i < tessellation; i++) {
  21025. var circleVector = getCircleVector(i);
  21026. var position = circleVector.scale(radius).add(offset);
  21027. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21028. positions.push(position.x, position.y, position.z);
  21029. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21030. }
  21031. for (var i = 0; i < tessellation - 2; i++) {
  21032. if (!isTop) {
  21033. indices.push(vbase);
  21034. indices.push(vbase + (i + 2) % tessellation);
  21035. indices.push(vbase + (i + 1) % tessellation);
  21036. }
  21037. else {
  21038. indices.push(vbase);
  21039. indices.push(vbase + (i + 1) % tessellation);
  21040. indices.push(vbase + (i + 2) % tessellation);
  21041. }
  21042. }
  21043. };
  21044. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21045. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21046. var stride = tessellation + 1;
  21047. for (var i = 0; i <= tessellation; i++) {
  21048. var circleVector = getCircleVector(i);
  21049. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21050. var position, radius = radiusBottom;
  21051. for (var s = 0; s <= subdivisions; s++) {
  21052. // Update variables
  21053. position = circleVector.scale(radius);
  21054. position.addInPlace(base.add(offset.scale(s)));
  21055. textureCoordinate.y += 1 / subdivisions;
  21056. radius += (radiusTop - radiusBottom) / subdivisions;
  21057. // Push in arrays
  21058. positions.push(position.x, position.y, position.z);
  21059. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21060. }
  21061. }
  21062. subdivisions += 1;
  21063. for (var s = 0; s < subdivisions - 1; s++) {
  21064. for (var i = 0; i <= tessellation; i++) {
  21065. indices.push(i * subdivisions + s);
  21066. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21067. indices.push(i * subdivisions + (s + 1));
  21068. indices.push(i * subdivisions + (s + 1));
  21069. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21070. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21071. }
  21072. }
  21073. // Create flat triangle fan caps to seal the top and bottom.
  21074. createCylinderCap(true);
  21075. createCylinderCap(false);
  21076. // Normals
  21077. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21078. // Result
  21079. var vertexData = new BABYLON.VertexData();
  21080. vertexData.indices = indices;
  21081. vertexData.positions = positions;
  21082. vertexData.normals = normals;
  21083. vertexData.uvs = uvs;
  21084. return vertexData;
  21085. };
  21086. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  21087. var indices = [];
  21088. var positions = [];
  21089. var normals = [];
  21090. var uvs = [];
  21091. diameter = diameter || 1;
  21092. thickness = thickness || 0.5;
  21093. tessellation = tessellation || 16;
  21094. var stride = tessellation + 1;
  21095. for (var i = 0; i <= tessellation; i++) {
  21096. var u = i / tessellation;
  21097. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21098. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21099. for (var j = 0; j <= tessellation; j++) {
  21100. var v = 1 - j / tessellation;
  21101. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21102. var dx = Math.cos(innerAngle);
  21103. var dy = Math.sin(innerAngle);
  21104. // Create a vertex.
  21105. var normal = new BABYLON.Vector3(dx, dy, 0);
  21106. var position = normal.scale(thickness / 2);
  21107. var textureCoordinate = new BABYLON.Vector2(u, v);
  21108. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21109. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21110. positions.push(position.x, position.y, position.z);
  21111. normals.push(normal.x, normal.y, normal.z);
  21112. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21113. // And create indices for two triangles.
  21114. var nextI = (i + 1) % stride;
  21115. var nextJ = (j + 1) % stride;
  21116. indices.push(i * stride + j);
  21117. indices.push(i * stride + nextJ);
  21118. indices.push(nextI * stride + j);
  21119. indices.push(i * stride + nextJ);
  21120. indices.push(nextI * stride + nextJ);
  21121. indices.push(nextI * stride + j);
  21122. }
  21123. }
  21124. // Result
  21125. var vertexData = new BABYLON.VertexData();
  21126. vertexData.indices = indices;
  21127. vertexData.positions = positions;
  21128. vertexData.normals = normals;
  21129. vertexData.uvs = uvs;
  21130. return vertexData;
  21131. };
  21132. VertexData.CreateLines = function (points) {
  21133. var indices = [];
  21134. var positions = [];
  21135. for (var index = 0; index < points.length; index++) {
  21136. positions.push(points[index].x, points[index].y, points[index].z);
  21137. if (index > 0) {
  21138. indices.push(index - 1);
  21139. indices.push(index);
  21140. }
  21141. }
  21142. // Result
  21143. var vertexData = new BABYLON.VertexData();
  21144. vertexData.indices = indices;
  21145. vertexData.positions = positions;
  21146. return vertexData;
  21147. };
  21148. VertexData.CreateGround = function (width, height, subdivisions) {
  21149. var indices = [];
  21150. var positions = [];
  21151. var normals = [];
  21152. var uvs = [];
  21153. var row, col;
  21154. width = width || 1;
  21155. height = height || 1;
  21156. subdivisions = subdivisions || 1;
  21157. for (row = 0; row <= subdivisions; row++) {
  21158. for (col = 0; col <= subdivisions; col++) {
  21159. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21160. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21161. positions.push(position.x, position.y, position.z);
  21162. normals.push(normal.x, normal.y, normal.z);
  21163. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21164. }
  21165. }
  21166. for (row = 0; row < subdivisions; row++) {
  21167. for (col = 0; col < subdivisions; col++) {
  21168. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21169. indices.push(col + 1 + row * (subdivisions + 1));
  21170. indices.push(col + row * (subdivisions + 1));
  21171. indices.push(col + (row + 1) * (subdivisions + 1));
  21172. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21173. indices.push(col + row * (subdivisions + 1));
  21174. }
  21175. }
  21176. // Result
  21177. var vertexData = new BABYLON.VertexData();
  21178. vertexData.indices = indices;
  21179. vertexData.positions = positions;
  21180. vertexData.normals = normals;
  21181. vertexData.uvs = uvs;
  21182. return vertexData;
  21183. };
  21184. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21185. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21186. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21187. var indices = [];
  21188. var positions = [];
  21189. var normals = [];
  21190. var uvs = [];
  21191. var row, col, tileRow, tileCol;
  21192. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21193. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21194. precision.w = (precision.w < 1) ? 1 : precision.w;
  21195. precision.h = (precision.h < 1) ? 1 : precision.h;
  21196. var tileSize = {
  21197. 'w': (xmax - xmin) / subdivisions.w,
  21198. 'h': (zmax - zmin) / subdivisions.h
  21199. };
  21200. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21201. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21202. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21203. }
  21204. }
  21205. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21206. // Indices
  21207. var base = positions.length / 3;
  21208. var rowLength = precision.w + 1;
  21209. for (row = 0; row < precision.h; row++) {
  21210. for (col = 0; col < precision.w; col++) {
  21211. var square = [
  21212. base + col + row * rowLength,
  21213. base + (col + 1) + row * rowLength,
  21214. base + (col + 1) + (row + 1) * rowLength,
  21215. base + col + (row + 1) * rowLength
  21216. ];
  21217. indices.push(square[1]);
  21218. indices.push(square[2]);
  21219. indices.push(square[3]);
  21220. indices.push(square[0]);
  21221. indices.push(square[1]);
  21222. indices.push(square[3]);
  21223. }
  21224. }
  21225. // Position, normals and uvs
  21226. var position = BABYLON.Vector3.Zero();
  21227. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21228. for (row = 0; row <= precision.h; row++) {
  21229. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21230. for (col = 0; col <= precision.w; col++) {
  21231. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21232. position.y = 0;
  21233. positions.push(position.x, position.y, position.z);
  21234. normals.push(normal.x, normal.y, normal.z);
  21235. uvs.push(col / precision.w, row / precision.h);
  21236. }
  21237. }
  21238. }
  21239. // Result
  21240. var vertexData = new BABYLON.VertexData();
  21241. vertexData.indices = indices;
  21242. vertexData.positions = positions;
  21243. vertexData.normals = normals;
  21244. vertexData.uvs = uvs;
  21245. return vertexData;
  21246. };
  21247. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21248. var indices = [];
  21249. var positions = [];
  21250. var normals = [];
  21251. var uvs = [];
  21252. var row, col;
  21253. for (row = 0; row <= subdivisions; row++) {
  21254. for (col = 0; col <= subdivisions; col++) {
  21255. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21256. // Compute height
  21257. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21258. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21259. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21260. var r = buffer[pos] / 255.0;
  21261. var g = buffer[pos + 1] / 255.0;
  21262. var b = buffer[pos + 2] / 255.0;
  21263. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21264. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21265. // Add vertex
  21266. positions.push(position.x, position.y, position.z);
  21267. normals.push(0, 0, 0);
  21268. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21269. }
  21270. }
  21271. for (row = 0; row < subdivisions; row++) {
  21272. for (col = 0; col < subdivisions; col++) {
  21273. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21274. indices.push(col + 1 + row * (subdivisions + 1));
  21275. indices.push(col + row * (subdivisions + 1));
  21276. indices.push(col + (row + 1) * (subdivisions + 1));
  21277. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21278. indices.push(col + row * (subdivisions + 1));
  21279. }
  21280. }
  21281. // Normals
  21282. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21283. // Result
  21284. var vertexData = new BABYLON.VertexData();
  21285. vertexData.indices = indices;
  21286. vertexData.positions = positions;
  21287. vertexData.normals = normals;
  21288. vertexData.uvs = uvs;
  21289. return vertexData;
  21290. };
  21291. VertexData.CreatePlane = function (size) {
  21292. var indices = [];
  21293. var positions = [];
  21294. var normals = [];
  21295. var uvs = [];
  21296. size = size || 1;
  21297. // Vertices
  21298. var halfSize = size / 2.0;
  21299. positions.push(-halfSize, -halfSize, 0);
  21300. normals.push(0, 0, -1.0);
  21301. uvs.push(0.0, 0.0);
  21302. positions.push(halfSize, -halfSize, 0);
  21303. normals.push(0, 0, -1.0);
  21304. uvs.push(1.0, 0.0);
  21305. positions.push(halfSize, halfSize, 0);
  21306. normals.push(0, 0, -1.0);
  21307. uvs.push(1.0, 1.0);
  21308. positions.push(-halfSize, halfSize, 0);
  21309. normals.push(0, 0, -1.0);
  21310. uvs.push(0.0, 1.0);
  21311. // Indices
  21312. indices.push(0);
  21313. indices.push(1);
  21314. indices.push(2);
  21315. indices.push(0);
  21316. indices.push(2);
  21317. indices.push(3);
  21318. // Result
  21319. var vertexData = new BABYLON.VertexData();
  21320. vertexData.indices = indices;
  21321. vertexData.positions = positions;
  21322. vertexData.normals = normals;
  21323. vertexData.uvs = uvs;
  21324. return vertexData;
  21325. };
  21326. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21327. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21328. var indices = [];
  21329. var positions = [];
  21330. var normals = [];
  21331. var uvs = [];
  21332. radius = radius || 2;
  21333. tube = tube || 0.5;
  21334. radialSegments = radialSegments || 32;
  21335. tubularSegments = tubularSegments || 32;
  21336. p = p || 2;
  21337. q = q || 3;
  21338. // Helper
  21339. var getPos = function (angle) {
  21340. var cu = Math.cos(angle);
  21341. var su = Math.sin(angle);
  21342. var quOverP = q / p * angle;
  21343. var cs = Math.cos(quOverP);
  21344. var tx = radius * (2 + cs) * 0.5 * cu;
  21345. var ty = radius * (2 + cs) * su * 0.5;
  21346. var tz = radius * Math.sin(quOverP) * 0.5;
  21347. return new BABYLON.Vector3(tx, ty, tz);
  21348. };
  21349. for (var i = 0; i <= radialSegments; i++) {
  21350. var modI = i % radialSegments;
  21351. var u = modI / radialSegments * 2 * p * Math.PI;
  21352. var p1 = getPos(u);
  21353. var p2 = getPos(u + 0.01);
  21354. var tang = p2.subtract(p1);
  21355. var n = p2.add(p1);
  21356. var bitan = BABYLON.Vector3.Cross(tang, n);
  21357. n = BABYLON.Vector3.Cross(bitan, tang);
  21358. bitan.normalize();
  21359. n.normalize();
  21360. for (var j = 0; j < tubularSegments; j++) {
  21361. var modJ = j % tubularSegments;
  21362. var v = modJ / tubularSegments * 2 * Math.PI;
  21363. var cx = -tube * Math.cos(v);
  21364. var cy = tube * Math.sin(v);
  21365. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21366. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21367. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21368. uvs.push(i / radialSegments);
  21369. uvs.push(j / tubularSegments);
  21370. }
  21371. }
  21372. for (i = 0; i < radialSegments; i++) {
  21373. for (j = 0; j < tubularSegments; j++) {
  21374. var jNext = (j + 1) % tubularSegments;
  21375. var a = i * tubularSegments + j;
  21376. var b = (i + 1) * tubularSegments + j;
  21377. var c = (i + 1) * tubularSegments + jNext;
  21378. var d = i * tubularSegments + jNext;
  21379. indices.push(d);
  21380. indices.push(b);
  21381. indices.push(a);
  21382. indices.push(d);
  21383. indices.push(c);
  21384. indices.push(b);
  21385. }
  21386. }
  21387. // Normals
  21388. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21389. // Result
  21390. var vertexData = new BABYLON.VertexData();
  21391. vertexData.indices = indices;
  21392. vertexData.positions = positions;
  21393. vertexData.normals = normals;
  21394. vertexData.uvs = uvs;
  21395. return vertexData;
  21396. };
  21397. // Tools
  21398. VertexData.ComputeNormals = function (positions, indices, normals) {
  21399. var positionVectors = [];
  21400. var facesOfVertices = [];
  21401. var index;
  21402. for (index = 0; index < positions.length; index += 3) {
  21403. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21404. positionVectors.push(vector3);
  21405. facesOfVertices.push([]);
  21406. }
  21407. // Compute normals
  21408. var facesNormals = [];
  21409. for (index = 0; index < indices.length / 3; index++) {
  21410. var i1 = indices[index * 3];
  21411. var i2 = indices[index * 3 + 1];
  21412. var i3 = indices[index * 3 + 2];
  21413. var p1 = positionVectors[i1];
  21414. var p2 = positionVectors[i2];
  21415. var p3 = positionVectors[i3];
  21416. var p1p2 = p1.subtract(p2);
  21417. var p3p2 = p3.subtract(p2);
  21418. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21419. facesOfVertices[i1].push(index);
  21420. facesOfVertices[i2].push(index);
  21421. facesOfVertices[i3].push(index);
  21422. }
  21423. for (index = 0; index < positionVectors.length; index++) {
  21424. var faces = facesOfVertices[index];
  21425. var normal = BABYLON.Vector3.Zero();
  21426. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21427. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21428. }
  21429. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21430. normals[index * 3] = normal.x;
  21431. normals[index * 3 + 1] = normal.y;
  21432. normals[index * 3 + 2] = normal.z;
  21433. }
  21434. };
  21435. return VertexData;
  21436. })();
  21437. BABYLON.VertexData = VertexData;
  21438. })(BABYLON || (BABYLON = {}));
  21439. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21440. var BABYLON;
  21441. (function (BABYLON) {
  21442. var buildCamera = function (that, name) {
  21443. that._leftCamera.isIntermediate = true;
  21444. that.subCameras.push(that._leftCamera);
  21445. that.subCameras.push(that._rightCamera);
  21446. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21447. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21448. that._anaglyphPostProcess.onApply = function (effect) {
  21449. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21450. };
  21451. that._update();
  21452. };
  21453. var AnaglyphArcRotateCamera = (function (_super) {
  21454. __extends(AnaglyphArcRotateCamera, _super);
  21455. // ANY
  21456. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21457. _super.call(this, name, alpha, beta, radius, target, scene);
  21458. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21459. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21460. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21461. buildCamera(this, name);
  21462. }
  21463. AnaglyphArcRotateCamera.prototype._update = function () {
  21464. this._updateCamera(this._leftCamera);
  21465. this._updateCamera(this._rightCamera);
  21466. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21467. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21468. _super.prototype._update.call(this);
  21469. };
  21470. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21471. camera.beta = this.beta;
  21472. camera.radius = this.radius;
  21473. camera.minZ = this.minZ;
  21474. camera.maxZ = this.maxZ;
  21475. camera.fov = this.fov;
  21476. camera.target = this.target;
  21477. };
  21478. return AnaglyphArcRotateCamera;
  21479. })(BABYLON.ArcRotateCamera);
  21480. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21481. var AnaglyphFreeCamera = (function (_super) {
  21482. __extends(AnaglyphFreeCamera, _super);
  21483. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21484. _super.call(this, name, position, scene);
  21485. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21486. this._transformMatrix = new BABYLON.Matrix();
  21487. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21488. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21489. buildCamera(this, name);
  21490. }
  21491. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21492. var target = this.getTarget();
  21493. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21494. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21495. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21496. };
  21497. AnaglyphFreeCamera.prototype._update = function () {
  21498. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21499. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21500. this._updateCamera(this._leftCamera);
  21501. this._updateCamera(this._rightCamera);
  21502. _super.prototype._update.call(this);
  21503. };
  21504. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21505. camera.minZ = this.minZ;
  21506. camera.maxZ = this.maxZ;
  21507. camera.fov = this.fov;
  21508. camera.viewport = this.viewport;
  21509. camera.setTarget(this.getTarget());
  21510. };
  21511. return AnaglyphFreeCamera;
  21512. })(BABYLON.FreeCamera);
  21513. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21514. })(BABYLON || (BABYLON = {}));
  21515. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21516. var BABYLON;
  21517. (function (BABYLON) {
  21518. var AnaglyphPostProcess = (function (_super) {
  21519. __extends(AnaglyphPostProcess, _super);
  21520. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21521. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21522. }
  21523. return AnaglyphPostProcess;
  21524. })(BABYLON.PostProcess);
  21525. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21526. })(BABYLON || (BABYLON = {}));
  21527. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21528. (function (BABYLON) {
  21529. var Tags = (function () {
  21530. function Tags() {
  21531. }
  21532. Tags.EnableFor = function (obj) {
  21533. obj._tags = obj._tags || {};
  21534. obj.hasTags = function () {
  21535. return Tags.HasTags(obj);
  21536. };
  21537. obj.addTags = function (tagsString) {
  21538. return Tags.AddTagsTo(obj, tagsString);
  21539. };
  21540. obj.removeTags = function (tagsString) {
  21541. return Tags.RemoveTagsFrom(obj, tagsString);
  21542. };
  21543. obj.matchesTagsQuery = function (tagsQuery) {
  21544. return Tags.MatchesQuery(obj, tagsQuery);
  21545. };
  21546. };
  21547. Tags.DisableFor = function (obj) {
  21548. delete obj._tags;
  21549. delete obj.hasTags;
  21550. delete obj.addTags;
  21551. delete obj.removeTags;
  21552. delete obj.matchesTagsQuery;
  21553. };
  21554. Tags.HasTags = function (obj) {
  21555. if (!obj._tags) {
  21556. return false;
  21557. }
  21558. return !BABYLON.Tools.IsEmpty(obj._tags);
  21559. };
  21560. Tags.GetTags = function (obj) {
  21561. if (!obj._tags) {
  21562. return null;
  21563. }
  21564. return obj._tags;
  21565. };
  21566. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21567. // a tag cannot start with '||', '&&', and '!'
  21568. // it cannot contain whitespaces
  21569. Tags.AddTagsTo = function (obj, tagsString) {
  21570. if (!tagsString) {
  21571. return;
  21572. }
  21573. var tags = tagsString.split(" ");
  21574. for (var t in tags) {
  21575. Tags._AddTagTo(obj, tags[t]);
  21576. }
  21577. };
  21578. Tags._AddTagTo = function (obj, tag) {
  21579. tag = tag.trim();
  21580. if (tag === "" || tag === "true" || tag === "false") {
  21581. return;
  21582. }
  21583. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21584. return;
  21585. }
  21586. Tags.EnableFor(obj);
  21587. obj._tags[tag] = true;
  21588. };
  21589. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21590. if (!Tags.HasTags(obj)) {
  21591. return;
  21592. }
  21593. var tags = tagsString.split(" ");
  21594. for (var t in tags) {
  21595. Tags._RemoveTagFrom(obj, tags[t]);
  21596. }
  21597. };
  21598. Tags._RemoveTagFrom = function (obj, tag) {
  21599. delete obj._tags[tag];
  21600. };
  21601. Tags.MatchesQuery = function (obj, tagsQuery) {
  21602. if (tagsQuery === undefined) {
  21603. return true;
  21604. }
  21605. if (tagsQuery === "") {
  21606. return Tags.HasTags(obj);
  21607. }
  21608. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21609. };
  21610. return Tags;
  21611. })();
  21612. BABYLON.Tags = Tags;
  21613. })(BABYLON || (BABYLON = {}));
  21614. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21615. (function (BABYLON) {
  21616. var Internals;
  21617. (function (Internals) {
  21618. var AndOrNotEvaluator = (function () {
  21619. function AndOrNotEvaluator() {
  21620. }
  21621. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21622. if (!query.match(/\([^\(\)]*\)/g)) {
  21623. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21624. }
  21625. else {
  21626. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21627. // remove parenthesis
  21628. r = r.slice(1, r.length - 1);
  21629. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21630. });
  21631. }
  21632. if (query === "true") {
  21633. return true;
  21634. }
  21635. if (query === "false") {
  21636. return false;
  21637. }
  21638. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21639. };
  21640. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21641. evaluateCallback = evaluateCallback || (function (r) {
  21642. return r === "true" ? true : false;
  21643. });
  21644. var result;
  21645. var or = parenthesisContent.split("||");
  21646. for (var i in or) {
  21647. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21648. var and = ori.split("&&");
  21649. if (and.length > 1) {
  21650. for (var j = 0; j < and.length; ++j) {
  21651. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21652. if (andj !== "true" && andj !== "false") {
  21653. if (andj[0] === "!") {
  21654. result = !evaluateCallback(andj.substring(1));
  21655. }
  21656. else {
  21657. result = evaluateCallback(andj);
  21658. }
  21659. }
  21660. else {
  21661. result = andj === "true" ? true : false;
  21662. }
  21663. if (!result) {
  21664. ori = "false";
  21665. break;
  21666. }
  21667. }
  21668. }
  21669. if (result || ori === "true") {
  21670. result = true;
  21671. break;
  21672. }
  21673. // result equals false (or undefined)
  21674. if (ori !== "true" && ori !== "false") {
  21675. if (ori[0] === "!") {
  21676. result = !evaluateCallback(ori.substring(1));
  21677. }
  21678. else {
  21679. result = evaluateCallback(ori);
  21680. }
  21681. }
  21682. else {
  21683. result = ori === "true" ? true : false;
  21684. }
  21685. }
  21686. // the whole parenthesis scope is replaced by 'true' or 'false'
  21687. return result ? "true" : "false";
  21688. };
  21689. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21690. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21691. // remove whitespaces
  21692. r = r.replace(/[\s]/g, function () { return ""; });
  21693. return r.length % 2 ? "!" : "";
  21694. });
  21695. booleanString = booleanString.trim();
  21696. if (booleanString === "!true") {
  21697. booleanString = "false";
  21698. }
  21699. else if (booleanString === "!false") {
  21700. booleanString = "true";
  21701. }
  21702. return booleanString;
  21703. };
  21704. return AndOrNotEvaluator;
  21705. })();
  21706. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21707. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21708. })(BABYLON || (BABYLON = {}));
  21709. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21710. (function (BABYLON) {
  21711. var PostProcessRenderPass = (function () {
  21712. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21713. this._enabled = true;
  21714. this._refCount = 0;
  21715. this._name = name;
  21716. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21717. this.setRenderList(renderList);
  21718. this._renderTexture.onBeforeRender = beforeRender;
  21719. this._renderTexture.onAfterRender = afterRender;
  21720. this._scene = scene;
  21721. this._renderList = renderList;
  21722. }
  21723. // private
  21724. PostProcessRenderPass.prototype._incRefCount = function () {
  21725. if (this._refCount === 0) {
  21726. this._scene.customRenderTargets.push(this._renderTexture);
  21727. }
  21728. return ++this._refCount;
  21729. };
  21730. PostProcessRenderPass.prototype._decRefCount = function () {
  21731. this._refCount--;
  21732. if (this._refCount <= 0) {
  21733. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21734. }
  21735. return this._refCount;
  21736. };
  21737. PostProcessRenderPass.prototype._update = function () {
  21738. this.setRenderList(this._renderList);
  21739. };
  21740. // public
  21741. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21742. this._renderTexture.renderList = renderList;
  21743. };
  21744. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21745. return this._renderTexture;
  21746. };
  21747. return PostProcessRenderPass;
  21748. })();
  21749. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21750. })(BABYLON || (BABYLON = {}));
  21751. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21752. (function (BABYLON) {
  21753. var PostProcessRenderEffect = (function () {
  21754. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21755. this._engine = engine;
  21756. this._name = name;
  21757. this._singleInstance = singleInstance || true;
  21758. this._getPostProcess = getPostProcess;
  21759. this._cameras = [];
  21760. this._indicesForCamera = [];
  21761. this._postProcesses = {};
  21762. this._renderPasses = {};
  21763. this._renderEffectAsPasses = {};
  21764. }
  21765. PostProcessRenderEffect.prototype._update = function () {
  21766. for (var renderPassName in this._renderPasses) {
  21767. this._renderPasses[renderPassName]._update();
  21768. }
  21769. };
  21770. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21771. this._renderPasses[renderPass._name] = renderPass;
  21772. this._linkParameters();
  21773. };
  21774. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21775. delete this._renderPasses[renderPass._name];
  21776. this._linkParameters();
  21777. };
  21778. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21779. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21780. this._linkParameters();
  21781. };
  21782. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21783. for (var renderPassName in this._renderPasses) {
  21784. if (renderPassName === passName) {
  21785. return this._renderPasses[passName];
  21786. }
  21787. }
  21788. };
  21789. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21790. this._renderPasses = {};
  21791. this._linkParameters();
  21792. };
  21793. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21794. var cameraKey;
  21795. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21796. for (var i = 0; i < _cam.length; i++) {
  21797. var camera = _cam[i];
  21798. var cameraName = camera.name;
  21799. if (this._singleInstance) {
  21800. cameraKey = 0;
  21801. }
  21802. else {
  21803. cameraKey = cameraName;
  21804. }
  21805. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21806. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21807. if (!this._indicesForCamera[cameraName]) {
  21808. this._indicesForCamera[cameraName] = [];
  21809. }
  21810. this._indicesForCamera[cameraName].push(index);
  21811. if (this._cameras.indexOf(camera) === -1) {
  21812. this._cameras[cameraName] = camera;
  21813. }
  21814. for (var passName in this._renderPasses) {
  21815. this._renderPasses[passName]._incRefCount();
  21816. }
  21817. }
  21818. this._linkParameters();
  21819. };
  21820. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21821. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21822. for (var i = 0; i < _cam.length; i++) {
  21823. var camera = _cam[i];
  21824. var cameraName = camera.name;
  21825. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21826. var index = this._cameras.indexOf(cameraName);
  21827. this._indicesForCamera.splice(index, 1);
  21828. this._cameras.splice(index, 1);
  21829. for (var passName in this._renderPasses) {
  21830. this._renderPasses[passName]._decRefCount();
  21831. }
  21832. }
  21833. };
  21834. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21835. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21836. for (var i = 0; i < _cam.length; i++) {
  21837. var camera = _cam[i];
  21838. var cameraName = camera.name;
  21839. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21840. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21841. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21842. }
  21843. }
  21844. for (var passName in this._renderPasses) {
  21845. this._renderPasses[passName]._incRefCount();
  21846. }
  21847. }
  21848. };
  21849. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21851. for (var i = 0; i < _cam.length; i++) {
  21852. var camera = _cam[i];
  21853. var cameraName = camera.Name;
  21854. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21855. for (var passName in this._renderPasses) {
  21856. this._renderPasses[passName]._decRefCount();
  21857. }
  21858. }
  21859. };
  21860. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21861. if (this._singleInstance) {
  21862. return this._postProcesses[0];
  21863. }
  21864. else {
  21865. return this._postProcesses[camera.name];
  21866. }
  21867. };
  21868. PostProcessRenderEffect.prototype._linkParameters = function () {
  21869. var _this = this;
  21870. for (var index in this._postProcesses) {
  21871. if (this.applyParameters) {
  21872. this.applyParameters(this._postProcesses[index]);
  21873. }
  21874. this._postProcesses[index].onBeforeRender = function (effect) {
  21875. _this._linkTextures(effect);
  21876. };
  21877. }
  21878. };
  21879. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21880. for (var renderPassName in this._renderPasses) {
  21881. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21882. }
  21883. for (var renderEffectName in this._renderEffectAsPasses) {
  21884. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21885. }
  21886. };
  21887. return PostProcessRenderEffect;
  21888. })();
  21889. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21890. })(BABYLON || (BABYLON = {}));
  21891. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21892. (function (BABYLON) {
  21893. var PostProcessRenderPipeline = (function () {
  21894. function PostProcessRenderPipeline(engine, name) {
  21895. this._engine = engine;
  21896. this._name = name;
  21897. this._renderEffects = {};
  21898. this._renderEffectsForIsolatedPass = {};
  21899. this._cameras = [];
  21900. }
  21901. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21902. this._renderEffects[renderEffect._name] = renderEffect;
  21903. };
  21904. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21905. var renderEffects = this._renderEffects[renderEffectName];
  21906. if (!renderEffects) {
  21907. return;
  21908. }
  21909. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21910. };
  21911. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21912. var renderEffects = this._renderEffects[renderEffectName];
  21913. if (!renderEffects) {
  21914. return;
  21915. }
  21916. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21917. };
  21918. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21919. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21920. var indicesToDelete = [];
  21921. for (var i = 0; i < _cam.length; i++) {
  21922. var camera = _cam[i];
  21923. var cameraName = camera.name;
  21924. if (this._cameras.indexOf(camera) === -1) {
  21925. this._cameras[cameraName] = camera;
  21926. }
  21927. else if (unique) {
  21928. indicesToDelete.push(i);
  21929. }
  21930. }
  21931. for (var i = 0; i < indicesToDelete.length; i++) {
  21932. cameras.splice(indicesToDelete[i], 1);
  21933. }
  21934. for (var renderEffectName in this._renderEffects) {
  21935. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21936. }
  21937. };
  21938. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21939. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21940. for (var renderEffectName in this._renderEffects) {
  21941. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21942. }
  21943. for (var i = 0; i < _cam.length; i++) {
  21944. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21945. }
  21946. };
  21947. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21948. var _this = this;
  21949. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21950. var pass = null;
  21951. for (var renderEffectName in this._renderEffects) {
  21952. pass = this._renderEffects[renderEffectName].getPass(passName);
  21953. if (pass != null) {
  21954. break;
  21955. }
  21956. }
  21957. if (pass === null) {
  21958. return;
  21959. }
  21960. for (var renderEffectName in this._renderEffects) {
  21961. this._renderEffects[renderEffectName]._disable(_cam);
  21962. }
  21963. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21964. for (var i = 0; i < _cam.length; i++) {
  21965. var camera = _cam[i];
  21966. var cameraName = camera.name;
  21967. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21968. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21969. });
  21970. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21971. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21972. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21973. }
  21974. };
  21975. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21976. var _this = this;
  21977. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21978. for (var i = 0; i < _cam.length; i++) {
  21979. var camera = _cam[i];
  21980. var cameraName = camera.name;
  21981. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21982. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21983. });
  21984. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21985. }
  21986. for (var renderEffectName in this._renderEffects) {
  21987. this._renderEffects[renderEffectName]._enable(_cam);
  21988. }
  21989. };
  21990. PostProcessRenderPipeline.prototype._update = function () {
  21991. for (var renderEffectName in this._renderEffects) {
  21992. this._renderEffects[renderEffectName]._update();
  21993. }
  21994. for (var i = 0; i < this._cameras.length; i++) {
  21995. var cameraName = this._cameras[i].name;
  21996. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21997. this._renderEffectsForIsolatedPass[cameraName]._update();
  21998. }
  21999. }
  22000. };
  22001. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22002. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22003. return PostProcessRenderPipeline;
  22004. })();
  22005. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22006. })(BABYLON || (BABYLON = {}));
  22007. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22008. (function (BABYLON) {
  22009. var PostProcessRenderPipelineManager = (function () {
  22010. function PostProcessRenderPipelineManager() {
  22011. this._renderPipelines = {};
  22012. }
  22013. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22014. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22015. };
  22016. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22017. var renderPipeline = this._renderPipelines[renderPipelineName];
  22018. if (!renderPipeline) {
  22019. return;
  22020. }
  22021. renderPipeline._attachCameras(cameras, unique);
  22022. };
  22023. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22024. var renderPipeline = this._renderPipelines[renderPipelineName];
  22025. if (!renderPipeline) {
  22026. return;
  22027. }
  22028. renderPipeline._detachCameras(cameras);
  22029. };
  22030. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22031. var renderPipeline = this._renderPipelines[renderPipelineName];
  22032. if (!renderPipeline) {
  22033. return;
  22034. }
  22035. renderPipeline._enableEffect(renderEffectName, cameras);
  22036. };
  22037. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22038. var renderPipeline = this._renderPipelines[renderPipelineName];
  22039. if (!renderPipeline) {
  22040. return;
  22041. }
  22042. renderPipeline._disableEffect(renderEffectName, cameras);
  22043. };
  22044. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22045. var renderPipeline = this._renderPipelines[renderPipelineName];
  22046. if (!renderPipeline) {
  22047. return;
  22048. }
  22049. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22050. };
  22051. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22052. var renderPipeline = this._renderPipelines[renderPipelineName];
  22053. if (!renderPipeline) {
  22054. return;
  22055. }
  22056. renderPipeline._disableDisplayOnlyPass(cameras);
  22057. };
  22058. PostProcessRenderPipelineManager.prototype.update = function () {
  22059. for (var renderPipelineName in this._renderPipelines) {
  22060. this._renderPipelines[renderPipelineName]._update();
  22061. }
  22062. };
  22063. return PostProcessRenderPipelineManager;
  22064. })();
  22065. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22066. })(BABYLON || (BABYLON = {}));
  22067. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22068. var BABYLON;
  22069. (function (BABYLON) {
  22070. var DisplayPassPostProcess = (function (_super) {
  22071. __extends(DisplayPassPostProcess, _super);
  22072. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22073. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22074. }
  22075. return DisplayPassPostProcess;
  22076. })(BABYLON.PostProcess);
  22077. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22078. })(BABYLON || (BABYLON = {}));
  22079. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22080. (function (BABYLON) {
  22081. var BoundingBoxRenderer = (function () {
  22082. function BoundingBoxRenderer(scene) {
  22083. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22084. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22085. this.showBackLines = true;
  22086. this.renderList = new BABYLON.SmartArray(32);
  22087. this._scene = scene;
  22088. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22089. attributes: ["position"],
  22090. uniforms: ["worldViewProjection", "color"]
  22091. });
  22092. var engine = this._scene.getEngine();
  22093. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22094. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22095. 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]);
  22096. }
  22097. BoundingBoxRenderer.prototype.reset = function () {
  22098. this.renderList.reset();
  22099. };
  22100. BoundingBoxRenderer.prototype.render = function () {
  22101. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22102. return;
  22103. }
  22104. var engine = this._scene.getEngine();
  22105. engine.setDepthWrite(false);
  22106. this._colorShader._preBind();
  22107. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22108. var boundingBox = this.renderList.data[boundingBoxIndex];
  22109. var min = boundingBox.minimum;
  22110. var max = boundingBox.maximum;
  22111. var diff = max.subtract(min);
  22112. var median = min.add(diff.scale(0.5));
  22113. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22114. // VBOs
  22115. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22116. if (this.showBackLines) {
  22117. // Back
  22118. engine.setDepthFunctionToGreaterOrEqual();
  22119. this._scene.resetCachedMaterial();
  22120. this._colorShader.setColor4("color", this.backColor.toColor4());
  22121. this._colorShader.bind(worldMatrix);
  22122. // Draw order
  22123. engine.draw(false, 0, 24);
  22124. }
  22125. // Front
  22126. engine.setDepthFunctionToLess();
  22127. this._scene.resetCachedMaterial();
  22128. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22129. this._colorShader.bind(worldMatrix);
  22130. // Draw order
  22131. engine.draw(false, 0, 24);
  22132. }
  22133. this._colorShader.unbind();
  22134. engine.setDepthFunctionToLessOrEqual();
  22135. engine.setDepthWrite(true);
  22136. };
  22137. BoundingBoxRenderer.prototype.dispose = function () {
  22138. this._colorShader.dispose();
  22139. this._vb.dispose();
  22140. this._scene.getEngine()._releaseBuffer(this._ib);
  22141. };
  22142. return BoundingBoxRenderer;
  22143. })();
  22144. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22145. })(BABYLON || (BABYLON = {}));
  22146. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22147. (function (BABYLON) {
  22148. var Internals;
  22149. (function (Internals) {
  22150. /*
  22151. * Based on jsTGALoader - Javascript loader for TGA file
  22152. * By Vincent Thibault
  22153. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22154. */
  22155. var TGATools = (function () {
  22156. function TGATools() {
  22157. }
  22158. TGATools.GetTGAHeader = function (data) {
  22159. var offset = 0;
  22160. var header = {
  22161. id_length: data[offset++],
  22162. colormap_type: data[offset++],
  22163. image_type: data[offset++],
  22164. colormap_index: data[offset++] | data[offset++] << 8,
  22165. colormap_length: data[offset++] | data[offset++] << 8,
  22166. colormap_size: data[offset++],
  22167. origin: [
  22168. data[offset++] | data[offset++] << 8,
  22169. data[offset++] | data[offset++] << 8
  22170. ],
  22171. width: data[offset++] | data[offset++] << 8,
  22172. height: data[offset++] | data[offset++] << 8,
  22173. pixel_size: data[offset++],
  22174. flags: data[offset++]
  22175. };
  22176. return header;
  22177. };
  22178. TGATools.UploadContent = function (gl, data) {
  22179. // Not enough data to contain header ?
  22180. if (data.length < 19) {
  22181. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22182. return;
  22183. }
  22184. // Read Header
  22185. var offset = 18;
  22186. var header = TGATools.GetTGAHeader(data);
  22187. // Assume it's a valid Targa file.
  22188. if (header.id_length + offset > data.length) {
  22189. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22190. return;
  22191. }
  22192. // Skip not needed data
  22193. offset += header.id_length;
  22194. var use_rle = false;
  22195. var use_pal = false;
  22196. var use_rgb = false;
  22197. var use_grey = false;
  22198. switch (header.image_type) {
  22199. case TGATools._TYPE_RLE_INDEXED:
  22200. use_rle = true;
  22201. case TGATools._TYPE_INDEXED:
  22202. use_pal = true;
  22203. break;
  22204. case TGATools._TYPE_RLE_RGB:
  22205. use_rle = true;
  22206. case TGATools._TYPE_RGB:
  22207. use_rgb = true;
  22208. break;
  22209. case TGATools._TYPE_RLE_GREY:
  22210. use_rle = true;
  22211. case TGATools._TYPE_GREY:
  22212. use_grey = true;
  22213. break;
  22214. }
  22215. var pixel_data;
  22216. var numAlphaBits = header.flags & 0xf;
  22217. var pixel_size = header.pixel_size >> 3;
  22218. var pixel_total = header.width * header.height * pixel_size;
  22219. // Read palettes
  22220. var palettes;
  22221. if (use_pal) {
  22222. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22223. }
  22224. // Read LRE
  22225. if (use_rle) {
  22226. pixel_data = new Uint8Array(pixel_total);
  22227. var c, count, i;
  22228. var localOffset = 0;
  22229. var pixels = new Uint8Array(pixel_size);
  22230. while (offset < pixel_total && localOffset < pixel_total) {
  22231. c = data[offset++];
  22232. count = (c & 0x7f) + 1;
  22233. // RLE pixels
  22234. if (c & 0x80) {
  22235. for (i = 0; i < pixel_size; ++i) {
  22236. pixels[i] = data[offset++];
  22237. }
  22238. for (i = 0; i < count; ++i) {
  22239. pixel_data.set(pixels, localOffset + i * pixel_size);
  22240. }
  22241. localOffset += pixel_size * count;
  22242. }
  22243. else {
  22244. count *= pixel_size;
  22245. for (i = 0; i < count; ++i) {
  22246. pixel_data[localOffset + i] = data[offset++];
  22247. }
  22248. localOffset += count;
  22249. }
  22250. }
  22251. }
  22252. else {
  22253. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22254. }
  22255. // Load to texture
  22256. var x_start, y_start, x_step, y_step, y_end, x_end;
  22257. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22258. default:
  22259. case TGATools._ORIGIN_UL:
  22260. x_start = 0;
  22261. x_step = 1;
  22262. x_end = header.width;
  22263. y_start = 0;
  22264. y_step = 1;
  22265. y_end = header.height;
  22266. break;
  22267. case TGATools._ORIGIN_BL:
  22268. x_start = 0;
  22269. x_step = 1;
  22270. x_end = header.width;
  22271. y_start = header.height - 1;
  22272. y_step = -1;
  22273. y_end = -1;
  22274. break;
  22275. case TGATools._ORIGIN_UR:
  22276. x_start = header.width - 1;
  22277. x_step = -1;
  22278. x_end = -1;
  22279. y_start = 0;
  22280. y_step = 1;
  22281. y_end = header.height;
  22282. break;
  22283. case TGATools._ORIGIN_BR:
  22284. x_start = header.width - 1;
  22285. x_step = -1;
  22286. x_end = -1;
  22287. y_start = header.height - 1;
  22288. y_step = -1;
  22289. y_end = -1;
  22290. break;
  22291. }
  22292. // Load the specify method
  22293. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22294. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22295. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22296. };
  22297. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22298. var image = pixel_data, colormap = palettes;
  22299. var width = header.width, height = header.height;
  22300. var color, i = 0, x, y;
  22301. var imageData = new Uint8Array(width * height * 4);
  22302. for (y = y_start; y !== y_end; y += y_step) {
  22303. for (x = x_start; x !== x_end; x += x_step, i++) {
  22304. color = image[i];
  22305. imageData[(x + width * y) * 4 + 3] = 255;
  22306. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22307. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22308. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22309. }
  22310. }
  22311. return imageData;
  22312. };
  22313. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22314. var image = pixel_data;
  22315. var width = header.width, height = header.height;
  22316. var color, i = 0, x, y;
  22317. var imageData = new Uint8Array(width * height * 4);
  22318. for (y = y_start; y !== y_end; y += y_step) {
  22319. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22320. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22321. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22322. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22323. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22324. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22325. }
  22326. }
  22327. return imageData;
  22328. };
  22329. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22330. var image = pixel_data;
  22331. var width = header.width, height = header.height;
  22332. var i = 0, x, y;
  22333. var imageData = new Uint8Array(width * height * 4);
  22334. for (y = y_start; y !== y_end; y += y_step) {
  22335. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22336. imageData[(x + width * y) * 4 + 3] = 255;
  22337. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22338. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22339. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22340. }
  22341. }
  22342. return imageData;
  22343. };
  22344. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22345. var image = pixel_data;
  22346. var width = header.width, height = header.height;
  22347. var i = 0, x, y;
  22348. var imageData = new Uint8Array(width * height * 4);
  22349. for (y = y_start; y !== y_end; y += y_step) {
  22350. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22351. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22352. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22353. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22354. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22355. }
  22356. }
  22357. return imageData;
  22358. };
  22359. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22360. var image = pixel_data;
  22361. var width = header.width, height = header.height;
  22362. var color, i = 0, x, y;
  22363. var imageData = new Uint8Array(width * height * 4);
  22364. for (y = y_start; y !== y_end; y += y_step) {
  22365. for (x = x_start; x !== x_end; x += x_step, i++) {
  22366. color = image[i];
  22367. imageData[(x + width * y) * 4 + 0] = color;
  22368. imageData[(x + width * y) * 4 + 1] = color;
  22369. imageData[(x + width * y) * 4 + 2] = color;
  22370. imageData[(x + width * y) * 4 + 3] = 255;
  22371. }
  22372. }
  22373. return imageData;
  22374. };
  22375. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22376. var image = pixel_data;
  22377. var width = header.width, height = header.height;
  22378. var i = 0, x, y;
  22379. var imageData = new Uint8Array(width * height * 4);
  22380. for (y = y_start; y !== y_end; y += y_step) {
  22381. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22382. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22383. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22384. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22385. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22386. }
  22387. }
  22388. return imageData;
  22389. };
  22390. TGATools._TYPE_NO_DATA = 0;
  22391. TGATools._TYPE_INDEXED = 1;
  22392. TGATools._TYPE_RGB = 2;
  22393. TGATools._TYPE_GREY = 3;
  22394. TGATools._TYPE_RLE_INDEXED = 9;
  22395. TGATools._TYPE_RLE_RGB = 10;
  22396. TGATools._TYPE_RLE_GREY = 11;
  22397. TGATools._ORIGIN_MASK = 0x30;
  22398. TGATools._ORIGIN_SHIFT = 0x04;
  22399. TGATools._ORIGIN_BL = 0x00;
  22400. TGATools._ORIGIN_BR = 0x01;
  22401. TGATools._ORIGIN_UL = 0x02;
  22402. TGATools._ORIGIN_UR = 0x03;
  22403. return TGATools;
  22404. })();
  22405. Internals.TGATools = TGATools;
  22406. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22407. })(BABYLON || (BABYLON = {}));
  22408. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22409. (function (BABYLON) {
  22410. var Internals;
  22411. (function (Internals) {
  22412. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22413. // All values and structures referenced from:
  22414. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22415. var DDS_MAGIC = 0x20534444;
  22416. 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;
  22417. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22418. 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;
  22419. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22420. function FourCCToInt32(value) {
  22421. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22422. }
  22423. function Int32ToFourCC(value) {
  22424. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22425. }
  22426. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22427. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22428. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22429. var headerLengthInt = 31; // The header length in 32 bit ints
  22430. // Offsets into the header array
  22431. var off_magic = 0;
  22432. var off_size = 1;
  22433. var off_flags = 2;
  22434. var off_height = 3;
  22435. var off_width = 4;
  22436. var off_mipmapCount = 7;
  22437. var off_pfFlags = 20;
  22438. var off_pfFourCC = 21;
  22439. var off_RGBbpp = 22;
  22440. var off_RMask = 23;
  22441. var off_GMask = 24;
  22442. var off_BMask = 25;
  22443. var off_AMask = 26;
  22444. var off_caps1 = 27;
  22445. var off_caps2 = 28;
  22446. ;
  22447. var DDSTools = (function () {
  22448. function DDSTools() {
  22449. }
  22450. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22451. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22452. var mipmapCount = 1;
  22453. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22454. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22455. }
  22456. return {
  22457. width: header[off_width],
  22458. height: header[off_height],
  22459. mipmapCount: mipmapCount,
  22460. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22461. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22462. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22463. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22464. };
  22465. };
  22466. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22467. var byteArray = new Uint8Array(dataLength);
  22468. var srcData = new Uint8Array(arrayBuffer);
  22469. var index = 0;
  22470. for (var y = height - 1; y >= 0; y--) {
  22471. for (var x = 0; x < width; x++) {
  22472. var srcPos = dataOffset + (x + y * width) * 4;
  22473. byteArray[index + 2] = srcData[srcPos];
  22474. byteArray[index + 1] = srcData[srcPos + 1];
  22475. byteArray[index] = srcData[srcPos + 2];
  22476. byteArray[index + 3] = srcData[srcPos + 3];
  22477. index += 4;
  22478. }
  22479. }
  22480. return byteArray;
  22481. };
  22482. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22483. var byteArray = new Uint8Array(dataLength);
  22484. var srcData = new Uint8Array(arrayBuffer);
  22485. var index = 0;
  22486. for (var y = height - 1; y >= 0; y--) {
  22487. for (var x = 0; x < width; x++) {
  22488. var srcPos = dataOffset + (x + y * width) * 3;
  22489. byteArray[index + 2] = srcData[srcPos];
  22490. byteArray[index + 1] = srcData[srcPos + 1];
  22491. byteArray[index] = srcData[srcPos + 2];
  22492. index += 3;
  22493. }
  22494. }
  22495. return byteArray;
  22496. };
  22497. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22498. var byteArray = new Uint8Array(dataLength);
  22499. var srcData = new Uint8Array(arrayBuffer);
  22500. var index = 0;
  22501. for (var y = height - 1; y >= 0; y--) {
  22502. for (var x = 0; x < width; x++) {
  22503. var srcPos = dataOffset + (x + y * width);
  22504. byteArray[index] = srcData[srcPos];
  22505. index++;
  22506. }
  22507. }
  22508. return byteArray;
  22509. };
  22510. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22511. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22512. if (header[off_magic] != DDS_MAGIC) {
  22513. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22514. return;
  22515. }
  22516. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22517. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22518. return;
  22519. }
  22520. if (info.isFourCC) {
  22521. fourCC = header[off_pfFourCC];
  22522. switch (fourCC) {
  22523. case FOURCC_DXT1:
  22524. blockBytes = 8;
  22525. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22526. break;
  22527. case FOURCC_DXT3:
  22528. blockBytes = 16;
  22529. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22530. break;
  22531. case FOURCC_DXT5:
  22532. blockBytes = 16;
  22533. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22534. break;
  22535. default:
  22536. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22537. return;
  22538. }
  22539. }
  22540. mipmapCount = 1;
  22541. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22542. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22543. }
  22544. var bpp = header[off_RGBbpp];
  22545. for (var face = 0; face < faces; face++) {
  22546. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22547. width = header[off_width];
  22548. height = header[off_height];
  22549. dataOffset = header[off_size] + 4;
  22550. for (i = 0; i < mipmapCount; ++i) {
  22551. if (info.isRGB) {
  22552. if (bpp == 24) {
  22553. dataLength = width * height * 3;
  22554. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22555. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22556. }
  22557. else {
  22558. dataLength = width * height * 4;
  22559. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22560. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22561. }
  22562. }
  22563. else if (info.isLuminance) {
  22564. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22565. var unpaddedRowSize = width;
  22566. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22567. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22568. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22569. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22570. }
  22571. else {
  22572. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22573. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22574. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22575. }
  22576. dataOffset += dataLength;
  22577. width *= 0.5;
  22578. height *= 0.5;
  22579. width = Math.max(1.0, width);
  22580. height = Math.max(1.0, height);
  22581. }
  22582. }
  22583. };
  22584. return DDSTools;
  22585. })();
  22586. Internals.DDSTools = DDSTools;
  22587. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22588. })(BABYLON || (BABYLON = {}));
  22589. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22590. (function (BABYLON) {
  22591. var SmartArray = (function () {
  22592. function SmartArray(capacity) {
  22593. this.length = 0;
  22594. this._duplicateId = 0;
  22595. this.data = new Array(capacity);
  22596. this._id = SmartArray._GlobalId++;
  22597. }
  22598. SmartArray.prototype.push = function (value) {
  22599. this.data[this.length++] = value;
  22600. if (this.length > this.data.length) {
  22601. this.data.length *= 2;
  22602. }
  22603. if (!value.__smartArrayFlags) {
  22604. value.__smartArrayFlags = {};
  22605. }
  22606. value.__smartArrayFlags[this._id] = this._duplicateId;
  22607. };
  22608. SmartArray.prototype.pushNoDuplicate = function (value) {
  22609. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22610. return;
  22611. }
  22612. this.push(value);
  22613. };
  22614. SmartArray.prototype.sort = function (compareFn) {
  22615. this.data.sort(compareFn);
  22616. };
  22617. SmartArray.prototype.reset = function () {
  22618. this.length = 0;
  22619. this._duplicateId++;
  22620. };
  22621. SmartArray.prototype.concat = function (array) {
  22622. if (array.length === 0) {
  22623. return;
  22624. }
  22625. if (this.length + array.length > this.data.length) {
  22626. this.data.length = (this.length + array.length) * 2;
  22627. }
  22628. for (var index = 0; index < array.length; index++) {
  22629. this.data[this.length++] = (array.data || array)[index];
  22630. }
  22631. };
  22632. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22633. if (array.length === 0) {
  22634. return;
  22635. }
  22636. if (this.length + array.length > this.data.length) {
  22637. this.data.length = (this.length + array.length) * 2;
  22638. }
  22639. for (var index = 0; index < array.length; index++) {
  22640. var item = (array.data || array)[index];
  22641. this.pushNoDuplicate(item);
  22642. }
  22643. };
  22644. SmartArray.prototype.indexOf = function (value) {
  22645. var position = this.data.indexOf(value);
  22646. if (position >= this.length) {
  22647. return -1;
  22648. }
  22649. return position;
  22650. };
  22651. // Statics
  22652. SmartArray._GlobalId = 0;
  22653. return SmartArray;
  22654. })();
  22655. BABYLON.SmartArray = SmartArray;
  22656. })(BABYLON || (BABYLON = {}));
  22657. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22658. (function (BABYLON) {
  22659. var CannonJSPlugin = (function () {
  22660. function CannonJSPlugin() {
  22661. this._registeredMeshes = [];
  22662. this._physicsMaterials = [];
  22663. this.updateBodyPosition = function (mesh) {
  22664. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22665. var registeredMesh = this._registeredMeshes[index];
  22666. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22667. var body = registeredMesh.body;
  22668. var center = mesh.getBoundingInfo().boundingBox.center;
  22669. body.position.set(center.x, center.z, center.y);
  22670. body.quaternion.x = mesh.rotationQuaternion.x;
  22671. body.quaternion.z = mesh.rotationQuaternion.y;
  22672. body.quaternion.y = mesh.rotationQuaternion.z;
  22673. body.quaternion.w = -mesh.rotationQuaternion.w;
  22674. return;
  22675. }
  22676. }
  22677. };
  22678. }
  22679. CannonJSPlugin.prototype.initialize = function (iterations) {
  22680. if (iterations === void 0) { iterations = 10; }
  22681. this._world = new CANNON.World();
  22682. this._world.broadphase = new CANNON.NaiveBroadphase();
  22683. this._world.solver.iterations = iterations;
  22684. };
  22685. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22686. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22687. };
  22688. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22689. this._world.step(delta);
  22690. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22691. var registeredMesh = this._registeredMeshes[index];
  22692. if (registeredMesh.isChild) {
  22693. continue;
  22694. }
  22695. // Body position
  22696. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22697. var deltaPos = registeredMesh.delta;
  22698. if (deltaPos) {
  22699. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22700. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22701. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22702. }
  22703. else {
  22704. registeredMesh.mesh.position.x = bodyX;
  22705. registeredMesh.mesh.position.y = bodyZ;
  22706. registeredMesh.mesh.position.z = bodyY;
  22707. }
  22708. if (!registeredMesh.mesh.rotationQuaternion) {
  22709. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22710. }
  22711. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22712. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22713. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22714. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22715. }
  22716. };
  22717. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22718. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22719. };
  22720. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22721. this.unregisterMesh(mesh);
  22722. mesh.computeWorldMatrix(true);
  22723. switch (impostor) {
  22724. case BABYLON.PhysicsEngine.SphereImpostor:
  22725. var bbox = mesh.getBoundingInfo().boundingBox;
  22726. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22727. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22728. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22729. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22730. case BABYLON.PhysicsEngine.BoxImpostor:
  22731. bbox = mesh.getBoundingInfo().boundingBox;
  22732. var min = bbox.minimumWorld;
  22733. var max = bbox.maximumWorld;
  22734. var box = max.subtract(min).scale(0.5);
  22735. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22736. case BABYLON.PhysicsEngine.PlaneImpostor:
  22737. return this._createPlane(mesh, options);
  22738. case BABYLON.PhysicsEngine.MeshImpostor:
  22739. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22740. var rawFaces = mesh.getIndices();
  22741. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22742. }
  22743. return null;
  22744. };
  22745. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22746. var shape = new CANNON.Sphere(radius);
  22747. if (!options) {
  22748. return shape;
  22749. }
  22750. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22751. };
  22752. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22753. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22754. if (!options) {
  22755. return shape;
  22756. }
  22757. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22758. };
  22759. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22760. var shape = new CANNON.Plane();
  22761. if (!options) {
  22762. return shape;
  22763. }
  22764. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22765. };
  22766. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22767. var verts = [], faces = [];
  22768. mesh.computeWorldMatrix(true);
  22769. for (var i = 0; i < rawVerts.length; i += 3) {
  22770. var transformed = BABYLON.Vector3.Zero();
  22771. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22772. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22773. }
  22774. for (var j = 0; j < rawFaces.length; j += 3) {
  22775. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22776. }
  22777. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22778. if (!options) {
  22779. return shape;
  22780. }
  22781. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22782. };
  22783. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22784. var index;
  22785. var mat;
  22786. for (index = 0; index < this._physicsMaterials.length; index++) {
  22787. mat = this._physicsMaterials[index];
  22788. if (mat.friction === friction && mat.restitution === restitution) {
  22789. return mat;
  22790. }
  22791. }
  22792. var currentMat = new CANNON.Material();
  22793. currentMat.friction = friction;
  22794. currentMat.restitution = restitution;
  22795. this._physicsMaterials.push(currentMat);
  22796. for (index = 0; index < this._physicsMaterials.length; index++) {
  22797. mat = this._physicsMaterials[index];
  22798. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22799. contactMaterial.contactEquationStiffness = 1e10;
  22800. contactMaterial.contactEquationRegularizationTime = 10;
  22801. this._world.addContactMaterial(contactMaterial);
  22802. }
  22803. return currentMat;
  22804. };
  22805. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22806. var initialRotation = null;
  22807. if (mesh.rotationQuaternion) {
  22808. initialRotation = mesh.rotationQuaternion.clone();
  22809. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22810. }
  22811. // The delta between the mesh position and the mesh bounding box center
  22812. var bbox = mesh.getBoundingInfo().boundingBox;
  22813. var deltaPosition = mesh.position.subtract(bbox.center);
  22814. var material = this._addMaterial(friction, restitution);
  22815. var body = new CANNON.RigidBody(mass, shape, material);
  22816. if (initialRotation) {
  22817. body.quaternion.x = initialRotation.x;
  22818. body.quaternion.z = initialRotation.y;
  22819. body.quaternion.y = initialRotation.z;
  22820. body.quaternion.w = -initialRotation.w;
  22821. }
  22822. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22823. this._world.add(body);
  22824. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22825. return body;
  22826. };
  22827. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22828. var compoundShape = new CANNON.Compound();
  22829. for (var index = 0; index < parts.length; index++) {
  22830. var mesh = parts[index].mesh;
  22831. var shape = this.registerMesh(mesh, parts[index].impostor);
  22832. if (index == 0) {
  22833. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22834. }
  22835. else {
  22836. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22837. }
  22838. }
  22839. var initialMesh = parts[0].mesh;
  22840. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22841. body.parts = parts;
  22842. return body;
  22843. };
  22844. CannonJSPlugin.prototype._unbindBody = function (body) {
  22845. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22846. var registeredMesh = this._registeredMeshes[index];
  22847. if (registeredMesh.body === body) {
  22848. registeredMesh.body = null;
  22849. registeredMesh.delta = 0;
  22850. }
  22851. }
  22852. };
  22853. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22854. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22855. var registeredMesh = this._registeredMeshes[index];
  22856. if (registeredMesh.mesh === mesh) {
  22857. // Remove body
  22858. if (registeredMesh.body) {
  22859. this._world.remove(registeredMesh.body);
  22860. this._unbindBody(registeredMesh.body);
  22861. }
  22862. this._registeredMeshes.splice(index, 1);
  22863. return;
  22864. }
  22865. }
  22866. };
  22867. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22868. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22869. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22870. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22871. var registeredMesh = this._registeredMeshes[index];
  22872. if (registeredMesh.mesh === mesh) {
  22873. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22874. return;
  22875. }
  22876. }
  22877. };
  22878. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22879. var body1 = null, body2 = null;
  22880. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22881. var registeredMesh = this._registeredMeshes[index];
  22882. if (registeredMesh.mesh === mesh1) {
  22883. body1 = registeredMesh.body;
  22884. }
  22885. else if (registeredMesh.mesh === mesh2) {
  22886. body2 = registeredMesh.body;
  22887. }
  22888. }
  22889. if (!body1 || !body2) {
  22890. return false;
  22891. }
  22892. 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));
  22893. this._world.addConstraint(constraint);
  22894. return true;
  22895. };
  22896. CannonJSPlugin.prototype.dispose = function () {
  22897. while (this._registeredMeshes.length) {
  22898. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22899. }
  22900. };
  22901. CannonJSPlugin.prototype.isSupported = function () {
  22902. return window.CANNON !== undefined;
  22903. };
  22904. return CannonJSPlugin;
  22905. })();
  22906. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22907. })(BABYLON || (BABYLON = {}));
  22908. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22909. var BABYLON;
  22910. (function (BABYLON) {
  22911. var Condition = (function () {
  22912. function Condition(actionManager) {
  22913. this._actionManager = actionManager;
  22914. }
  22915. Condition.prototype.isValid = function () {
  22916. return true;
  22917. };
  22918. Condition.prototype._getProperty = function (propertyPath) {
  22919. return this._actionManager._getProperty(propertyPath);
  22920. };
  22921. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22922. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22923. };
  22924. return Condition;
  22925. })();
  22926. BABYLON.Condition = Condition;
  22927. var ValueCondition = (function (_super) {
  22928. __extends(ValueCondition, _super);
  22929. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22930. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22931. _super.call(this, actionManager);
  22932. this.propertyPath = propertyPath;
  22933. this.value = value;
  22934. this.operator = operator;
  22935. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22936. this._property = this._getProperty(this.propertyPath);
  22937. }
  22938. Object.defineProperty(ValueCondition, "IsEqual", {
  22939. get: function () {
  22940. return ValueCondition._IsEqual;
  22941. },
  22942. enumerable: true,
  22943. configurable: true
  22944. });
  22945. Object.defineProperty(ValueCondition, "IsDifferent", {
  22946. get: function () {
  22947. return ValueCondition._IsDifferent;
  22948. },
  22949. enumerable: true,
  22950. configurable: true
  22951. });
  22952. Object.defineProperty(ValueCondition, "IsGreater", {
  22953. get: function () {
  22954. return ValueCondition._IsGreater;
  22955. },
  22956. enumerable: true,
  22957. configurable: true
  22958. });
  22959. Object.defineProperty(ValueCondition, "IsLesser", {
  22960. get: function () {
  22961. return ValueCondition._IsLesser;
  22962. },
  22963. enumerable: true,
  22964. configurable: true
  22965. });
  22966. // Methods
  22967. ValueCondition.prototype.isValid = function () {
  22968. switch (this.operator) {
  22969. case ValueCondition.IsGreater:
  22970. return this._target[this._property] > this.value;
  22971. case ValueCondition.IsLesser:
  22972. return this._target[this._property] < this.value;
  22973. case ValueCondition.IsEqual:
  22974. case ValueCondition.IsDifferent:
  22975. var check;
  22976. if (this.value.equals) {
  22977. check = this.value.equals(this._target[this._property]);
  22978. }
  22979. else {
  22980. check = this.value === this._target[this._property];
  22981. }
  22982. return this.operator === ValueCondition.IsEqual ? check : !check;
  22983. }
  22984. return false;
  22985. };
  22986. // Statics
  22987. ValueCondition._IsEqual = 0;
  22988. ValueCondition._IsDifferent = 1;
  22989. ValueCondition._IsGreater = 2;
  22990. ValueCondition._IsLesser = 3;
  22991. return ValueCondition;
  22992. })(Condition);
  22993. BABYLON.ValueCondition = ValueCondition;
  22994. var PredicateCondition = (function (_super) {
  22995. __extends(PredicateCondition, _super);
  22996. function PredicateCondition(actionManager, predicate) {
  22997. _super.call(this, actionManager);
  22998. this.predicate = predicate;
  22999. }
  23000. PredicateCondition.prototype.isValid = function () {
  23001. return this.predicate();
  23002. };
  23003. return PredicateCondition;
  23004. })(Condition);
  23005. BABYLON.PredicateCondition = PredicateCondition;
  23006. var StateCondition = (function (_super) {
  23007. __extends(StateCondition, _super);
  23008. function StateCondition(actionManager, target, value) {
  23009. _super.call(this, actionManager);
  23010. this.value = value;
  23011. this._target = target;
  23012. }
  23013. // Methods
  23014. StateCondition.prototype.isValid = function () {
  23015. return this._target.state === this.value;
  23016. };
  23017. return StateCondition;
  23018. })(Condition);
  23019. BABYLON.StateCondition = StateCondition;
  23020. })(BABYLON || (BABYLON = {}));
  23021. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23022. (function (BABYLON) {
  23023. var Action = (function () {
  23024. function Action(triggerOptions, condition) {
  23025. this.triggerOptions = triggerOptions;
  23026. if (triggerOptions.parameter) {
  23027. this.trigger = triggerOptions.trigger;
  23028. this._triggerParameter = triggerOptions.parameter;
  23029. }
  23030. else {
  23031. this.trigger = triggerOptions;
  23032. }
  23033. this._nextActiveAction = this;
  23034. this._condition = condition;
  23035. }
  23036. // Methods
  23037. Action.prototype._prepare = function () {
  23038. };
  23039. Action.prototype.getTriggerParameter = function () {
  23040. return this._triggerParameter;
  23041. };
  23042. Action.prototype._executeCurrent = function (evt) {
  23043. if (this._condition) {
  23044. var currentRenderId = this._actionManager.getScene().getRenderId();
  23045. // We cache the current evaluation for the current frame
  23046. if (this._condition._evaluationId === currentRenderId) {
  23047. if (!this._condition._currentResult) {
  23048. return;
  23049. }
  23050. }
  23051. else {
  23052. this._condition._evaluationId = currentRenderId;
  23053. if (!this._condition.isValid()) {
  23054. this._condition._currentResult = false;
  23055. return;
  23056. }
  23057. this._condition._currentResult = true;
  23058. }
  23059. }
  23060. this._nextActiveAction.execute(evt);
  23061. if (this._nextActiveAction._child) {
  23062. if (!this._nextActiveAction._child._actionManager) {
  23063. this._nextActiveAction._child._actionManager = this._actionManager;
  23064. }
  23065. this._nextActiveAction = this._nextActiveAction._child;
  23066. }
  23067. else {
  23068. this._nextActiveAction = this;
  23069. }
  23070. };
  23071. Action.prototype.execute = function (evt) {
  23072. };
  23073. Action.prototype.then = function (action) {
  23074. this._child = action;
  23075. action._actionManager = this._actionManager;
  23076. action._prepare();
  23077. return action;
  23078. };
  23079. Action.prototype._getProperty = function (propertyPath) {
  23080. return this._actionManager._getProperty(propertyPath);
  23081. };
  23082. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23083. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23084. };
  23085. return Action;
  23086. })();
  23087. BABYLON.Action = Action;
  23088. })(BABYLON || (BABYLON = {}));
  23089. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23090. (function (BABYLON) {
  23091. /**
  23092. * ActionEvent is the event beint sent when an action is triggered.
  23093. */
  23094. var ActionEvent = (function () {
  23095. /**
  23096. * @constructor
  23097. * @param source The mesh that triggered the action.
  23098. * @param pointerX the X mouse cursor position at the time of the event
  23099. * @param pointerY the Y mouse cursor position at the time of the event
  23100. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23101. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23102. */
  23103. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23104. this.source = source;
  23105. this.pointerX = pointerX;
  23106. this.pointerY = pointerY;
  23107. this.meshUnderPointer = meshUnderPointer;
  23108. this.sourceEvent = sourceEvent;
  23109. }
  23110. /**
  23111. * Helper function to auto-create an ActionEvent from a source mesh.
  23112. * @param source the source mesh that triggered the event
  23113. * @param evt {Event} The original (browser) event
  23114. */
  23115. ActionEvent.CreateNew = function (source, evt) {
  23116. var scene = source.getScene();
  23117. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23118. };
  23119. /**
  23120. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23121. * @param scene the scene where the event occurred
  23122. * @param evt {Event} The original (browser) event
  23123. */
  23124. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23125. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23126. };
  23127. return ActionEvent;
  23128. })();
  23129. BABYLON.ActionEvent = ActionEvent;
  23130. /**
  23131. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23132. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23133. */
  23134. var ActionManager = (function () {
  23135. function ActionManager(scene) {
  23136. // Members
  23137. this.actions = new Array();
  23138. this._scene = scene;
  23139. scene._actionManagers.push(this);
  23140. }
  23141. Object.defineProperty(ActionManager, "NothingTrigger", {
  23142. get: function () {
  23143. return ActionManager._NothingTrigger;
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23149. get: function () {
  23150. return ActionManager._OnPickTrigger;
  23151. },
  23152. enumerable: true,
  23153. configurable: true
  23154. });
  23155. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23156. get: function () {
  23157. return ActionManager._OnLeftPickTrigger;
  23158. },
  23159. enumerable: true,
  23160. configurable: true
  23161. });
  23162. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23163. get: function () {
  23164. return ActionManager._OnRightPickTrigger;
  23165. },
  23166. enumerable: true,
  23167. configurable: true
  23168. });
  23169. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23170. get: function () {
  23171. return ActionManager._OnCenterPickTrigger;
  23172. },
  23173. enumerable: true,
  23174. configurable: true
  23175. });
  23176. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23177. get: function () {
  23178. return ActionManager._OnPointerOverTrigger;
  23179. },
  23180. enumerable: true,
  23181. configurable: true
  23182. });
  23183. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23184. get: function () {
  23185. return ActionManager._OnPointerOutTrigger;
  23186. },
  23187. enumerable: true,
  23188. configurable: true
  23189. });
  23190. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23191. get: function () {
  23192. return ActionManager._OnEveryFrameTrigger;
  23193. },
  23194. enumerable: true,
  23195. configurable: true
  23196. });
  23197. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23198. get: function () {
  23199. return ActionManager._OnIntersectionEnterTrigger;
  23200. },
  23201. enumerable: true,
  23202. configurable: true
  23203. });
  23204. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23205. get: function () {
  23206. return ActionManager._OnIntersectionExitTrigger;
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23212. get: function () {
  23213. return ActionManager._OnKeyDownTrigger;
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23219. get: function () {
  23220. return ActionManager._OnKeyUpTrigger;
  23221. },
  23222. enumerable: true,
  23223. configurable: true
  23224. });
  23225. // Methods
  23226. ActionManager.prototype.dispose = function () {
  23227. var index = this._scene._actionManagers.indexOf(this);
  23228. if (index > -1) {
  23229. this._scene._actionManagers.splice(index, 1);
  23230. }
  23231. };
  23232. ActionManager.prototype.getScene = function () {
  23233. return this._scene;
  23234. };
  23235. /**
  23236. * Does this action manager handles actions of any of the given triggers
  23237. * @param {number[]} triggers - the triggers to be tested
  23238. * @return {boolean} whether one (or more) of the triggers is handeled
  23239. */
  23240. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23241. for (var index = 0; index < this.actions.length; index++) {
  23242. var action = this.actions[index];
  23243. if (triggers.indexOf(action.trigger) > -1) {
  23244. return true;
  23245. }
  23246. }
  23247. return false;
  23248. };
  23249. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23250. /**
  23251. * Does this action manager has pointer triggers
  23252. * @return {boolean} whether or not it has pointer triggers
  23253. */
  23254. get: function () {
  23255. for (var index = 0; index < this.actions.length; index++) {
  23256. var action = this.actions[index];
  23257. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23258. return true;
  23259. }
  23260. }
  23261. return false;
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23267. /**
  23268. * Does this action manager has pick triggers
  23269. * @return {boolean} whether or not it has pick triggers
  23270. */
  23271. get: function () {
  23272. for (var index = 0; index < this.actions.length; index++) {
  23273. var action = this.actions[index];
  23274. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23275. return true;
  23276. }
  23277. }
  23278. return false;
  23279. },
  23280. enumerable: true,
  23281. configurable: true
  23282. });
  23283. /**
  23284. * Registers an action to this action manager
  23285. * @param {BABYLON.Action} action - the action to be registered
  23286. * @return {BABYLON.Action} the action amended (prepared) after registration
  23287. */
  23288. ActionManager.prototype.registerAction = function (action) {
  23289. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23290. if (this.getScene().actionManager !== this) {
  23291. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23292. return null;
  23293. }
  23294. }
  23295. this.actions.push(action);
  23296. action._actionManager = this;
  23297. action._prepare();
  23298. return action;
  23299. };
  23300. /**
  23301. * Process a specific trigger
  23302. * @param {number} trigger - the trigger to process
  23303. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23304. */
  23305. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23306. for (var index = 0; index < this.actions.length; index++) {
  23307. var action = this.actions[index];
  23308. if (action.trigger === trigger) {
  23309. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23310. var parameter = action.getTriggerParameter();
  23311. if (parameter) {
  23312. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23313. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23314. if (actualkey !== parameter.toLowerCase()) {
  23315. continue;
  23316. }
  23317. }
  23318. }
  23319. action._executeCurrent(evt);
  23320. }
  23321. }
  23322. };
  23323. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23324. var properties = propertyPath.split(".");
  23325. for (var index = 0; index < properties.length - 1; index++) {
  23326. target = target[properties[index]];
  23327. }
  23328. return target;
  23329. };
  23330. ActionManager.prototype._getProperty = function (propertyPath) {
  23331. var properties = propertyPath.split(".");
  23332. return properties[properties.length - 1];
  23333. };
  23334. // Statics
  23335. ActionManager._NothingTrigger = 0;
  23336. ActionManager._OnPickTrigger = 1;
  23337. ActionManager._OnLeftPickTrigger = 2;
  23338. ActionManager._OnRightPickTrigger = 3;
  23339. ActionManager._OnCenterPickTrigger = 4;
  23340. ActionManager._OnPointerOverTrigger = 5;
  23341. ActionManager._OnPointerOutTrigger = 6;
  23342. ActionManager._OnEveryFrameTrigger = 7;
  23343. ActionManager._OnIntersectionEnterTrigger = 8;
  23344. ActionManager._OnIntersectionExitTrigger = 9;
  23345. ActionManager._OnKeyDownTrigger = 10;
  23346. ActionManager._OnKeyUpTrigger = 11;
  23347. return ActionManager;
  23348. })();
  23349. BABYLON.ActionManager = ActionManager;
  23350. })(BABYLON || (BABYLON = {}));
  23351. //# sourceMappingURL=babylon.actionManager.js.map
  23352. var BABYLON;
  23353. (function (BABYLON) {
  23354. var InterpolateValueAction = (function (_super) {
  23355. __extends(InterpolateValueAction, _super);
  23356. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23357. if (duration === void 0) { duration = 1000; }
  23358. _super.call(this, triggerOptions, condition);
  23359. this.propertyPath = propertyPath;
  23360. this.value = value;
  23361. this.duration = duration;
  23362. this.stopOtherAnimations = stopOtherAnimations;
  23363. this._target = target;
  23364. }
  23365. InterpolateValueAction.prototype._prepare = function () {
  23366. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23367. this._property = this._getProperty(this.propertyPath);
  23368. };
  23369. InterpolateValueAction.prototype.execute = function () {
  23370. var scene = this._actionManager.getScene();
  23371. var keys = [
  23372. {
  23373. frame: 0,
  23374. value: this._target[this._property]
  23375. },
  23376. {
  23377. frame: 100,
  23378. value: this.value
  23379. }
  23380. ];
  23381. var dataType;
  23382. if (typeof this.value === "number") {
  23383. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23384. }
  23385. else if (this.value instanceof BABYLON.Color3) {
  23386. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23387. }
  23388. else if (this.value instanceof BABYLON.Vector3) {
  23389. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23390. }
  23391. else if (this.value instanceof BABYLON.Matrix) {
  23392. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23393. }
  23394. else if (this.value instanceof BABYLON.Quaternion) {
  23395. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23396. }
  23397. else {
  23398. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23399. return;
  23400. }
  23401. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23402. animation.setKeys(keys);
  23403. if (this.stopOtherAnimations) {
  23404. scene.stopAnimation(this._target);
  23405. }
  23406. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23407. };
  23408. return InterpolateValueAction;
  23409. })(BABYLON.Action);
  23410. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23411. })(BABYLON || (BABYLON = {}));
  23412. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23413. var BABYLON;
  23414. (function (BABYLON) {
  23415. var SwitchBooleanAction = (function (_super) {
  23416. __extends(SwitchBooleanAction, _super);
  23417. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23418. _super.call(this, triggerOptions, condition);
  23419. this.propertyPath = propertyPath;
  23420. this._target = target;
  23421. }
  23422. SwitchBooleanAction.prototype._prepare = function () {
  23423. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23424. this._property = this._getProperty(this.propertyPath);
  23425. };
  23426. SwitchBooleanAction.prototype.execute = function () {
  23427. this._target[this._property] = !this._target[this._property];
  23428. };
  23429. return SwitchBooleanAction;
  23430. })(BABYLON.Action);
  23431. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23432. var SetStateAction = (function (_super) {
  23433. __extends(SetStateAction, _super);
  23434. function SetStateAction(triggerOptions, target, value, condition) {
  23435. _super.call(this, triggerOptions, condition);
  23436. this.value = value;
  23437. this._target = target;
  23438. }
  23439. SetStateAction.prototype.execute = function () {
  23440. this._target.state = this.value;
  23441. };
  23442. return SetStateAction;
  23443. })(BABYLON.Action);
  23444. BABYLON.SetStateAction = SetStateAction;
  23445. var SetValueAction = (function (_super) {
  23446. __extends(SetValueAction, _super);
  23447. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23448. _super.call(this, triggerOptions, condition);
  23449. this.propertyPath = propertyPath;
  23450. this.value = value;
  23451. this._target = target;
  23452. }
  23453. SetValueAction.prototype._prepare = function () {
  23454. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23455. this._property = this._getProperty(this.propertyPath);
  23456. };
  23457. SetValueAction.prototype.execute = function () {
  23458. this._target[this._property] = this.value;
  23459. };
  23460. return SetValueAction;
  23461. })(BABYLON.Action);
  23462. BABYLON.SetValueAction = SetValueAction;
  23463. var IncrementValueAction = (function (_super) {
  23464. __extends(IncrementValueAction, _super);
  23465. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23466. _super.call(this, triggerOptions, condition);
  23467. this.propertyPath = propertyPath;
  23468. this.value = value;
  23469. this._target = target;
  23470. }
  23471. IncrementValueAction.prototype._prepare = function () {
  23472. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23473. this._property = this._getProperty(this.propertyPath);
  23474. if (typeof this._target[this._property] !== "number") {
  23475. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23476. }
  23477. };
  23478. IncrementValueAction.prototype.execute = function () {
  23479. this._target[this._property] += this.value;
  23480. };
  23481. return IncrementValueAction;
  23482. })(BABYLON.Action);
  23483. BABYLON.IncrementValueAction = IncrementValueAction;
  23484. var PlayAnimationAction = (function (_super) {
  23485. __extends(PlayAnimationAction, _super);
  23486. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23487. _super.call(this, triggerOptions, condition);
  23488. this.from = from;
  23489. this.to = to;
  23490. this.loop = loop;
  23491. this._target = target;
  23492. }
  23493. PlayAnimationAction.prototype._prepare = function () {
  23494. };
  23495. PlayAnimationAction.prototype.execute = function () {
  23496. var scene = this._actionManager.getScene();
  23497. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23498. };
  23499. return PlayAnimationAction;
  23500. })(BABYLON.Action);
  23501. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23502. var StopAnimationAction = (function (_super) {
  23503. __extends(StopAnimationAction, _super);
  23504. function StopAnimationAction(triggerOptions, target, condition) {
  23505. _super.call(this, triggerOptions, condition);
  23506. this._target = target;
  23507. }
  23508. StopAnimationAction.prototype._prepare = function () {
  23509. };
  23510. StopAnimationAction.prototype.execute = function () {
  23511. var scene = this._actionManager.getScene();
  23512. scene.stopAnimation(this._target);
  23513. };
  23514. return StopAnimationAction;
  23515. })(BABYLON.Action);
  23516. BABYLON.StopAnimationAction = StopAnimationAction;
  23517. var DoNothingAction = (function (_super) {
  23518. __extends(DoNothingAction, _super);
  23519. function DoNothingAction(triggerOptions, condition) {
  23520. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23521. _super.call(this, triggerOptions, condition);
  23522. }
  23523. DoNothingAction.prototype.execute = function () {
  23524. };
  23525. return DoNothingAction;
  23526. })(BABYLON.Action);
  23527. BABYLON.DoNothingAction = DoNothingAction;
  23528. var CombineAction = (function (_super) {
  23529. __extends(CombineAction, _super);
  23530. function CombineAction(triggerOptions, children, condition) {
  23531. _super.call(this, triggerOptions, condition);
  23532. this.children = children;
  23533. }
  23534. CombineAction.prototype._prepare = function () {
  23535. for (var index = 0; index < this.children.length; index++) {
  23536. this.children[index]._actionManager = this._actionManager;
  23537. this.children[index]._prepare();
  23538. }
  23539. };
  23540. CombineAction.prototype.execute = function (evt) {
  23541. for (var index = 0; index < this.children.length; index++) {
  23542. this.children[index].execute(evt);
  23543. }
  23544. };
  23545. return CombineAction;
  23546. })(BABYLON.Action);
  23547. BABYLON.CombineAction = CombineAction;
  23548. var ExecuteCodeAction = (function (_super) {
  23549. __extends(ExecuteCodeAction, _super);
  23550. function ExecuteCodeAction(triggerOptions, func, condition) {
  23551. _super.call(this, triggerOptions, condition);
  23552. this.func = func;
  23553. }
  23554. ExecuteCodeAction.prototype.execute = function (evt) {
  23555. this.func(evt);
  23556. };
  23557. return ExecuteCodeAction;
  23558. })(BABYLON.Action);
  23559. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23560. var SetParentAction = (function (_super) {
  23561. __extends(SetParentAction, _super);
  23562. function SetParentAction(triggerOptions, target, parent, condition) {
  23563. _super.call(this, triggerOptions, condition);
  23564. this._target = target;
  23565. this._parent = parent;
  23566. }
  23567. SetParentAction.prototype._prepare = function () {
  23568. };
  23569. SetParentAction.prototype.execute = function () {
  23570. if (this._target.parent === this._parent) {
  23571. return;
  23572. }
  23573. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23574. invertParentWorldMatrix.invert();
  23575. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23576. this._target.parent = this._parent;
  23577. };
  23578. return SetParentAction;
  23579. })(BABYLON.Action);
  23580. BABYLON.SetParentAction = SetParentAction;
  23581. var PlaySoundAction = (function (_super) {
  23582. __extends(PlaySoundAction, _super);
  23583. function PlaySoundAction(triggerOptions, sound, condition) {
  23584. _super.call(this, triggerOptions, condition);
  23585. this._sound = sound;
  23586. }
  23587. PlaySoundAction.prototype._prepare = function () {
  23588. };
  23589. PlaySoundAction.prototype.execute = function () {
  23590. if (this._sound !== undefined)
  23591. this._sound.play();
  23592. };
  23593. return PlaySoundAction;
  23594. })(BABYLON.Action);
  23595. BABYLON.PlaySoundAction = PlaySoundAction;
  23596. var StopSoundAction = (function (_super) {
  23597. __extends(StopSoundAction, _super);
  23598. function StopSoundAction(triggerOptions, sound, condition) {
  23599. _super.call(this, triggerOptions, condition);
  23600. this._sound = sound;
  23601. }
  23602. StopSoundAction.prototype._prepare = function () {
  23603. };
  23604. StopSoundAction.prototype.execute = function () {
  23605. if (this._sound !== undefined)
  23606. this._sound.stop();
  23607. };
  23608. return StopSoundAction;
  23609. })(BABYLON.Action);
  23610. BABYLON.StopSoundAction = StopSoundAction;
  23611. })(BABYLON || (BABYLON = {}));
  23612. //# sourceMappingURL=babylon.directActions.js.map
  23613. var BABYLON;
  23614. (function (BABYLON) {
  23615. var Geometry = (function () {
  23616. function Geometry(id, scene, vertexData, updatable, mesh) {
  23617. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23618. this._totalVertices = 0;
  23619. this._indices = [];
  23620. this.id = id;
  23621. this._engine = scene.getEngine();
  23622. this._meshes = [];
  23623. this._scene = scene;
  23624. // vertexData
  23625. if (vertexData) {
  23626. this.setAllVerticesData(vertexData, updatable);
  23627. }
  23628. else {
  23629. this._totalVertices = 0;
  23630. this._indices = [];
  23631. }
  23632. // applyToMesh
  23633. if (mesh) {
  23634. this.applyToMesh(mesh);
  23635. mesh.computeWorldMatrix(true);
  23636. }
  23637. }
  23638. Geometry.prototype.getScene = function () {
  23639. return this._scene;
  23640. };
  23641. Geometry.prototype.getEngine = function () {
  23642. return this._engine;
  23643. };
  23644. Geometry.prototype.isReady = function () {
  23645. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23646. };
  23647. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23648. vertexData.applyToGeometry(this, updatable);
  23649. };
  23650. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23651. this._vertexBuffers = this._vertexBuffers || {};
  23652. if (this._vertexBuffers[kind]) {
  23653. this._vertexBuffers[kind].dispose();
  23654. }
  23655. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23656. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23657. stride = this._vertexBuffers[kind].getStrideSize();
  23658. this._totalVertices = data.length / stride;
  23659. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23660. var meshes = this._meshes;
  23661. var numOfMeshes = meshes.length;
  23662. for (var index = 0; index < numOfMeshes; index++) {
  23663. var mesh = meshes[index];
  23664. mesh._resetPointsArrayCache();
  23665. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23666. mesh._createGlobalSubMesh();
  23667. mesh.computeWorldMatrix(true);
  23668. }
  23669. }
  23670. };
  23671. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23672. var vertexBuffer = this.getVertexBuffer(kind);
  23673. if (!vertexBuffer) {
  23674. return;
  23675. }
  23676. vertexBuffer.updateDirectly(data, offset);
  23677. };
  23678. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23679. var vertexBuffer = this.getVertexBuffer(kind);
  23680. if (!vertexBuffer) {
  23681. return;
  23682. }
  23683. vertexBuffer.update(data);
  23684. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23685. var extend;
  23686. var stride = vertexBuffer.getStrideSize();
  23687. this._totalVertices = data.length / stride;
  23688. if (updateExtends) {
  23689. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23690. }
  23691. var meshes = this._meshes;
  23692. var numOfMeshes = meshes.length;
  23693. for (var index = 0; index < numOfMeshes; index++) {
  23694. var mesh = meshes[index];
  23695. mesh._resetPointsArrayCache();
  23696. if (updateExtends) {
  23697. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23698. }
  23699. }
  23700. }
  23701. };
  23702. Geometry.prototype.getTotalVertices = function () {
  23703. if (!this.isReady()) {
  23704. return 0;
  23705. }
  23706. return this._totalVertices;
  23707. };
  23708. Geometry.prototype.getVerticesData = function (kind) {
  23709. var vertexBuffer = this.getVertexBuffer(kind);
  23710. if (!vertexBuffer) {
  23711. return null;
  23712. }
  23713. return vertexBuffer.getData();
  23714. };
  23715. Geometry.prototype.getVertexBuffer = function (kind) {
  23716. if (!this.isReady()) {
  23717. return null;
  23718. }
  23719. return this._vertexBuffers[kind];
  23720. };
  23721. Geometry.prototype.getVertexBuffers = function () {
  23722. if (!this.isReady()) {
  23723. return null;
  23724. }
  23725. return this._vertexBuffers;
  23726. };
  23727. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23728. if (!this._vertexBuffers) {
  23729. if (this._delayInfo) {
  23730. return this._delayInfo.indexOf(kind) !== -1;
  23731. }
  23732. return false;
  23733. }
  23734. return this._vertexBuffers[kind] !== undefined;
  23735. };
  23736. Geometry.prototype.getVerticesDataKinds = function () {
  23737. var result = [];
  23738. if (!this._vertexBuffers && this._delayInfo) {
  23739. for (var kind in this._delayInfo) {
  23740. result.push(kind);
  23741. }
  23742. }
  23743. else {
  23744. for (kind in this._vertexBuffers) {
  23745. result.push(kind);
  23746. }
  23747. }
  23748. return result;
  23749. };
  23750. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23751. if (this._indexBuffer) {
  23752. this._engine._releaseBuffer(this._indexBuffer);
  23753. }
  23754. this._indices = indices;
  23755. if (this._meshes.length !== 0 && this._indices) {
  23756. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23757. }
  23758. if (totalVertices !== undefined) {
  23759. this._totalVertices = totalVertices;
  23760. }
  23761. var meshes = this._meshes;
  23762. var numOfMeshes = meshes.length;
  23763. for (var index = 0; index < numOfMeshes; index++) {
  23764. meshes[index]._createGlobalSubMesh();
  23765. }
  23766. };
  23767. Geometry.prototype.getTotalIndices = function () {
  23768. if (!this.isReady()) {
  23769. return 0;
  23770. }
  23771. return this._indices.length;
  23772. };
  23773. Geometry.prototype.getIndices = function () {
  23774. if (!this.isReady()) {
  23775. return null;
  23776. }
  23777. return this._indices;
  23778. };
  23779. Geometry.prototype.getIndexBuffer = function () {
  23780. if (!this.isReady()) {
  23781. return null;
  23782. }
  23783. return this._indexBuffer;
  23784. };
  23785. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23786. var meshes = this._meshes;
  23787. var index = meshes.indexOf(mesh);
  23788. if (index === -1) {
  23789. return;
  23790. }
  23791. for (var kind in this._vertexBuffers) {
  23792. this._vertexBuffers[kind].dispose();
  23793. }
  23794. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23795. this._indexBuffer = null;
  23796. }
  23797. meshes.splice(index, 1);
  23798. mesh._geometry = null;
  23799. if (meshes.length === 0 && shouldDispose) {
  23800. this.dispose();
  23801. }
  23802. };
  23803. Geometry.prototype.applyToMesh = function (mesh) {
  23804. if (mesh._geometry === this) {
  23805. return;
  23806. }
  23807. var previousGeometry = mesh._geometry;
  23808. if (previousGeometry) {
  23809. previousGeometry.releaseForMesh(mesh);
  23810. }
  23811. var meshes = this._meshes;
  23812. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23813. mesh._geometry = this;
  23814. this._scene.pushGeometry(this);
  23815. meshes.push(mesh);
  23816. if (this.isReady()) {
  23817. this._applyToMesh(mesh);
  23818. }
  23819. else {
  23820. mesh._boundingInfo = this._boundingInfo;
  23821. }
  23822. };
  23823. Geometry.prototype._applyToMesh = function (mesh) {
  23824. var numOfMeshes = this._meshes.length;
  23825. for (var kind in this._vertexBuffers) {
  23826. if (numOfMeshes === 1) {
  23827. this._vertexBuffers[kind].create();
  23828. }
  23829. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23830. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23831. mesh._resetPointsArrayCache();
  23832. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23833. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23834. mesh._createGlobalSubMesh();
  23835. //bounding info was just created again, world matrix should be applied again.
  23836. mesh._updateBoundingInfo();
  23837. }
  23838. }
  23839. // indexBuffer
  23840. if (numOfMeshes === 1 && this._indices) {
  23841. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23842. }
  23843. if (this._indexBuffer) {
  23844. this._indexBuffer.references = numOfMeshes;
  23845. }
  23846. };
  23847. Geometry.prototype.load = function (scene, onLoaded) {
  23848. var _this = this;
  23849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23850. return;
  23851. }
  23852. if (this.isReady()) {
  23853. if (onLoaded) {
  23854. onLoaded();
  23855. }
  23856. return;
  23857. }
  23858. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23859. scene._addPendingData(this);
  23860. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23861. _this._delayLoadingFunction(JSON.parse(data), _this);
  23862. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23863. _this._delayInfo = [];
  23864. scene._removePendingData(_this);
  23865. var meshes = _this._meshes;
  23866. var numOfMeshes = meshes.length;
  23867. for (var index = 0; index < numOfMeshes; index++) {
  23868. _this._applyToMesh(meshes[index]);
  23869. }
  23870. if (onLoaded) {
  23871. onLoaded();
  23872. }
  23873. }, function () {
  23874. }, scene.database);
  23875. };
  23876. Geometry.prototype.dispose = function () {
  23877. var meshes = this._meshes;
  23878. var numOfMeshes = meshes.length;
  23879. var index;
  23880. for (index = 0; index < numOfMeshes; index++) {
  23881. this.releaseForMesh(meshes[index]);
  23882. }
  23883. this._meshes = [];
  23884. for (var kind in this._vertexBuffers) {
  23885. this._vertexBuffers[kind].dispose();
  23886. }
  23887. this._vertexBuffers = [];
  23888. this._totalVertices = 0;
  23889. if (this._indexBuffer) {
  23890. this._engine._releaseBuffer(this._indexBuffer);
  23891. }
  23892. this._indexBuffer = null;
  23893. this._indices = [];
  23894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23895. this.delayLoadingFile = null;
  23896. this._delayLoadingFunction = null;
  23897. this._delayInfo = [];
  23898. this._boundingInfo = null; // todo: .dispose()
  23899. var geometries = this._scene.getGeometries();
  23900. index = geometries.indexOf(this);
  23901. if (index > -1) {
  23902. geometries.splice(index, 1);
  23903. }
  23904. };
  23905. Geometry.prototype.copy = function (id) {
  23906. var vertexData = new BABYLON.VertexData();
  23907. vertexData.indices = [];
  23908. var indices = this.getIndices();
  23909. for (var index = 0; index < indices.length; index++) {
  23910. vertexData.indices.push(indices[index]);
  23911. }
  23912. var updatable = false;
  23913. var stopChecking = false;
  23914. for (var kind in this._vertexBuffers) {
  23915. vertexData.set(this.getVerticesData(kind), kind);
  23916. if (!stopChecking) {
  23917. updatable = this.getVertexBuffer(kind).isUpdatable();
  23918. stopChecking = !updatable;
  23919. }
  23920. }
  23921. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23922. geometry.delayLoadState = this.delayLoadState;
  23923. geometry.delayLoadingFile = this.delayLoadingFile;
  23924. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23925. for (kind in this._delayInfo) {
  23926. geometry._delayInfo = geometry._delayInfo || [];
  23927. geometry._delayInfo.push(kind);
  23928. }
  23929. // Bounding info
  23930. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23931. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23932. return geometry;
  23933. };
  23934. // Statics
  23935. Geometry.ExtractFromMesh = function (mesh, id) {
  23936. var geometry = mesh._geometry;
  23937. if (!geometry) {
  23938. return null;
  23939. }
  23940. return geometry.copy(id);
  23941. };
  23942. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23943. // be aware Math.random() could cause collisions
  23944. Geometry.RandomId = function () {
  23945. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23946. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23947. return v.toString(16);
  23948. });
  23949. };
  23950. return Geometry;
  23951. })();
  23952. BABYLON.Geometry = Geometry;
  23953. /////// Primitives //////////////////////////////////////////////
  23954. var Geometry;
  23955. (function (Geometry) {
  23956. var Primitives;
  23957. (function (Primitives) {
  23958. /// Abstract class
  23959. var _Primitive = (function (_super) {
  23960. __extends(_Primitive, _super);
  23961. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23962. this._beingRegenerated = true;
  23963. this._canBeRegenerated = canBeRegenerated;
  23964. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23965. this._beingRegenerated = false;
  23966. }
  23967. _Primitive.prototype.canBeRegenerated = function () {
  23968. return this._canBeRegenerated;
  23969. };
  23970. _Primitive.prototype.regenerate = function () {
  23971. if (!this._canBeRegenerated) {
  23972. return;
  23973. }
  23974. this._beingRegenerated = true;
  23975. this.setAllVerticesData(this._regenerateVertexData(), false);
  23976. this._beingRegenerated = false;
  23977. };
  23978. _Primitive.prototype.asNewGeometry = function (id) {
  23979. return _super.prototype.copy.call(this, id);
  23980. };
  23981. // overrides
  23982. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23983. if (!this._beingRegenerated) {
  23984. return;
  23985. }
  23986. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23987. };
  23988. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23989. if (!this._beingRegenerated) {
  23990. return;
  23991. }
  23992. _super.prototype.setVerticesData.call(this, kind, data, false);
  23993. };
  23994. // to override
  23995. // protected
  23996. _Primitive.prototype._regenerateVertexData = function () {
  23997. throw new Error("Abstract method");
  23998. };
  23999. _Primitive.prototype.copy = function (id) {
  24000. throw new Error("Must be overriden in sub-classes.");
  24001. };
  24002. return _Primitive;
  24003. })(Geometry);
  24004. Primitives._Primitive = _Primitive;
  24005. var Box = (function (_super) {
  24006. __extends(Box, _super);
  24007. function Box(id, scene, size, canBeRegenerated, mesh) {
  24008. this.size = size;
  24009. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24010. }
  24011. Box.prototype._regenerateVertexData = function () {
  24012. return BABYLON.VertexData.CreateBox(this.size);
  24013. };
  24014. Box.prototype.copy = function (id) {
  24015. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24016. };
  24017. return Box;
  24018. })(_Primitive);
  24019. Primitives.Box = Box;
  24020. var Sphere = (function (_super) {
  24021. __extends(Sphere, _super);
  24022. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  24023. this.segments = segments;
  24024. this.diameter = diameter;
  24025. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24026. }
  24027. Sphere.prototype._regenerateVertexData = function () {
  24028. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  24029. };
  24030. Sphere.prototype.copy = function (id) {
  24031. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  24032. };
  24033. return Sphere;
  24034. })(_Primitive);
  24035. Primitives.Sphere = Sphere;
  24036. var Cylinder = (function (_super) {
  24037. __extends(Cylinder, _super);
  24038. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  24039. if (subdivisions === void 0) { subdivisions = 1; }
  24040. this.height = height;
  24041. this.diameterTop = diameterTop;
  24042. this.diameterBottom = diameterBottom;
  24043. this.tessellation = tessellation;
  24044. this.subdivisions = subdivisions;
  24045. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24046. }
  24047. Cylinder.prototype._regenerateVertexData = function () {
  24048. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  24049. };
  24050. Cylinder.prototype.copy = function (id) {
  24051. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  24052. };
  24053. return Cylinder;
  24054. })(_Primitive);
  24055. Primitives.Cylinder = Cylinder;
  24056. var Torus = (function (_super) {
  24057. __extends(Torus, _super);
  24058. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  24059. this.diameter = diameter;
  24060. this.thickness = thickness;
  24061. this.tessellation = tessellation;
  24062. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24063. }
  24064. Torus.prototype._regenerateVertexData = function () {
  24065. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  24066. };
  24067. Torus.prototype.copy = function (id) {
  24068. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  24069. };
  24070. return Torus;
  24071. })(_Primitive);
  24072. Primitives.Torus = Torus;
  24073. var Ground = (function (_super) {
  24074. __extends(Ground, _super);
  24075. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24076. this.width = width;
  24077. this.height = height;
  24078. this.subdivisions = subdivisions;
  24079. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24080. }
  24081. Ground.prototype._regenerateVertexData = function () {
  24082. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24083. };
  24084. Ground.prototype.copy = function (id) {
  24085. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24086. };
  24087. return Ground;
  24088. })(_Primitive);
  24089. Primitives.Ground = Ground;
  24090. var TiledGround = (function (_super) {
  24091. __extends(TiledGround, _super);
  24092. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24093. this.xmin = xmin;
  24094. this.zmin = zmin;
  24095. this.xmax = xmax;
  24096. this.zmax = zmax;
  24097. this.subdivisions = subdivisions;
  24098. this.precision = precision;
  24099. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24100. }
  24101. TiledGround.prototype._regenerateVertexData = function () {
  24102. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24103. };
  24104. TiledGround.prototype.copy = function (id) {
  24105. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24106. };
  24107. return TiledGround;
  24108. })(_Primitive);
  24109. Primitives.TiledGround = TiledGround;
  24110. var Plane = (function (_super) {
  24111. __extends(Plane, _super);
  24112. function Plane(id, scene, size, canBeRegenerated, mesh) {
  24113. this.size = size;
  24114. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24115. }
  24116. Plane.prototype._regenerateVertexData = function () {
  24117. return BABYLON.VertexData.CreatePlane(this.size);
  24118. };
  24119. Plane.prototype.copy = function (id) {
  24120. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24121. };
  24122. return Plane;
  24123. })(_Primitive);
  24124. Primitives.Plane = Plane;
  24125. var TorusKnot = (function (_super) {
  24126. __extends(TorusKnot, _super);
  24127. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  24128. this.radius = radius;
  24129. this.tube = tube;
  24130. this.radialSegments = radialSegments;
  24131. this.tubularSegments = tubularSegments;
  24132. this.p = p;
  24133. this.q = q;
  24134. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24135. }
  24136. TorusKnot.prototype._regenerateVertexData = function () {
  24137. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  24138. };
  24139. TorusKnot.prototype.copy = function (id) {
  24140. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  24141. };
  24142. return TorusKnot;
  24143. })(_Primitive);
  24144. Primitives.TorusKnot = TorusKnot;
  24145. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24146. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24147. })(BABYLON || (BABYLON = {}));
  24148. //# sourceMappingURL=babylon.geometry.js.map
  24149. var BABYLON;
  24150. (function (BABYLON) {
  24151. var Gamepads = (function () {
  24152. function Gamepads(ongamedpadconnected) {
  24153. var _this = this;
  24154. this.babylonGamepads = [];
  24155. this.oneGamepadConnected = false;
  24156. this.isMonitoring = false;
  24157. this.gamepadEventSupported = 'GamepadEvent' in window;
  24158. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24159. 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=";
  24160. this._callbackGamepadConnected = ongamedpadconnected;
  24161. if (this.gamepadSupportAvailable) {
  24162. // Checking if the gamepad connected event is supported (like in Firefox)
  24163. if (this.gamepadEventSupported) {
  24164. window.addEventListener('gamepadconnected', function (evt) {
  24165. _this._onGamepadConnected(evt);
  24166. }, false);
  24167. window.addEventListener('gamepaddisconnected', function (evt) {
  24168. _this._onGamepadDisconnected(evt);
  24169. }, false);
  24170. }
  24171. else {
  24172. this._startMonitoringGamepads();
  24173. }
  24174. if (!this.oneGamepadConnected) {
  24175. this._insertGamepadDOMInstructions();
  24176. }
  24177. }
  24178. else {
  24179. this._insertGamepadDOMNotSupported();
  24180. }
  24181. }
  24182. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24183. Gamepads.gamepadDOMInfo = document.createElement("div");
  24184. var buttonAImage = document.createElement("img");
  24185. buttonAImage.src = this.buttonADataURL;
  24186. var spanMessage = document.createElement("span");
  24187. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24188. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24189. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24190. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24191. Gamepads.gamepadDOMInfo.style.width = "100%";
  24192. Gamepads.gamepadDOMInfo.style.height = "48px";
  24193. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24194. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24195. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24196. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24197. buttonAImage.style.position = "relative";
  24198. buttonAImage.style.bottom = "8px";
  24199. spanMessage.style.position = "relative";
  24200. spanMessage.style.fontSize = "32px";
  24201. spanMessage.style.bottom = "32px";
  24202. spanMessage.style.color = "green";
  24203. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24204. };
  24205. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24206. Gamepads.gamepadDOMInfo = document.createElement("div");
  24207. var spanMessage = document.createElement("span");
  24208. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24209. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24210. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24211. Gamepads.gamepadDOMInfo.style.width = "100%";
  24212. Gamepads.gamepadDOMInfo.style.height = "40px";
  24213. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24214. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24215. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24216. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24217. spanMessage.style.position = "relative";
  24218. spanMessage.style.fontSize = "32px";
  24219. spanMessage.style.color = "red";
  24220. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24221. };
  24222. Gamepads.prototype.dispose = function () {
  24223. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24224. };
  24225. Gamepads.prototype._onGamepadConnected = function (evt) {
  24226. var newGamepad = this._addNewGamepad(evt.gamepad);
  24227. if (this._callbackGamepadConnected)
  24228. this._callbackGamepadConnected(newGamepad);
  24229. this._startMonitoringGamepads();
  24230. };
  24231. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24232. if (!this.oneGamepadConnected) {
  24233. this.oneGamepadConnected = true;
  24234. if (Gamepads.gamepadDOMInfo) {
  24235. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24236. Gamepads.gamepadDOMInfo = null;
  24237. }
  24238. }
  24239. var newGamepad;
  24240. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24241. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24242. }
  24243. else {
  24244. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24245. }
  24246. this.babylonGamepads.push(newGamepad);
  24247. return newGamepad;
  24248. };
  24249. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24250. for (var i in this.babylonGamepads) {
  24251. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24252. this.babylonGamepads.splice(i, 1);
  24253. break;
  24254. }
  24255. }
  24256. // If no gamepads are left, stop the polling loop.
  24257. if (this.babylonGamepads.length == 0) {
  24258. this._stopMonitoringGamepads();
  24259. }
  24260. };
  24261. Gamepads.prototype._startMonitoringGamepads = function () {
  24262. if (!this.isMonitoring) {
  24263. this.isMonitoring = true;
  24264. this._checkGamepadsStatus();
  24265. }
  24266. };
  24267. Gamepads.prototype._stopMonitoringGamepads = function () {
  24268. this.isMonitoring = false;
  24269. };
  24270. Gamepads.prototype._checkGamepadsStatus = function () {
  24271. var _this = this;
  24272. // updating gamepad objects
  24273. this._updateGamepadObjects();
  24274. for (var i in this.babylonGamepads) {
  24275. this.babylonGamepads[i].update();
  24276. }
  24277. if (this.isMonitoring) {
  24278. if (window.requestAnimationFrame) {
  24279. window.requestAnimationFrame(function () {
  24280. _this._checkGamepadsStatus();
  24281. });
  24282. }
  24283. else if (window.mozRequestAnimationFrame) {
  24284. window.mozRequestAnimationFrame(function () {
  24285. _this._checkGamepadsStatus();
  24286. });
  24287. }
  24288. else if (window.webkitRequestAnimationFrame) {
  24289. window.webkitRequestAnimationFrame(function () {
  24290. _this._checkGamepadsStatus();
  24291. });
  24292. }
  24293. }
  24294. };
  24295. // This function is called only on Chrome, which does not yet support
  24296. // connection/disconnection events, but requires you to monitor
  24297. // an array for changes.
  24298. Gamepads.prototype._updateGamepadObjects = function () {
  24299. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24300. for (var i = 0; i < gamepads.length; i++) {
  24301. if (gamepads[i]) {
  24302. if (!(gamepads[i].index in this.babylonGamepads)) {
  24303. var newGamepad = this._addNewGamepad(gamepads[i]);
  24304. if (this._callbackGamepadConnected) {
  24305. this._callbackGamepadConnected(newGamepad);
  24306. }
  24307. }
  24308. else {
  24309. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24310. }
  24311. }
  24312. }
  24313. };
  24314. return Gamepads;
  24315. })();
  24316. BABYLON.Gamepads = Gamepads;
  24317. var StickValues = (function () {
  24318. function StickValues(x, y) {
  24319. this.x = x;
  24320. this.y = y;
  24321. }
  24322. return StickValues;
  24323. })();
  24324. BABYLON.StickValues = StickValues;
  24325. var Gamepad = (function () {
  24326. function Gamepad(id, index, browserGamepad) {
  24327. this.id = id;
  24328. this.index = index;
  24329. this.browserGamepad = browserGamepad;
  24330. if (this.browserGamepad.axes.length >= 2) {
  24331. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24332. }
  24333. if (this.browserGamepad.axes.length >= 4) {
  24334. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24335. }
  24336. }
  24337. Gamepad.prototype.onleftstickchanged = function (callback) {
  24338. this._onleftstickchanged = callback;
  24339. };
  24340. Gamepad.prototype.onrightstickchanged = function (callback) {
  24341. this._onrightstickchanged = callback;
  24342. };
  24343. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24344. get: function () {
  24345. return this._leftStick;
  24346. },
  24347. set: function (newValues) {
  24348. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24349. this._onleftstickchanged(newValues);
  24350. }
  24351. this._leftStick = newValues;
  24352. },
  24353. enumerable: true,
  24354. configurable: true
  24355. });
  24356. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24357. get: function () {
  24358. return this._rightStick;
  24359. },
  24360. set: function (newValues) {
  24361. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24362. this._onrightstickchanged(newValues);
  24363. }
  24364. this._rightStick = newValues;
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Gamepad.prototype.update = function () {
  24370. if (this._leftStick) {
  24371. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24372. }
  24373. if (this._rightStick) {
  24374. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24375. }
  24376. };
  24377. return Gamepad;
  24378. })();
  24379. BABYLON.Gamepad = Gamepad;
  24380. var GenericPad = (function (_super) {
  24381. __extends(GenericPad, _super);
  24382. function GenericPad(id, index, gamepad) {
  24383. _super.call(this, id, index, gamepad);
  24384. this.id = id;
  24385. this.index = index;
  24386. this.gamepad = gamepad;
  24387. this._buttons = new Array(gamepad.buttons.length);
  24388. }
  24389. GenericPad.prototype.onbuttondown = function (callback) {
  24390. this._onbuttondown = callback;
  24391. };
  24392. GenericPad.prototype.onbuttonup = function (callback) {
  24393. this._onbuttonup = callback;
  24394. };
  24395. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24396. if (newValue !== currentValue) {
  24397. if (this._onbuttondown && newValue === 1) {
  24398. this._onbuttondown(buttonIndex);
  24399. }
  24400. if (this._onbuttonup && newValue === 0) {
  24401. this._onbuttonup(buttonIndex);
  24402. }
  24403. }
  24404. return newValue;
  24405. };
  24406. GenericPad.prototype.update = function () {
  24407. _super.prototype.update.call(this);
  24408. for (var index = 0; index < this._buttons.length; index++) {
  24409. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24410. }
  24411. };
  24412. return GenericPad;
  24413. })(Gamepad);
  24414. BABYLON.GenericPad = GenericPad;
  24415. (function (Xbox360Button) {
  24416. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24417. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24418. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24419. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24420. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24421. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24422. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24423. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24424. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24425. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24426. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24427. var Xbox360Button = BABYLON.Xbox360Button;
  24428. (function (Xbox360Dpad) {
  24429. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24430. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24431. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24432. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24433. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24434. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24435. var Xbox360Pad = (function (_super) {
  24436. __extends(Xbox360Pad, _super);
  24437. function Xbox360Pad() {
  24438. _super.apply(this, arguments);
  24439. this._leftTrigger = 0;
  24440. this._rightTrigger = 0;
  24441. this._buttonA = 0;
  24442. this._buttonB = 0;
  24443. this._buttonX = 0;
  24444. this._buttonY = 0;
  24445. this._buttonBack = 0;
  24446. this._buttonStart = 0;
  24447. this._buttonLB = 0;
  24448. this._buttonRB = 0;
  24449. this._buttonLeftStick = 0;
  24450. this._buttonRightStick = 0;
  24451. this._dPadUp = 0;
  24452. this._dPadDown = 0;
  24453. this._dPadLeft = 0;
  24454. this._dPadRight = 0;
  24455. }
  24456. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24457. this._onlefttriggerchanged = callback;
  24458. };
  24459. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24460. this._onrighttriggerchanged = callback;
  24461. };
  24462. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24463. get: function () {
  24464. return this._leftTrigger;
  24465. },
  24466. set: function (newValue) {
  24467. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24468. this._onlefttriggerchanged(newValue);
  24469. }
  24470. this._leftTrigger = newValue;
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24476. get: function () {
  24477. return this._rightTrigger;
  24478. },
  24479. set: function (newValue) {
  24480. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24481. this._onrighttriggerchanged(newValue);
  24482. }
  24483. this._rightTrigger = newValue;
  24484. },
  24485. enumerable: true,
  24486. configurable: true
  24487. });
  24488. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24489. this._onbuttondown = callback;
  24490. };
  24491. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24492. this._onbuttonup = callback;
  24493. };
  24494. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24495. this._ondpaddown = callback;
  24496. };
  24497. Xbox360Pad.prototype.ondpadup = function (callback) {
  24498. this._ondpadup = callback;
  24499. };
  24500. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24501. if (newValue !== currentValue) {
  24502. if (this._onbuttondown && newValue === 1) {
  24503. this._onbuttondown(buttonType);
  24504. }
  24505. if (this._onbuttonup && newValue === 0) {
  24506. this._onbuttonup(buttonType);
  24507. }
  24508. }
  24509. return newValue;
  24510. };
  24511. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24512. if (newValue !== currentValue) {
  24513. if (this._ondpaddown && newValue === 1) {
  24514. this._ondpaddown(buttonType);
  24515. }
  24516. if (this._ondpadup && newValue === 0) {
  24517. this._ondpadup(buttonType);
  24518. }
  24519. }
  24520. return newValue;
  24521. };
  24522. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24523. get: function () {
  24524. return this._buttonA;
  24525. },
  24526. set: function (value) {
  24527. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24533. get: function () {
  24534. return this._buttonB;
  24535. },
  24536. set: function (value) {
  24537. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24538. },
  24539. enumerable: true,
  24540. configurable: true
  24541. });
  24542. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24543. get: function () {
  24544. return this._buttonX;
  24545. },
  24546. set: function (value) {
  24547. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24553. get: function () {
  24554. return this._buttonY;
  24555. },
  24556. set: function (value) {
  24557. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24563. get: function () {
  24564. return this._buttonStart;
  24565. },
  24566. set: function (value) {
  24567. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24568. },
  24569. enumerable: true,
  24570. configurable: true
  24571. });
  24572. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24573. get: function () {
  24574. return this._buttonBack;
  24575. },
  24576. set: function (value) {
  24577. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24583. get: function () {
  24584. return this._buttonLB;
  24585. },
  24586. set: function (value) {
  24587. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24593. get: function () {
  24594. return this._buttonRB;
  24595. },
  24596. set: function (value) {
  24597. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24603. get: function () {
  24604. return this._buttonLeftStick;
  24605. },
  24606. set: function (value) {
  24607. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24608. },
  24609. enumerable: true,
  24610. configurable: true
  24611. });
  24612. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24613. get: function () {
  24614. return this._buttonRightStick;
  24615. },
  24616. set: function (value) {
  24617. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24623. get: function () {
  24624. return this._dPadUp;
  24625. },
  24626. set: function (value) {
  24627. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24633. get: function () {
  24634. return this._dPadDown;
  24635. },
  24636. set: function (value) {
  24637. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24643. get: function () {
  24644. return this._dPadLeft;
  24645. },
  24646. set: function (value) {
  24647. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24653. get: function () {
  24654. return this._dPadRight;
  24655. },
  24656. set: function (value) {
  24657. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Xbox360Pad.prototype.update = function () {
  24663. _super.prototype.update.call(this);
  24664. this.buttonA = this.browserGamepad.buttons[0].value;
  24665. this.buttonB = this.browserGamepad.buttons[1].value;
  24666. this.buttonX = this.browserGamepad.buttons[2].value;
  24667. this.buttonY = this.browserGamepad.buttons[3].value;
  24668. this.buttonLB = this.browserGamepad.buttons[4].value;
  24669. this.buttonRB = this.browserGamepad.buttons[5].value;
  24670. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24671. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24672. this.buttonBack = this.browserGamepad.buttons[8].value;
  24673. this.buttonStart = this.browserGamepad.buttons[9].value;
  24674. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24675. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24676. this.dPadUp = this.browserGamepad.buttons[12].value;
  24677. this.dPadDown = this.browserGamepad.buttons[13].value;
  24678. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24679. this.dPadRight = this.browserGamepad.buttons[15].value;
  24680. };
  24681. return Xbox360Pad;
  24682. })(Gamepad);
  24683. BABYLON.Xbox360Pad = Xbox360Pad;
  24684. })(BABYLON || (BABYLON = {}));
  24685. //# sourceMappingURL=babylon.gamepads.js.map
  24686. var BABYLON;
  24687. (function (BABYLON) {
  24688. // We're mainly based on the logic defined into the FreeCamera code
  24689. var GamepadCamera = (function (_super) {
  24690. __extends(GamepadCamera, _super);
  24691. function GamepadCamera(name, position, scene) {
  24692. var _this = this;
  24693. _super.call(this, name, position, scene);
  24694. this.angularSensibility = 200;
  24695. this.moveSensibility = 75;
  24696. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24697. _this._onNewGameConnected(gamepad);
  24698. });
  24699. }
  24700. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24701. // Only the first gamepad can control the camera
  24702. if (gamepad.index === 0) {
  24703. this._gamepad = gamepad;
  24704. }
  24705. };
  24706. GamepadCamera.prototype._checkInputs = function () {
  24707. if (!this._gamepad) {
  24708. return;
  24709. }
  24710. var LSValues = this._gamepad.leftStick;
  24711. var normalizedLX = LSValues.x / this.moveSensibility;
  24712. var normalizedLY = LSValues.y / this.moveSensibility;
  24713. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24714. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24715. var RSValues = this._gamepad.rightStick;
  24716. var normalizedRX = RSValues.x / this.angularSensibility;
  24717. var normalizedRY = RSValues.y / this.angularSensibility;
  24718. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24719. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24720. ;
  24721. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24722. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24723. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24724. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24725. };
  24726. GamepadCamera.prototype.dispose = function () {
  24727. this._gamepads.dispose();
  24728. _super.prototype.dispose.call(this);
  24729. };
  24730. return GamepadCamera;
  24731. })(BABYLON.FreeCamera);
  24732. BABYLON.GamepadCamera = GamepadCamera;
  24733. })(BABYLON || (BABYLON = {}));
  24734. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24735. var BABYLON;
  24736. (function (BABYLON) {
  24737. var LinesMesh = (function (_super) {
  24738. __extends(LinesMesh, _super);
  24739. function LinesMesh(name, scene, updatable) {
  24740. if (updatable === void 0) { updatable = false; }
  24741. _super.call(this, name, scene);
  24742. this.color = new BABYLON.Color3(1, 1, 1);
  24743. this.alpha = 1;
  24744. this._indices = new Array();
  24745. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24746. attributes: ["position"],
  24747. uniforms: ["worldViewProjection", "color"],
  24748. needAlphaBlending: true
  24749. });
  24750. }
  24751. Object.defineProperty(LinesMesh.prototype, "material", {
  24752. get: function () {
  24753. return this._colorShader;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24759. get: function () {
  24760. return false;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24766. get: function () {
  24767. return false;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24773. var engine = this.getScene().getEngine();
  24774. var indexToBind = this._geometry.getIndexBuffer();
  24775. // VBOs
  24776. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24777. // Color
  24778. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24779. };
  24780. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24781. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24782. return;
  24783. }
  24784. var engine = this.getScene().getEngine();
  24785. // Draw order
  24786. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24787. };
  24788. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24789. return null;
  24790. };
  24791. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24792. this._colorShader.dispose();
  24793. _super.prototype.dispose.call(this, doNotRecurse);
  24794. };
  24795. return LinesMesh;
  24796. })(BABYLON.Mesh);
  24797. BABYLON.LinesMesh = LinesMesh;
  24798. })(BABYLON || (BABYLON = {}));
  24799. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24800. (function (BABYLON) {
  24801. var OutlineRenderer = (function () {
  24802. function OutlineRenderer(scene) {
  24803. this._scene = scene;
  24804. }
  24805. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24806. var _this = this;
  24807. if (useOverlay === void 0) { useOverlay = false; }
  24808. var scene = this._scene;
  24809. var engine = this._scene.getEngine();
  24810. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24811. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24812. return;
  24813. }
  24814. var mesh = subMesh.getRenderingMesh();
  24815. var material = subMesh.getMaterial();
  24816. engine.enableEffect(this._effect);
  24817. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24818. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24819. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24820. // Bones
  24821. if (mesh.useBones) {
  24822. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24823. }
  24824. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24825. // Alpha test
  24826. if (material && material.needAlphaTesting()) {
  24827. var alphaTexture = material.getAlphaTestTexture();
  24828. this._effect.setTexture("diffuseSampler", alphaTexture);
  24829. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24830. }
  24831. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  24832. _this._effect.setMatrix("world", world);
  24833. });
  24834. };
  24835. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24836. var defines = [];
  24837. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24838. var mesh = subMesh.getMesh();
  24839. var material = subMesh.getMaterial();
  24840. // Alpha test
  24841. if (material && material.needAlphaTesting()) {
  24842. defines.push("#define ALPHATEST");
  24843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24844. attribs.push(BABYLON.VertexBuffer.UVKind);
  24845. defines.push("#define UV1");
  24846. }
  24847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24848. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24849. defines.push("#define UV2");
  24850. }
  24851. }
  24852. // Bones
  24853. if (mesh.useBones) {
  24854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24856. defines.push("#define BONES");
  24857. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24858. }
  24859. // Instances
  24860. if (useInstances) {
  24861. defines.push("#define INSTANCES");
  24862. attribs.push("world0");
  24863. attribs.push("world1");
  24864. attribs.push("world2");
  24865. attribs.push("world3");
  24866. }
  24867. // Get correct effect
  24868. var join = defines.join("\n");
  24869. if (this._cachedDefines !== join) {
  24870. this._cachedDefines = join;
  24871. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24872. }
  24873. return this._effect.isReady();
  24874. };
  24875. return OutlineRenderer;
  24876. })();
  24877. BABYLON.OutlineRenderer = OutlineRenderer;
  24878. })(BABYLON || (BABYLON = {}));
  24879. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24880. (function (BABYLON) {
  24881. var MeshAssetTask = (function () {
  24882. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24883. this.name = name;
  24884. this.meshesNames = meshesNames;
  24885. this.rootUrl = rootUrl;
  24886. this.sceneFilename = sceneFilename;
  24887. this.isCompleted = false;
  24888. }
  24889. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24890. var _this = this;
  24891. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24892. _this.loadedMeshes = meshes;
  24893. _this.loadedParticleSystems = particleSystems;
  24894. _this.loadedSkeletons = skeletons;
  24895. _this.isCompleted = true;
  24896. if (_this.onSuccess) {
  24897. _this.onSuccess(_this);
  24898. }
  24899. onSuccess();
  24900. }, null, function () {
  24901. if (_this.onError) {
  24902. _this.onError(_this);
  24903. }
  24904. onError();
  24905. });
  24906. };
  24907. return MeshAssetTask;
  24908. })();
  24909. BABYLON.MeshAssetTask = MeshAssetTask;
  24910. var TextFileAssetTask = (function () {
  24911. function TextFileAssetTask(name, url) {
  24912. this.name = name;
  24913. this.url = url;
  24914. this.isCompleted = false;
  24915. }
  24916. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24917. var _this = this;
  24918. BABYLON.Tools.LoadFile(this.url, function (data) {
  24919. _this.text = data;
  24920. _this.isCompleted = true;
  24921. if (_this.onSuccess) {
  24922. _this.onSuccess(_this);
  24923. }
  24924. onSuccess();
  24925. }, null, scene.database, false, function () {
  24926. if (_this.onError) {
  24927. _this.onError(_this);
  24928. }
  24929. onError();
  24930. });
  24931. };
  24932. return TextFileAssetTask;
  24933. })();
  24934. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24935. var BinaryFileAssetTask = (function () {
  24936. function BinaryFileAssetTask(name, url) {
  24937. this.name = name;
  24938. this.url = url;
  24939. this.isCompleted = false;
  24940. }
  24941. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24942. var _this = this;
  24943. BABYLON.Tools.LoadFile(this.url, function (data) {
  24944. _this.data = data;
  24945. _this.isCompleted = true;
  24946. if (_this.onSuccess) {
  24947. _this.onSuccess(_this);
  24948. }
  24949. onSuccess();
  24950. }, null, scene.database, true, function () {
  24951. if (_this.onError) {
  24952. _this.onError(_this);
  24953. }
  24954. onError();
  24955. });
  24956. };
  24957. return BinaryFileAssetTask;
  24958. })();
  24959. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24960. var ImageAssetTask = (function () {
  24961. function ImageAssetTask(name, url) {
  24962. this.name = name;
  24963. this.url = url;
  24964. this.isCompleted = false;
  24965. }
  24966. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24967. var _this = this;
  24968. var img = new Image();
  24969. img.onload = function () {
  24970. _this.image = img;
  24971. _this.isCompleted = true;
  24972. if (_this.onSuccess) {
  24973. _this.onSuccess(_this);
  24974. }
  24975. onSuccess();
  24976. };
  24977. img.onerror = function () {
  24978. if (_this.onError) {
  24979. _this.onError(_this);
  24980. }
  24981. onError();
  24982. };
  24983. img.src = this.url;
  24984. };
  24985. return ImageAssetTask;
  24986. })();
  24987. BABYLON.ImageAssetTask = ImageAssetTask;
  24988. var TextureAssetTask = (function () {
  24989. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24991. this.name = name;
  24992. this.url = url;
  24993. this.noMipmap = noMipmap;
  24994. this.invertY = invertY;
  24995. this.samplingMode = samplingMode;
  24996. this.isCompleted = false;
  24997. }
  24998. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24999. var _this = this;
  25000. var onload = function () {
  25001. _this.isCompleted = true;
  25002. if (_this.onSuccess) {
  25003. _this.onSuccess(_this);
  25004. }
  25005. onSuccess();
  25006. };
  25007. var onerror = function () {
  25008. if (_this.onError) {
  25009. _this.onError(_this);
  25010. }
  25011. onError();
  25012. };
  25013. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25014. };
  25015. return TextureAssetTask;
  25016. })();
  25017. BABYLON.TextureAssetTask = TextureAssetTask;
  25018. var AssetsManager = (function () {
  25019. function AssetsManager(scene) {
  25020. this._tasks = new Array();
  25021. this._waitingTasksCount = 0;
  25022. this.useDefaultLoadingScreen = true;
  25023. this._scene = scene;
  25024. }
  25025. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25026. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25027. this._tasks.push(task);
  25028. return task;
  25029. };
  25030. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25031. var task = new TextFileAssetTask(taskName, url);
  25032. this._tasks.push(task);
  25033. return task;
  25034. };
  25035. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25036. var task = new BinaryFileAssetTask(taskName, url);
  25037. this._tasks.push(task);
  25038. return task;
  25039. };
  25040. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25041. var task = new ImageAssetTask(taskName, url);
  25042. this._tasks.push(task);
  25043. return task;
  25044. };
  25045. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25047. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25048. this._tasks.push(task);
  25049. return task;
  25050. };
  25051. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25052. this._waitingTasksCount--;
  25053. if (this._waitingTasksCount === 0) {
  25054. if (this.onFinish) {
  25055. this.onFinish(this._tasks);
  25056. }
  25057. this._scene.getEngine().hideLoadingUI();
  25058. }
  25059. };
  25060. AssetsManager.prototype._runTask = function (task) {
  25061. var _this = this;
  25062. task.run(this._scene, function () {
  25063. if (_this.onTaskSuccess) {
  25064. _this.onTaskSuccess(task);
  25065. }
  25066. _this._decreaseWaitingTasksCount();
  25067. }, function () {
  25068. if (_this.onTaskError) {
  25069. _this.onTaskError(task);
  25070. }
  25071. _this._decreaseWaitingTasksCount();
  25072. });
  25073. };
  25074. AssetsManager.prototype.reset = function () {
  25075. this._tasks = new Array();
  25076. return this;
  25077. };
  25078. AssetsManager.prototype.load = function () {
  25079. this._waitingTasksCount = this._tasks.length;
  25080. if (this._waitingTasksCount === 0) {
  25081. if (this.onFinish) {
  25082. this.onFinish(this._tasks);
  25083. }
  25084. return this;
  25085. }
  25086. if (this.useDefaultLoadingScreen) {
  25087. this._scene.getEngine().displayLoadingUI();
  25088. }
  25089. for (var index = 0; index < this._tasks.length; index++) {
  25090. var task = this._tasks[index];
  25091. this._runTask(task);
  25092. }
  25093. return this;
  25094. };
  25095. return AssetsManager;
  25096. })();
  25097. BABYLON.AssetsManager = AssetsManager;
  25098. })(BABYLON || (BABYLON = {}));
  25099. //# sourceMappingURL=babylon.assetsManager.js.map
  25100. var BABYLON;
  25101. (function (BABYLON) {
  25102. var VRDeviceOrientationCamera = (function (_super) {
  25103. __extends(VRDeviceOrientationCamera, _super);
  25104. function VRDeviceOrientationCamera(name, position, scene) {
  25105. _super.call(this, name, position, scene);
  25106. this._alpha = 0;
  25107. this._beta = 0;
  25108. this._gamma = 0;
  25109. }
  25110. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25111. this._alpha = +evt.alpha | 0;
  25112. this._beta = +evt.beta | 0;
  25113. this._gamma = +evt.gamma | 0;
  25114. if (this._gamma < 0) {
  25115. this._gamma = 90 + this._gamma;
  25116. }
  25117. else {
  25118. // Incline it in the correct angle.
  25119. this._gamma = 270 - this._gamma;
  25120. }
  25121. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25122. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25123. this.rotation.z = this._beta / 180.0 * Math.PI;
  25124. };
  25125. return VRDeviceOrientationCamera;
  25126. })(BABYLON.OculusCamera);
  25127. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25128. })(BABYLON || (BABYLON = {}));
  25129. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25130. var BABYLON;
  25131. (function (BABYLON) {
  25132. var WebVRCamera = (function (_super) {
  25133. __extends(WebVRCamera, _super);
  25134. function WebVRCamera(name, position, scene) {
  25135. _super.call(this, name, position, scene);
  25136. this._hmdDevice = null;
  25137. this._sensorDevice = null;
  25138. this._cacheState = null;
  25139. this._cacheQuaternion = new BABYLON.Quaternion();
  25140. this._cacheRotation = BABYLON.Vector3.Zero();
  25141. this._vrEnabled = false;
  25142. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25143. }
  25144. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25145. var size = devices.length;
  25146. var i = 0;
  25147. // Reset devices.
  25148. this._sensorDevice = null;
  25149. this._hmdDevice = null;
  25150. while (i < size && this._hmdDevice === null) {
  25151. if (devices[i] instanceof HMDVRDevice) {
  25152. this._hmdDevice = devices[i];
  25153. }
  25154. i++;
  25155. }
  25156. i = 0;
  25157. while (i < size && this._sensorDevice === null) {
  25158. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25159. this._sensorDevice = devices[i];
  25160. }
  25161. i++;
  25162. }
  25163. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25164. };
  25165. WebVRCamera.prototype._update = function () {
  25166. if (this._vrEnabled) {
  25167. this._cacheState = this._sensorDevice.getState();
  25168. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25169. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25170. this.rotation.x = -this._cacheRotation.z;
  25171. this.rotation.y = -this._cacheRotation.y;
  25172. this.rotation.z = this._cacheRotation.x;
  25173. }
  25174. _super.prototype._update.call(this);
  25175. };
  25176. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25177. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25178. if (navigator.getVRDevices) {
  25179. navigator.getVRDevices().then(this._getWebVRDevices);
  25180. }
  25181. else if (navigator.mozGetVRDevices) {
  25182. navigator.mozGetVRDevices(this._getWebVRDevices);
  25183. }
  25184. };
  25185. WebVRCamera.prototype.detachControl = function (element) {
  25186. _super.prototype.detachControl.call(this, element);
  25187. this._vrEnabled = false;
  25188. };
  25189. return WebVRCamera;
  25190. })(BABYLON.OculusCamera);
  25191. BABYLON.WebVRCamera = WebVRCamera;
  25192. })(BABYLON || (BABYLON = {}));
  25193. //# sourceMappingURL=babylon.webVRCamera.js.map
  25194. var BABYLON;
  25195. (function (BABYLON) {
  25196. // Standard optimizations
  25197. var SceneOptimization = (function () {
  25198. function SceneOptimization(priority) {
  25199. if (priority === void 0) { priority = 0; }
  25200. this.priority = priority;
  25201. this.apply = function (scene) {
  25202. return true; // Return true if everything that can be done was applied
  25203. };
  25204. }
  25205. return SceneOptimization;
  25206. })();
  25207. BABYLON.SceneOptimization = SceneOptimization;
  25208. var TextureOptimization = (function (_super) {
  25209. __extends(TextureOptimization, _super);
  25210. function TextureOptimization(priority, maximumSize) {
  25211. var _this = this;
  25212. if (priority === void 0) { priority = 0; }
  25213. if (maximumSize === void 0) { maximumSize = 1024; }
  25214. _super.call(this, priority);
  25215. this.priority = priority;
  25216. this.maximumSize = maximumSize;
  25217. this.apply = function (scene) {
  25218. var allDone = true;
  25219. for (var index = 0; index < scene.textures.length; index++) {
  25220. var texture = scene.textures[index];
  25221. if (!texture.canRescale) {
  25222. continue;
  25223. }
  25224. var currentSize = texture.getSize();
  25225. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25226. if (maxDimension > _this.maximumSize) {
  25227. texture.scale(0.5);
  25228. allDone = false;
  25229. }
  25230. }
  25231. return allDone;
  25232. };
  25233. }
  25234. return TextureOptimization;
  25235. })(SceneOptimization);
  25236. BABYLON.TextureOptimization = TextureOptimization;
  25237. var HardwareScalingOptimization = (function (_super) {
  25238. __extends(HardwareScalingOptimization, _super);
  25239. function HardwareScalingOptimization(priority, maximumScale) {
  25240. var _this = this;
  25241. if (priority === void 0) { priority = 0; }
  25242. if (maximumScale === void 0) { maximumScale = 2; }
  25243. _super.call(this, priority);
  25244. this.priority = priority;
  25245. this.maximumScale = maximumScale;
  25246. this._currentScale = 1;
  25247. this.apply = function (scene) {
  25248. _this._currentScale++;
  25249. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25250. return _this._currentScale >= _this.maximumScale;
  25251. };
  25252. }
  25253. return HardwareScalingOptimization;
  25254. })(SceneOptimization);
  25255. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25256. var ShadowsOptimization = (function (_super) {
  25257. __extends(ShadowsOptimization, _super);
  25258. function ShadowsOptimization() {
  25259. _super.apply(this, arguments);
  25260. this.apply = function (scene) {
  25261. scene.shadowsEnabled = false;
  25262. return true;
  25263. };
  25264. }
  25265. return ShadowsOptimization;
  25266. })(SceneOptimization);
  25267. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25268. var PostProcessesOptimization = (function (_super) {
  25269. __extends(PostProcessesOptimization, _super);
  25270. function PostProcessesOptimization() {
  25271. _super.apply(this, arguments);
  25272. this.apply = function (scene) {
  25273. scene.postProcessesEnabled = false;
  25274. return true;
  25275. };
  25276. }
  25277. return PostProcessesOptimization;
  25278. })(SceneOptimization);
  25279. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25280. var LensFlaresOptimization = (function (_super) {
  25281. __extends(LensFlaresOptimization, _super);
  25282. function LensFlaresOptimization() {
  25283. _super.apply(this, arguments);
  25284. this.apply = function (scene) {
  25285. scene.lensFlaresEnabled = false;
  25286. return true;
  25287. };
  25288. }
  25289. return LensFlaresOptimization;
  25290. })(SceneOptimization);
  25291. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25292. var ParticlesOptimization = (function (_super) {
  25293. __extends(ParticlesOptimization, _super);
  25294. function ParticlesOptimization() {
  25295. _super.apply(this, arguments);
  25296. this.apply = function (scene) {
  25297. scene.particlesEnabled = false;
  25298. return true;
  25299. };
  25300. }
  25301. return ParticlesOptimization;
  25302. })(SceneOptimization);
  25303. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25304. var RenderTargetsOptimization = (function (_super) {
  25305. __extends(RenderTargetsOptimization, _super);
  25306. function RenderTargetsOptimization() {
  25307. _super.apply(this, arguments);
  25308. this.apply = function (scene) {
  25309. scene.renderTargetsEnabled = false;
  25310. return true;
  25311. };
  25312. }
  25313. return RenderTargetsOptimization;
  25314. })(SceneOptimization);
  25315. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25316. var MergeMeshesOptimization = (function (_super) {
  25317. __extends(MergeMeshesOptimization, _super);
  25318. function MergeMeshesOptimization() {
  25319. var _this = this;
  25320. _super.apply(this, arguments);
  25321. this._canBeMerged = function (abstractMesh) {
  25322. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25323. return false;
  25324. }
  25325. var mesh = abstractMesh;
  25326. if (!mesh.isVisible || !mesh.isEnabled()) {
  25327. return false;
  25328. }
  25329. if (mesh.instances.length > 0) {
  25330. return false;
  25331. }
  25332. if (mesh.skeleton || mesh.hasLODLevels) {
  25333. return false;
  25334. }
  25335. return true;
  25336. };
  25337. this.apply = function (scene) {
  25338. var globalPool = scene.meshes.slice(0);
  25339. var globalLength = globalPool.length;
  25340. for (var index = 0; index < globalLength; index++) {
  25341. var currentPool = new Array();
  25342. var current = globalPool[index];
  25343. // Checks
  25344. if (!_this._canBeMerged(current)) {
  25345. continue;
  25346. }
  25347. currentPool.push(current);
  25348. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25349. var otherMesh = globalPool[subIndex];
  25350. if (!_this._canBeMerged(otherMesh)) {
  25351. continue;
  25352. }
  25353. if (otherMesh.material !== current.material) {
  25354. continue;
  25355. }
  25356. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25357. continue;
  25358. }
  25359. currentPool.push(otherMesh);
  25360. globalLength--;
  25361. globalPool.splice(subIndex, 1);
  25362. subIndex--;
  25363. }
  25364. if (currentPool.length < 2) {
  25365. continue;
  25366. }
  25367. // Merge meshes
  25368. BABYLON.Mesh.MergeMeshes(currentPool);
  25369. }
  25370. return true;
  25371. };
  25372. }
  25373. return MergeMeshesOptimization;
  25374. })(SceneOptimization);
  25375. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25376. // Options
  25377. var SceneOptimizerOptions = (function () {
  25378. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25379. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25380. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25381. this.targetFrameRate = targetFrameRate;
  25382. this.trackerDuration = trackerDuration;
  25383. this.optimizations = new Array();
  25384. }
  25385. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25386. var result = new SceneOptimizerOptions(targetFrameRate);
  25387. var priority = 0;
  25388. result.optimizations.push(new MergeMeshesOptimization(priority));
  25389. result.optimizations.push(new ShadowsOptimization(priority));
  25390. result.optimizations.push(new LensFlaresOptimization(priority));
  25391. // Next priority
  25392. priority++;
  25393. result.optimizations.push(new PostProcessesOptimization(priority));
  25394. result.optimizations.push(new ParticlesOptimization(priority));
  25395. // Next priority
  25396. priority++;
  25397. result.optimizations.push(new TextureOptimization(priority, 1024));
  25398. return result;
  25399. };
  25400. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25401. var result = new SceneOptimizerOptions(targetFrameRate);
  25402. var priority = 0;
  25403. result.optimizations.push(new MergeMeshesOptimization(priority));
  25404. result.optimizations.push(new ShadowsOptimization(priority));
  25405. result.optimizations.push(new LensFlaresOptimization(priority));
  25406. // Next priority
  25407. priority++;
  25408. result.optimizations.push(new PostProcessesOptimization(priority));
  25409. result.optimizations.push(new ParticlesOptimization(priority));
  25410. // Next priority
  25411. priority++;
  25412. result.optimizations.push(new TextureOptimization(priority, 512));
  25413. // Next priority
  25414. priority++;
  25415. result.optimizations.push(new RenderTargetsOptimization(priority));
  25416. // Next priority
  25417. priority++;
  25418. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25419. return result;
  25420. };
  25421. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25422. var result = new SceneOptimizerOptions(targetFrameRate);
  25423. var priority = 0;
  25424. result.optimizations.push(new MergeMeshesOptimization(priority));
  25425. result.optimizations.push(new ShadowsOptimization(priority));
  25426. result.optimizations.push(new LensFlaresOptimization(priority));
  25427. // Next priority
  25428. priority++;
  25429. result.optimizations.push(new PostProcessesOptimization(priority));
  25430. result.optimizations.push(new ParticlesOptimization(priority));
  25431. // Next priority
  25432. priority++;
  25433. result.optimizations.push(new TextureOptimization(priority, 256));
  25434. // Next priority
  25435. priority++;
  25436. result.optimizations.push(new RenderTargetsOptimization(priority));
  25437. // Next priority
  25438. priority++;
  25439. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25440. return result;
  25441. };
  25442. return SceneOptimizerOptions;
  25443. })();
  25444. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25445. // Scene optimizer tool
  25446. var SceneOptimizer = (function () {
  25447. function SceneOptimizer() {
  25448. }
  25449. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25450. // TODO: add an epsilon
  25451. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25452. if (onSuccess) {
  25453. onSuccess();
  25454. }
  25455. return;
  25456. }
  25457. // Apply current level of optimizations
  25458. var allDone = true;
  25459. var noOptimizationApplied = true;
  25460. for (var index = 0; index < options.optimizations.length; index++) {
  25461. var optimization = options.optimizations[index];
  25462. if (optimization.priority === currentPriorityLevel) {
  25463. noOptimizationApplied = false;
  25464. allDone = allDone && optimization.apply(scene);
  25465. }
  25466. }
  25467. // If no optimization was applied, this is a failure :(
  25468. if (noOptimizationApplied) {
  25469. if (onFailure) {
  25470. onFailure();
  25471. }
  25472. return;
  25473. }
  25474. // If all optimizations were done, move to next level
  25475. if (allDone) {
  25476. currentPriorityLevel++;
  25477. }
  25478. // Let's the system running for a specific amount of time before checking FPS
  25479. scene.executeWhenReady(function () {
  25480. setTimeout(function () {
  25481. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25482. }, options.trackerDuration);
  25483. });
  25484. };
  25485. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25486. if (!options) {
  25487. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25488. }
  25489. // Let's the system running for a specific amount of time before checking FPS
  25490. scene.executeWhenReady(function () {
  25491. setTimeout(function () {
  25492. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25493. }, options.trackerDuration);
  25494. });
  25495. };
  25496. return SceneOptimizer;
  25497. })();
  25498. BABYLON.SceneOptimizer = SceneOptimizer;
  25499. })(BABYLON || (BABYLON = {}));
  25500. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25501. (function (BABYLON) {
  25502. var Internals;
  25503. (function (Internals) {
  25504. var MeshLODLevel = (function () {
  25505. function MeshLODLevel(distance, mesh) {
  25506. this.distance = distance;
  25507. this.mesh = mesh;
  25508. }
  25509. return MeshLODLevel;
  25510. })();
  25511. Internals.MeshLODLevel = MeshLODLevel;
  25512. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25513. })(BABYLON || (BABYLON = {}));
  25514. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25515. (function (BABYLON) {
  25516. var AudioEngine = (function () {
  25517. function AudioEngine() {
  25518. this.audioContext = null;
  25519. this.canUseWebAudio = false;
  25520. this.WarnedWebAudioUnsupported = false;
  25521. try {
  25522. if (typeof AudioContext !== 'undefined') {
  25523. this.audioContext = new AudioContext();
  25524. this.canUseWebAudio = true;
  25525. }
  25526. else if (typeof webkitAudioContext !== 'undefined') {
  25527. this.audioContext = new webkitAudioContext();
  25528. this.canUseWebAudio = true;
  25529. }
  25530. }
  25531. catch (e) {
  25532. this.canUseWebAudio = false;
  25533. BABYLON.Tools.Error("Web Audio: " + e.message);
  25534. }
  25535. // create a global volume gain node
  25536. if (this.canUseWebAudio) {
  25537. this.masterGain = this.audioContext.createGain();
  25538. this.masterGain.gain.value = 1;
  25539. this.masterGain.connect(this.audioContext.destination);
  25540. }
  25541. }
  25542. AudioEngine.prototype.dispose = function () {
  25543. if (this.canUseWebAudio) {
  25544. if (this._connectedAnalyser) {
  25545. this._connectedAnalyser.stopDebugCanvas();
  25546. this._connectedAnalyser.dispose();
  25547. this.masterGain.disconnect();
  25548. this.masterGain.connect(this.audioContext.destination);
  25549. this._connectedAnalyser = null;
  25550. }
  25551. this.masterGain.gain.value = 1;
  25552. }
  25553. this.WarnedWebAudioUnsupported = false;
  25554. };
  25555. AudioEngine.prototype.getGlobalVolume = function () {
  25556. if (this.canUseWebAudio) {
  25557. return this.masterGain.gain.value;
  25558. }
  25559. else {
  25560. return -1;
  25561. }
  25562. };
  25563. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25564. if (this.canUseWebAudio) {
  25565. this.masterGain.gain.value = newVolume;
  25566. }
  25567. };
  25568. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25569. if (this._connectedAnalyser) {
  25570. this._connectedAnalyser.stopDebugCanvas();
  25571. }
  25572. this._connectedAnalyser = analyser;
  25573. if (this.canUseWebAudio) {
  25574. this.masterGain.disconnect();
  25575. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25576. }
  25577. };
  25578. return AudioEngine;
  25579. })();
  25580. BABYLON.AudioEngine = AudioEngine;
  25581. })(BABYLON || (BABYLON = {}));
  25582. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25583. (function (BABYLON) {
  25584. var Sound = (function () {
  25585. /**
  25586. * Create a sound and attach it to a scene
  25587. * @param name Name of your sound
  25588. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25589. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25590. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25591. */
  25592. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25593. var _this = this;
  25594. this.autoplay = false;
  25595. this.loop = false;
  25596. this.useCustomAttenuation = false;
  25597. this.spatialSound = false;
  25598. this.refDistance = 1;
  25599. this.rolloffFactor = 1;
  25600. this.maxDistance = 100;
  25601. this.distanceModel = "linear";
  25602. this.panningModel = "HRTF";
  25603. this._playbackRate = 1;
  25604. this._startTime = 0;
  25605. this._startOffset = 0;
  25606. this._position = BABYLON.Vector3.Zero();
  25607. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25608. this._volume = 1;
  25609. this._isLoaded = false;
  25610. this._isReadyToPlay = false;
  25611. this._isPlaying = false;
  25612. this._isDirectional = false;
  25613. // Used if you'd like to create a directional sound.
  25614. // If not set, the sound will be omnidirectional
  25615. this._coneInnerAngle = 360;
  25616. this._coneOuterAngle = 360;
  25617. this._coneOuterGain = 0;
  25618. this.name = name;
  25619. this._scene = scene;
  25620. this._readyToPlayCallback = readyToPlayCallback;
  25621. // Default custom attenuation function is a linear attenuation
  25622. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25623. if (currentDistance < maxDistance) {
  25624. return currentVolume * (1 - currentDistance / maxDistance);
  25625. }
  25626. else {
  25627. return 0;
  25628. }
  25629. };
  25630. if (options) {
  25631. this.autoplay = options.autoplay || false;
  25632. this.loop = options.loop || false;
  25633. // if volume === 0, we need another way to check this option
  25634. if (options.volume !== undefined) {
  25635. this._volume = options.volume;
  25636. }
  25637. this.spatialSound = options.spatialSound || false;
  25638. this.maxDistance = options.maxDistance || 100;
  25639. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25640. this.rolloffFactor = options.rolloffFactor || 1;
  25641. this.refDistance = options.refDistance || 1;
  25642. this.distanceModel = options.distanceModel || "linear";
  25643. this.panningModel = options.panningModel || "HRTF";
  25644. this._playbackRate = options.playbackRate || 1;
  25645. }
  25646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25647. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25648. this._soundGain.gain.value = this._volume;
  25649. this._inputAudioNode = this._soundGain;
  25650. this._ouputAudioNode = this._soundGain;
  25651. if (this.spatialSound) {
  25652. this._createSpatialParameters();
  25653. }
  25654. this._scene.mainSoundTrack.AddSound(this);
  25655. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25656. if (urlOrArrayBuffer) {
  25657. // If it's an URL
  25658. if (typeof (urlOrArrayBuffer) === "string") {
  25659. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25660. _this._soundLoaded(data);
  25661. }, null, null, true);
  25662. }
  25663. else {
  25664. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25665. this._soundLoaded(urlOrArrayBuffer);
  25666. }
  25667. else {
  25668. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25669. }
  25670. }
  25671. }
  25672. }
  25673. else {
  25674. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25675. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25676. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25677. }
  25678. }
  25679. }
  25680. Sound.prototype.dispose = function () {
  25681. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25682. if (this._isPlaying) {
  25683. this.stop();
  25684. }
  25685. this._isReadyToPlay = false;
  25686. if (this.soundTrackId === -1) {
  25687. this._scene.mainSoundTrack.RemoveSound(this);
  25688. }
  25689. else {
  25690. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25691. }
  25692. this._soundGain.disconnect();
  25693. this._soundSource.disconnect();
  25694. if (this._soundPanner) {
  25695. this._soundPanner.disconnect();
  25696. this._soundPanner = null;
  25697. }
  25698. this._audioBuffer = null;
  25699. this._soundGain = null;
  25700. this._soundSource = null;
  25701. if (this._connectedMesh) {
  25702. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25703. this._connectedMesh = null;
  25704. }
  25705. }
  25706. };
  25707. Sound.prototype._soundLoaded = function (audioData) {
  25708. var _this = this;
  25709. this._isLoaded = true;
  25710. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25711. _this._audioBuffer = buffer;
  25712. _this._isReadyToPlay = true;
  25713. if (_this.autoplay) {
  25714. _this.play();
  25715. }
  25716. if (_this._readyToPlayCallback) {
  25717. _this._readyToPlayCallback();
  25718. }
  25719. }, function (error) {
  25720. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25721. });
  25722. };
  25723. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25724. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25725. this._audioBuffer = audioBuffer;
  25726. this._isReadyToPlay = true;
  25727. }
  25728. };
  25729. Sound.prototype.updateOptions = function (options) {
  25730. if (options) {
  25731. this.loop = options.loop || this.loop;
  25732. this.maxDistance = options.maxDistance || this.maxDistance;
  25733. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25734. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25735. this.refDistance = options.refDistance || this.refDistance;
  25736. this.distanceModel = options.distanceModel || this.distanceModel;
  25737. this.panningModel = options.panningModel || this.panningModel;
  25738. this._playbackRate = options.playbackRate || this._playbackRate;
  25739. }
  25740. };
  25741. Sound.prototype._createSpatialParameters = function () {
  25742. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25743. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25744. if (this.useCustomAttenuation) {
  25745. // Tricks to disable in a way embedded Web Audio attenuation
  25746. this._soundPanner.distanceModel = "linear";
  25747. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25748. this._soundPanner.refDistance = 1;
  25749. this._soundPanner.rolloffFactor = 1;
  25750. this._soundPanner.panningModel = "HRTF";
  25751. }
  25752. else {
  25753. this._soundPanner.distanceModel = this.distanceModel;
  25754. this._soundPanner.maxDistance = this.maxDistance;
  25755. this._soundPanner.refDistance = this.refDistance;
  25756. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25757. this._soundPanner.panningModel = this.panningModel;
  25758. }
  25759. this._soundPanner.connect(this._ouputAudioNode);
  25760. this._inputAudioNode = this._soundPanner;
  25761. }
  25762. };
  25763. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25765. this._ouputAudioNode.disconnect();
  25766. this._ouputAudioNode.connect(soundTrackAudioNode);
  25767. }
  25768. };
  25769. /**
  25770. * Transform this sound into a directional source
  25771. * @param coneInnerAngle Size of the inner cone in degree
  25772. * @param coneOuterAngle Size of the outer cone in degree
  25773. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25774. */
  25775. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25776. if (coneOuterAngle < coneInnerAngle) {
  25777. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25778. return;
  25779. }
  25780. this._coneInnerAngle = coneInnerAngle;
  25781. this._coneOuterAngle = coneOuterAngle;
  25782. this._coneOuterGain = coneOuterGain;
  25783. this._isDirectional = true;
  25784. if (this._isPlaying && this.loop) {
  25785. this.stop();
  25786. this.play();
  25787. }
  25788. };
  25789. Sound.prototype.setPosition = function (newPosition) {
  25790. this._position = newPosition;
  25791. if (this._isPlaying && this.spatialSound) {
  25792. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25793. }
  25794. };
  25795. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25796. this._localDirection = newLocalDirection;
  25797. if (this._connectedMesh && this._isPlaying) {
  25798. this._updateDirection();
  25799. }
  25800. };
  25801. Sound.prototype._updateDirection = function () {
  25802. var mat = this._connectedMesh.getWorldMatrix();
  25803. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25804. direction.normalize();
  25805. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25806. };
  25807. Sound.prototype.updateDistanceFromListener = function () {
  25808. if (this._connectedMesh && this.useCustomAttenuation) {
  25809. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25810. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25811. }
  25812. };
  25813. Sound.prototype.setAttenuationFunction = function (callback) {
  25814. this._customAttenuationFunction = callback;
  25815. };
  25816. /**
  25817. * Play the sound
  25818. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25819. */
  25820. Sound.prototype.play = function (time) {
  25821. if (this._isReadyToPlay) {
  25822. try {
  25823. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25824. if (!this._soundSource) {
  25825. if (this.spatialSound) {
  25826. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25827. if (this._isDirectional) {
  25828. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25829. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25830. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25831. if (this._connectedMesh) {
  25832. this._updateDirection();
  25833. }
  25834. else {
  25835. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25836. }
  25837. }
  25838. }
  25839. }
  25840. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25841. this._soundSource.buffer = this._audioBuffer;
  25842. this._soundSource.connect(this._inputAudioNode);
  25843. this._soundSource.loop = this.loop;
  25844. this._soundSource.playbackRate.value = this._playbackRate;
  25845. this._startTime = startTime;
  25846. if (this.onended) {
  25847. this._soundSource.onended = this.onended;
  25848. }
  25849. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25850. this._isPlaying = true;
  25851. }
  25852. catch (ex) {
  25853. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25854. }
  25855. }
  25856. };
  25857. /**
  25858. * Stop the sound
  25859. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25860. */
  25861. Sound.prototype.stop = function (time) {
  25862. if (this._isPlaying) {
  25863. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25864. this._soundSource.stop(stopTime);
  25865. this._isPlaying = false;
  25866. }
  25867. };
  25868. Sound.prototype.pause = function () {
  25869. if (this._isPlaying) {
  25870. this._soundSource.stop(0);
  25871. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25872. }
  25873. };
  25874. Sound.prototype.setVolume = function (newVolume, time) {
  25875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25876. if (time) {
  25877. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  25878. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  25879. }
  25880. else {
  25881. this._soundGain.gain.value = newVolume;
  25882. }
  25883. }
  25884. this._volume = newVolume;
  25885. };
  25886. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25887. this._playbackRate = newPlaybackRate;
  25888. if (this._isPlaying) {
  25889. this._soundSource.playbackRate.value = this._playbackRate;
  25890. }
  25891. };
  25892. Sound.prototype.getVolume = function () {
  25893. return this._volume;
  25894. };
  25895. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25896. var _this = this;
  25897. this._connectedMesh = meshToConnectTo;
  25898. if (!this.spatialSound) {
  25899. this._createSpatialParameters();
  25900. this.spatialSound = true;
  25901. if (this._isPlaying && this.loop) {
  25902. this.stop();
  25903. this.play();
  25904. }
  25905. }
  25906. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  25907. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25908. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25909. };
  25910. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25911. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  25912. if (this._isDirectional && this._isPlaying) {
  25913. this._updateDirection();
  25914. }
  25915. };
  25916. return Sound;
  25917. })();
  25918. BABYLON.Sound = Sound;
  25919. })(BABYLON || (BABYLON = {}));
  25920. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25921. (function (BABYLON) {
  25922. var SoundTrack = (function () {
  25923. function SoundTrack(scene, options) {
  25924. this.id = -1;
  25925. this._isMainTrack = false;
  25926. this._scene = scene;
  25927. this._audioEngine = BABYLON.Engine.audioEngine;
  25928. this.soundCollection = new Array();
  25929. if (this._audioEngine.canUseWebAudio) {
  25930. this._trackGain = this._audioEngine.audioContext.createGain();
  25931. this._trackGain.connect(this._audioEngine.masterGain);
  25932. if (options) {
  25933. if (options.volume) {
  25934. this._trackGain.gain.value = options.volume;
  25935. }
  25936. if (options.mainTrack) {
  25937. this._isMainTrack = options.mainTrack;
  25938. }
  25939. }
  25940. }
  25941. if (!this._isMainTrack) {
  25942. this._scene.soundTracks.push(this);
  25943. this.id = this._scene.soundTracks.length - 1;
  25944. }
  25945. }
  25946. SoundTrack.prototype.dispose = function () {
  25947. if (this._audioEngine.canUseWebAudio) {
  25948. if (this._connectedAnalyser) {
  25949. this._connectedAnalyser.stopDebugCanvas();
  25950. }
  25951. while (this.soundCollection.length) {
  25952. this.soundCollection[0].dispose();
  25953. }
  25954. this._trackGain.disconnect();
  25955. this._trackGain = null;
  25956. }
  25957. };
  25958. SoundTrack.prototype.AddSound = function (sound) {
  25959. sound.connectToSoundTrackAudioNode(this._trackGain);
  25960. if (sound.soundTrackId) {
  25961. if (sound.soundTrackId === -1) {
  25962. this._scene.mainSoundTrack.RemoveSound(sound);
  25963. }
  25964. else {
  25965. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25966. }
  25967. }
  25968. this.soundCollection.push(sound);
  25969. sound.soundTrackId = this.id;
  25970. };
  25971. SoundTrack.prototype.RemoveSound = function (sound) {
  25972. var index = this.soundCollection.indexOf(sound);
  25973. if (index !== -1) {
  25974. this.soundCollection.splice(index, 1);
  25975. }
  25976. };
  25977. SoundTrack.prototype.setVolume = function (newVolume) {
  25978. if (this._audioEngine.canUseWebAudio) {
  25979. this._trackGain.gain.value = newVolume;
  25980. }
  25981. };
  25982. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25983. if (this._connectedAnalyser) {
  25984. this._connectedAnalyser.stopDebugCanvas();
  25985. }
  25986. this._connectedAnalyser = analyser;
  25987. if (this._audioEngine.canUseWebAudio) {
  25988. this._trackGain.disconnect();
  25989. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25990. }
  25991. };
  25992. return SoundTrack;
  25993. })();
  25994. BABYLON.SoundTrack = SoundTrack;
  25995. })(BABYLON || (BABYLON = {}));
  25996. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25997. (function (BABYLON) {
  25998. var DebugLayer = (function () {
  25999. function DebugLayer(scene) {
  26000. var _this = this;
  26001. this._enabled = false;
  26002. this._labelsEnabled = false;
  26003. this._displayStatistics = true;
  26004. this._displayTree = false;
  26005. this._displayLogs = false;
  26006. this._identityMatrix = BABYLON.Matrix.Identity();
  26007. this.axisRatio = 0.02;
  26008. this.accentColor = "orange";
  26009. this._scene = scene;
  26010. this._syncPositions = function () {
  26011. var engine = _this._scene.getEngine();
  26012. var canvasRect = engine.getRenderingCanvasClientRect();
  26013. if (_this._showUI) {
  26014. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26015. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26016. _this._statsDiv.style.width = "400px";
  26017. _this._statsDiv.style.height = "auto";
  26018. _this._statsSubsetDiv.style.maxHeight = "240px";
  26019. _this._optionsDiv.style.left = "0px";
  26020. _this._optionsDiv.style.top = "10px";
  26021. _this._optionsDiv.style.width = "200px";
  26022. _this._optionsDiv.style.height = "auto";
  26023. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26024. _this._logDiv.style.left = "0px";
  26025. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26026. _this._logDiv.style.width = "600px";
  26027. _this._logDiv.style.height = "160px";
  26028. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26029. _this._treeDiv.style.top = "10px";
  26030. _this._treeDiv.style.width = "300px";
  26031. _this._treeDiv.style.height = "auto";
  26032. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26033. }
  26034. _this._globalDiv.style.left = canvasRect.left + "px";
  26035. _this._globalDiv.style.top = canvasRect.top + "px";
  26036. _this._drawingCanvas.style.left = "0px";
  26037. _this._drawingCanvas.style.top = "0px";
  26038. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26039. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26040. var devicePixelRatio = window.devicePixelRatio || 1;
  26041. var context = _this._drawingContext;
  26042. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26043. _this._ratio = devicePixelRatio / backingStoreRatio;
  26044. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26045. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26046. };
  26047. this._onCanvasClick = function (evt) {
  26048. _this._clickPosition = {
  26049. x: evt.clientX * _this._ratio,
  26050. y: evt.clientY * _this._ratio
  26051. };
  26052. };
  26053. this._syncData = function () {
  26054. if (_this._showUI) {
  26055. if (_this._displayStatistics) {
  26056. _this._displayStats();
  26057. _this._statsDiv.style.display = "";
  26058. }
  26059. else {
  26060. _this._statsDiv.style.display = "none";
  26061. }
  26062. if (_this._displayLogs) {
  26063. _this._logDiv.style.display = "";
  26064. }
  26065. else {
  26066. _this._logDiv.style.display = "none";
  26067. }
  26068. if (_this._displayTree) {
  26069. _this._treeDiv.style.display = "";
  26070. if (_this._needToRefreshMeshesTree) {
  26071. _this._needToRefreshMeshesTree = false;
  26072. _this._refreshMeshesTreeContent();
  26073. }
  26074. }
  26075. else {
  26076. _this._treeDiv.style.display = "none";
  26077. }
  26078. }
  26079. if (_this._labelsEnabled || !_this._showUI) {
  26080. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26081. var engine = _this._scene.getEngine();
  26082. var viewport = _this._scene.activeCamera.viewport;
  26083. var globalViewport = viewport.toGlobal(engine);
  26084. // Meshes
  26085. var meshes = _this._scene.getActiveMeshes();
  26086. for (var index = 0; index < meshes.length; index++) {
  26087. var mesh = meshes.data[index];
  26088. var position = mesh.getBoundingInfo().boundingSphere.center;
  26089. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26090. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26091. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26092. }
  26093. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26094. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26095. mesh.renderOverlay = !mesh.renderOverlay;
  26096. }, function () {
  26097. return mesh.renderOverlay ? 'red' : 'black';
  26098. });
  26099. }
  26100. }
  26101. // Cameras
  26102. var cameras = _this._scene.cameras;
  26103. for (index = 0; index < cameras.length; index++) {
  26104. var camera = cameras[index];
  26105. if (camera === _this._scene.activeCamera) {
  26106. continue;
  26107. }
  26108. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26109. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26110. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26111. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  26112. _this._scene.activeCamera = camera;
  26113. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  26114. }, function () {
  26115. return "purple";
  26116. });
  26117. }
  26118. }
  26119. // Lights
  26120. var lights = _this._scene.lights;
  26121. for (index = 0; index < lights.length; index++) {
  26122. var light = lights[index];
  26123. if (light.position) {
  26124. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  26125. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26126. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26127. light.setEnabled(!light.isEnabled());
  26128. }, function () {
  26129. return light.isEnabled() ? "orange" : "gray";
  26130. });
  26131. }
  26132. }
  26133. }
  26134. }
  26135. _this._clickPosition = undefined;
  26136. };
  26137. }
  26138. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26139. while (this._treeSubsetDiv.hasChildNodes()) {
  26140. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26141. }
  26142. // Add meshes
  26143. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26144. sortedArray.sort(function (a, b) {
  26145. if (a.name === b.name) {
  26146. return 0;
  26147. }
  26148. return (a.name > b.name) ? 1 : -1;
  26149. });
  26150. for (var index = 0; index < sortedArray.length; index++) {
  26151. var mesh = sortedArray[index];
  26152. if (!mesh.isEnabled()) {
  26153. continue;
  26154. }
  26155. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26156. m.isVisible = element.checked;
  26157. }, mesh);
  26158. }
  26159. };
  26160. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26161. this._drawingContext.beginPath();
  26162. this._drawingContext.moveTo(zero.x, zero.y);
  26163. this._drawingContext.lineTo(unit.x, unit.y);
  26164. this._drawingContext.strokeStyle = color;
  26165. this._drawingContext.lineWidth = 4;
  26166. this._drawingContext.stroke();
  26167. this._drawingContext.font = "normal 14px Segoe UI";
  26168. this._drawingContext.fillStyle = color;
  26169. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26170. };
  26171. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26172. var position = mesh.getBoundingInfo().boundingSphere.center;
  26173. var worldMatrix = mesh.getWorldMatrix();
  26174. 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());
  26175. var unit = (unprojectedVector.subtract(position)).length();
  26176. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26177. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26178. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26179. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26180. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26181. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26182. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26183. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26184. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26185. };
  26186. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26187. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26188. this._drawingContext.font = "normal 12px Segoe UI";
  26189. var textMetrics = this._drawingContext.measureText(text);
  26190. var centerX = projectedPosition.x - textMetrics.width / 2;
  26191. var centerY = projectedPosition.y;
  26192. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26193. onClick();
  26194. }
  26195. this._drawingContext.beginPath();
  26196. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26197. this._drawingContext.fillStyle = getFillStyle();
  26198. this._drawingContext.globalAlpha = 0.5;
  26199. this._drawingContext.fill();
  26200. this._drawingContext.globalAlpha = 1.0;
  26201. this._drawingContext.strokeStyle = '#FFFFFF';
  26202. this._drawingContext.lineWidth = 1;
  26203. this._drawingContext.stroke();
  26204. this._drawingContext.fillStyle = "#FFFFFF";
  26205. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26206. this._drawingContext.beginPath();
  26207. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26208. this._drawingContext.fill();
  26209. }
  26210. };
  26211. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26212. if (!this._clickPosition) {
  26213. return false;
  26214. }
  26215. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26216. return false;
  26217. }
  26218. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26219. return false;
  26220. }
  26221. return true;
  26222. };
  26223. DebugLayer.prototype.isVisible = function () {
  26224. return this._enabled;
  26225. };
  26226. DebugLayer.prototype.hide = function () {
  26227. if (!this._enabled) {
  26228. return;
  26229. }
  26230. this._enabled = false;
  26231. var engine = this._scene.getEngine();
  26232. this._scene.unregisterAfterRender(this._syncData);
  26233. document.body.removeChild(this._globalDiv);
  26234. window.removeEventListener("resize", this._syncPositions);
  26235. this._scene.forceShowBoundingBoxes = false;
  26236. this._scene.forceWireframe = false;
  26237. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26238. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26239. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26240. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26241. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26242. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26243. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26244. this._scene.shadowsEnabled = true;
  26245. this._scene.particlesEnabled = true;
  26246. this._scene.postProcessesEnabled = true;
  26247. this._scene.collisionsEnabled = true;
  26248. this._scene.lightsEnabled = true;
  26249. this._scene.texturesEnabled = true;
  26250. this._scene.lensFlaresEnabled = true;
  26251. this._scene.proceduralTexturesEnabled = true;
  26252. this._scene.renderTargetsEnabled = true;
  26253. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26254. };
  26255. DebugLayer.prototype.show = function (showUI) {
  26256. if (showUI === void 0) { showUI = true; }
  26257. if (this._enabled) {
  26258. return;
  26259. }
  26260. this._enabled = true;
  26261. this._showUI = showUI;
  26262. var engine = this._scene.getEngine();
  26263. this._globalDiv = document.createElement("div");
  26264. document.body.appendChild(this._globalDiv);
  26265. this._generateDOMelements();
  26266. window.addEventListener("resize", this._syncPositions);
  26267. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26268. this._syncPositions();
  26269. this._scene.registerAfterRender(this._syncData);
  26270. };
  26271. DebugLayer.prototype._clearLabels = function () {
  26272. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26273. for (var index = 0; index < this._scene.meshes.length; index++) {
  26274. var mesh = this._scene.meshes[index];
  26275. mesh.renderOverlay = false;
  26276. }
  26277. };
  26278. DebugLayer.prototype._generateheader = function (root, text) {
  26279. var header = document.createElement("div");
  26280. header.innerHTML = text + "&nbsp;";
  26281. header.style.textAlign = "right";
  26282. header.style.width = "100%";
  26283. header.style.color = "white";
  26284. header.style.backgroundColor = "Black";
  26285. header.style.padding = "5px 5px 4px 0px";
  26286. header.style.marginLeft = "-5px";
  26287. header.style.fontWeight = "bold";
  26288. root.appendChild(header);
  26289. };
  26290. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26291. var label = document.createElement("label");
  26292. label.innerHTML = title;
  26293. label.style.color = color;
  26294. root.appendChild(label);
  26295. root.appendChild(document.createElement("br"));
  26296. };
  26297. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26298. if (tag === void 0) { tag = null; }
  26299. var label = document.createElement("label");
  26300. var boundingBoxesCheckbox = document.createElement("input");
  26301. boundingBoxesCheckbox.type = "checkbox";
  26302. boundingBoxesCheckbox.checked = initialState;
  26303. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26304. task(evt.target, tag);
  26305. });
  26306. label.appendChild(boundingBoxesCheckbox);
  26307. var container = document.createElement("span");
  26308. var leftPart = document.createElement("span");
  26309. var rightPart = document.createElement("span");
  26310. rightPart.style.cssFloat = "right";
  26311. leftPart.innerHTML = leftTitle;
  26312. rightPart.innerHTML = rightTitle;
  26313. rightPart.style.fontSize = "12px";
  26314. rightPart.style.maxWidth = "200px";
  26315. container.appendChild(leftPart);
  26316. container.appendChild(rightPart);
  26317. label.appendChild(container);
  26318. root.appendChild(label);
  26319. root.appendChild(document.createElement("br"));
  26320. };
  26321. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26322. if (tag === void 0) { tag = null; }
  26323. var label = document.createElement("label");
  26324. var boundingBoxesCheckbox = document.createElement("input");
  26325. boundingBoxesCheckbox.type = "checkbox";
  26326. boundingBoxesCheckbox.checked = initialState;
  26327. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26328. task(evt.target, tag);
  26329. });
  26330. label.appendChild(boundingBoxesCheckbox);
  26331. label.appendChild(document.createTextNode(title));
  26332. root.appendChild(label);
  26333. root.appendChild(document.createElement("br"));
  26334. };
  26335. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26336. if (tag === void 0) { tag = null; }
  26337. var label = document.createElement("label");
  26338. var boundingBoxesRadio = document.createElement("input");
  26339. boundingBoxesRadio.type = "radio";
  26340. boundingBoxesRadio.name = name;
  26341. boundingBoxesRadio.checked = initialState;
  26342. boundingBoxesRadio.addEventListener("change", function (evt) {
  26343. task(evt.target, tag);
  26344. });
  26345. label.appendChild(boundingBoxesRadio);
  26346. label.appendChild(document.createTextNode(title));
  26347. root.appendChild(label);
  26348. root.appendChild(document.createElement("br"));
  26349. };
  26350. DebugLayer.prototype._generateDOMelements = function () {
  26351. var _this = this;
  26352. this._globalDiv.id = "DebugLayer";
  26353. this._globalDiv.style.position = "absolute";
  26354. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26355. this._globalDiv.style.fontSize = "14px";
  26356. this._globalDiv.style.color = "white";
  26357. // Drawing canvas
  26358. this._drawingCanvas = document.createElement("canvas");
  26359. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26360. this._drawingCanvas.style.position = "absolute";
  26361. this._drawingCanvas.style.pointerEvents = "none";
  26362. this._drawingContext = this._drawingCanvas.getContext("2d");
  26363. this._globalDiv.appendChild(this._drawingCanvas);
  26364. if (this._showUI) {
  26365. var background = "rgba(128, 128, 128, 0.4)";
  26366. var border = "rgb(180, 180, 180) solid 1px";
  26367. // Stats
  26368. this._statsDiv = document.createElement("div");
  26369. this._statsDiv.id = "DebugLayerStats";
  26370. this._statsDiv.style.border = border;
  26371. this._statsDiv.style.position = "absolute";
  26372. this._statsDiv.style.background = background;
  26373. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26374. this._generateheader(this._statsDiv, "STATISTICS");
  26375. this._statsSubsetDiv = document.createElement("div");
  26376. this._statsSubsetDiv.style.paddingTop = "5px";
  26377. this._statsSubsetDiv.style.paddingBottom = "5px";
  26378. this._statsSubsetDiv.style.overflowY = "auto";
  26379. this._statsDiv.appendChild(this._statsSubsetDiv);
  26380. // Tree
  26381. this._treeDiv = document.createElement("div");
  26382. this._treeDiv.id = "DebugLayerTree";
  26383. this._treeDiv.style.border = border;
  26384. this._treeDiv.style.position = "absolute";
  26385. this._treeDiv.style.background = background;
  26386. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26387. this._treeDiv.style.display = "none";
  26388. this._generateheader(this._treeDiv, "MESHES TREE");
  26389. this._treeSubsetDiv = document.createElement("div");
  26390. this._treeSubsetDiv.style.paddingTop = "5px";
  26391. this._treeSubsetDiv.style.paddingRight = "5px";
  26392. this._treeSubsetDiv.style.overflowY = "auto";
  26393. this._treeSubsetDiv.style.maxHeight = "300px";
  26394. this._treeDiv.appendChild(this._treeSubsetDiv);
  26395. this._needToRefreshMeshesTree = true;
  26396. // Logs
  26397. this._logDiv = document.createElement("div");
  26398. this._logDiv.style.border = border;
  26399. this._logDiv.id = "DebugLayerLogs";
  26400. this._logDiv.style.position = "absolute";
  26401. this._logDiv.style.background = background;
  26402. this._logDiv.style.padding = "0px 0px 0px 5px";
  26403. this._logDiv.style.display = "none";
  26404. this._generateheader(this._logDiv, "LOGS");
  26405. this._logSubsetDiv = document.createElement("div");
  26406. this._logSubsetDiv.style.height = "127px";
  26407. this._logSubsetDiv.style.paddingTop = "5px";
  26408. this._logSubsetDiv.style.overflowY = "auto";
  26409. this._logSubsetDiv.style.fontSize = "12px";
  26410. this._logSubsetDiv.style.fontFamily = "consolas";
  26411. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26412. this._logDiv.appendChild(this._logSubsetDiv);
  26413. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26414. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26415. };
  26416. // Options
  26417. this._optionsDiv = document.createElement("div");
  26418. this._optionsDiv.id = "DebugLayerOptions";
  26419. this._optionsDiv.style.border = border;
  26420. this._optionsDiv.style.position = "absolute";
  26421. this._optionsDiv.style.background = background;
  26422. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26423. this._optionsDiv.style.overflowY = "auto";
  26424. this._generateheader(this._optionsDiv, "OPTIONS");
  26425. this._optionsSubsetDiv = document.createElement("div");
  26426. this._optionsSubsetDiv.style.paddingTop = "5px";
  26427. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26428. this._optionsSubsetDiv.style.overflowY = "auto";
  26429. this._optionsSubsetDiv.style.maxHeight = "200px";
  26430. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26431. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26432. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26433. _this._displayStatistics = element.checked;
  26434. });
  26435. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26436. _this._displayLogs = element.checked;
  26437. });
  26438. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26439. _this._displayTree = element.checked;
  26440. _this._needToRefreshMeshesTree = true;
  26441. });
  26442. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26443. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26444. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26445. _this._scene.forceShowBoundingBoxes = element.checked;
  26446. });
  26447. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26448. _this._labelsEnabled = element.checked;
  26449. if (!_this._labelsEnabled) {
  26450. _this._clearLabels();
  26451. }
  26452. });
  26453. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26454. if (element.checked) {
  26455. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26456. }
  26457. else {
  26458. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26459. }
  26460. });
  26461. ;
  26462. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26463. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26464. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26465. if (element.checked) {
  26466. _this._scene.forceWireframe = false;
  26467. _this._scene.forcePointsCloud = false;
  26468. }
  26469. });
  26470. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26471. if (element.checked) {
  26472. _this._scene.forceWireframe = true;
  26473. _this._scene.forcePointsCloud = false;
  26474. }
  26475. });
  26476. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26477. if (element.checked) {
  26478. _this._scene.forceWireframe = false;
  26479. _this._scene.forcePointsCloud = true;
  26480. }
  26481. });
  26482. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26483. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26484. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26485. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26486. });
  26487. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26488. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26489. });
  26490. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26491. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26492. });
  26493. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26494. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26495. });
  26496. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26497. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26498. });
  26499. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26500. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26501. });
  26502. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26503. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26504. });
  26505. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26506. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26507. });
  26508. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26509. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26510. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26511. _this._scene.animationsEnabled = element.checked;
  26512. });
  26513. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26514. _this._scene.collisionsEnabled = element.checked;
  26515. });
  26516. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26517. _this._scene.fogEnabled = element.checked;
  26518. });
  26519. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26520. _this._scene.lensFlaresEnabled = element.checked;
  26521. });
  26522. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26523. _this._scene.lightsEnabled = element.checked;
  26524. });
  26525. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26526. _this._scene.particlesEnabled = element.checked;
  26527. });
  26528. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26529. _this._scene.postProcessesEnabled = element.checked;
  26530. });
  26531. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26532. _this._scene.proceduralTexturesEnabled = element.checked;
  26533. });
  26534. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26535. _this._scene.renderTargetsEnabled = element.checked;
  26536. });
  26537. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26538. _this._scene.shadowsEnabled = element.checked;
  26539. });
  26540. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26541. _this._scene.skeletonsEnabled = element.checked;
  26542. });
  26543. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26544. _this._scene.texturesEnabled = element.checked;
  26545. });
  26546. this._globalDiv.appendChild(this._statsDiv);
  26547. this._globalDiv.appendChild(this._logDiv);
  26548. this._globalDiv.appendChild(this._optionsDiv);
  26549. this._globalDiv.appendChild(this._treeDiv);
  26550. }
  26551. };
  26552. DebugLayer.prototype._displayStats = function () {
  26553. var scene = this._scene;
  26554. var engine = scene.getEngine();
  26555. var glInfo = engine.getGlInfo();
  26556. 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>";
  26557. if (this.customStatsFunction) {
  26558. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26559. }
  26560. };
  26561. return DebugLayer;
  26562. })();
  26563. BABYLON.DebugLayer = DebugLayer;
  26564. })(BABYLON || (BABYLON = {}));
  26565. //# sourceMappingURL=babylon.debugLayer.js.map
  26566. var BABYLON;
  26567. (function (BABYLON) {
  26568. var RawTexture = (function (_super) {
  26569. __extends(RawTexture, _super);
  26570. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26572. if (invertY === void 0) { invertY = false; }
  26573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26574. _super.call(this, null, scene, !generateMipMaps, invertY);
  26575. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26576. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26577. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26578. }
  26579. // Statics
  26580. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26581. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26582. if (invertY === void 0) { invertY = false; }
  26583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26584. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26585. };
  26586. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26587. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26588. if (invertY === void 0) { invertY = false; }
  26589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26590. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26591. };
  26592. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26594. if (invertY === void 0) { invertY = false; }
  26595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26596. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26597. };
  26598. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26600. if (invertY === void 0) { invertY = false; }
  26601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26602. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26603. };
  26604. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26606. if (invertY === void 0) { invertY = false; }
  26607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26608. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26609. };
  26610. return RawTexture;
  26611. })(BABYLON.Texture);
  26612. BABYLON.RawTexture = RawTexture;
  26613. })(BABYLON || (BABYLON = {}));
  26614. //# sourceMappingURL=babylon.rawTexture.js.map
  26615. var BABYLON;
  26616. (function (BABYLON) {
  26617. var IndexedVector2 = (function (_super) {
  26618. __extends(IndexedVector2, _super);
  26619. function IndexedVector2(original, index) {
  26620. _super.call(this, original.x, original.y);
  26621. this.index = index;
  26622. }
  26623. return IndexedVector2;
  26624. })(BABYLON.Vector2);
  26625. var PolygonPoints = (function () {
  26626. function PolygonPoints() {
  26627. this.elements = new Array();
  26628. }
  26629. PolygonPoints.prototype.add = function (originalPoints) {
  26630. var _this = this;
  26631. var result = new Array();
  26632. originalPoints.forEach(function (point) {
  26633. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26634. var newPoint = new IndexedVector2(point, _this.elements.length);
  26635. result.push(newPoint);
  26636. _this.elements.push(newPoint);
  26637. }
  26638. });
  26639. return result;
  26640. };
  26641. PolygonPoints.prototype.computeBounds = function () {
  26642. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26643. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26644. this.elements.forEach(function (point) {
  26645. // x
  26646. if (point.x < lmin.x) {
  26647. lmin.x = point.x;
  26648. }
  26649. else if (point.x > lmax.x) {
  26650. lmax.x = point.x;
  26651. }
  26652. // y
  26653. if (point.y < lmin.y) {
  26654. lmin.y = point.y;
  26655. }
  26656. else if (point.y > lmax.y) {
  26657. lmax.y = point.y;
  26658. }
  26659. });
  26660. return {
  26661. min: lmin,
  26662. max: lmax,
  26663. width: lmax.x - lmin.x,
  26664. height: lmax.y - lmin.y
  26665. };
  26666. };
  26667. return PolygonPoints;
  26668. })();
  26669. var Polygon = (function () {
  26670. function Polygon() {
  26671. }
  26672. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26673. return [
  26674. new BABYLON.Vector2(xmin, ymin),
  26675. new BABYLON.Vector2(xmax, ymin),
  26676. new BABYLON.Vector2(xmax, ymax),
  26677. new BABYLON.Vector2(xmin, ymax)
  26678. ];
  26679. };
  26680. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26681. if (cx === void 0) { cx = 0; }
  26682. if (cy === void 0) { cy = 0; }
  26683. if (numberOfSides === void 0) { numberOfSides = 32; }
  26684. var result = new Array();
  26685. var angle = 0;
  26686. var increment = (Math.PI * 2) / numberOfSides;
  26687. for (var i = 0; i < numberOfSides; i++) {
  26688. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26689. angle -= increment;
  26690. }
  26691. return result;
  26692. };
  26693. Polygon.Parse = function (input) {
  26694. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26695. var i, result = [];
  26696. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26697. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26698. }
  26699. return result;
  26700. };
  26701. Polygon.StartingAt = function (x, y) {
  26702. return BABYLON.Path2.StartingAt(x, y);
  26703. };
  26704. return Polygon;
  26705. })();
  26706. BABYLON.Polygon = Polygon;
  26707. var PolygonMeshBuilder = (function () {
  26708. function PolygonMeshBuilder(name, contours, scene) {
  26709. this._points = new PolygonPoints();
  26710. if (!("poly2tri" in window)) {
  26711. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26712. }
  26713. this._name = name;
  26714. this._scene = scene;
  26715. var points;
  26716. if (contours instanceof BABYLON.Path2) {
  26717. points = contours.getPoints();
  26718. }
  26719. else {
  26720. points = contours;
  26721. }
  26722. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26723. }
  26724. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26725. this._swctx.addHole(this._points.add(hole));
  26726. return this;
  26727. };
  26728. PolygonMeshBuilder.prototype.build = function (updatable) {
  26729. if (updatable === void 0) { updatable = false; }
  26730. var result = new BABYLON.Mesh(this._name, this._scene);
  26731. var normals = [];
  26732. var positions = [];
  26733. var uvs = [];
  26734. var bounds = this._points.computeBounds();
  26735. this._points.elements.forEach(function (p) {
  26736. normals.push(0, 1.0, 0);
  26737. positions.push(p.x, 0, p.y);
  26738. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26739. });
  26740. var indices = [];
  26741. this._swctx.triangulate();
  26742. this._swctx.getTriangles().forEach(function (triangle) {
  26743. triangle.getPoints().forEach(function (point) {
  26744. indices.push(point.index);
  26745. });
  26746. });
  26747. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26748. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26749. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26750. result.setIndices(indices);
  26751. return result;
  26752. };
  26753. return PolygonMeshBuilder;
  26754. })();
  26755. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26756. })(BABYLON || (BABYLON = {}));
  26757. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26758. (function (BABYLON) {
  26759. var SimplificationSettings = (function () {
  26760. function SimplificationSettings(quality, distance) {
  26761. this.quality = quality;
  26762. this.distance = distance;
  26763. }
  26764. return SimplificationSettings;
  26765. })();
  26766. BABYLON.SimplificationSettings = SimplificationSettings;
  26767. /**
  26768. * The implemented types of simplification.
  26769. * At the moment only Quadratic Error Decimation is implemented.
  26770. */
  26771. (function (SimplificationType) {
  26772. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26773. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26774. var SimplificationType = BABYLON.SimplificationType;
  26775. var DecimationTriangle = (function () {
  26776. function DecimationTriangle(vertices) {
  26777. this.vertices = vertices;
  26778. this.error = new Array(4);
  26779. this.deleted = false;
  26780. this.isDirty = false;
  26781. this.borderFactor = 0;
  26782. }
  26783. return DecimationTriangle;
  26784. })();
  26785. BABYLON.DecimationTriangle = DecimationTriangle;
  26786. var DecimationVertex = (function () {
  26787. function DecimationVertex(position, normal, uv, id) {
  26788. this.position = position;
  26789. this.normal = normal;
  26790. this.uv = uv;
  26791. this.id = id;
  26792. this.isBorder = true;
  26793. this.q = new QuadraticMatrix();
  26794. this.triangleCount = 0;
  26795. this.triangleStart = 0;
  26796. }
  26797. return DecimationVertex;
  26798. })();
  26799. BABYLON.DecimationVertex = DecimationVertex;
  26800. var QuadraticMatrix = (function () {
  26801. function QuadraticMatrix(data) {
  26802. this.data = new Array(10);
  26803. for (var i = 0; i < 10; ++i) {
  26804. if (data && data[i]) {
  26805. this.data[i] = data[i];
  26806. }
  26807. else {
  26808. this.data[i] = 0;
  26809. }
  26810. }
  26811. }
  26812. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26813. 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];
  26814. return det;
  26815. };
  26816. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26817. for (var i = 0; i < 10; ++i) {
  26818. this.data[i] += matrix.data[i];
  26819. }
  26820. };
  26821. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26822. for (var i = 0; i < 10; ++i) {
  26823. this.data[i] += data[i];
  26824. }
  26825. };
  26826. QuadraticMatrix.prototype.add = function (matrix) {
  26827. var m = new QuadraticMatrix();
  26828. for (var i = 0; i < 10; ++i) {
  26829. m.data[i] = this.data[i] + matrix.data[i];
  26830. }
  26831. return m;
  26832. };
  26833. QuadraticMatrix.FromData = function (a, b, c, d) {
  26834. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26835. };
  26836. //returning an array to avoid garbage collection
  26837. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26838. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26839. };
  26840. return QuadraticMatrix;
  26841. })();
  26842. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26843. var Reference = (function () {
  26844. function Reference(vertexId, triangleId) {
  26845. this.vertexId = vertexId;
  26846. this.triangleId = triangleId;
  26847. }
  26848. return Reference;
  26849. })();
  26850. BABYLON.Reference = Reference;
  26851. /**
  26852. * An implementation of the Quadratic Error simplification algorithm.
  26853. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26854. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26855. * @author RaananW
  26856. */
  26857. var QuadraticErrorSimplification = (function () {
  26858. function QuadraticErrorSimplification(_mesh) {
  26859. this._mesh = _mesh;
  26860. this.initialised = false;
  26861. this.syncIterations = 5000;
  26862. this.aggressiveness = 7;
  26863. this.decimationIterations = 100;
  26864. }
  26865. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26866. var _this = this;
  26867. this.initWithMesh(this._mesh, function () {
  26868. _this.runDecimation(settings, successCallback);
  26869. });
  26870. };
  26871. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26872. var _this = this;
  26873. var targetCount = ~~(this.triangles.length * settings.quality);
  26874. var deletedTriangles = 0;
  26875. var triangleCount = this.triangles.length;
  26876. var iterationFunction = function (iteration, callback) {
  26877. setTimeout(function () {
  26878. if (iteration % 5 === 0) {
  26879. _this.updateMesh(iteration === 0);
  26880. }
  26881. for (var i = 0; i < _this.triangles.length; ++i) {
  26882. _this.triangles[i].isDirty = false;
  26883. }
  26884. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26885. var trianglesIterator = function (i) {
  26886. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26887. var t = _this.triangles[tIdx];
  26888. if (!t)
  26889. return;
  26890. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26891. return;
  26892. }
  26893. for (var j = 0; j < 3; ++j) {
  26894. if (t.error[j] < threshold) {
  26895. var deleted0 = [];
  26896. var deleted1 = [];
  26897. var i0 = t.vertices[j];
  26898. var i1 = t.vertices[(j + 1) % 3];
  26899. var v0 = _this.vertices[i0];
  26900. var v1 = _this.vertices[i1];
  26901. if (v0.isBorder !== v1.isBorder)
  26902. continue;
  26903. var p = BABYLON.Vector3.Zero();
  26904. var n = BABYLON.Vector3.Zero();
  26905. var uv = BABYLON.Vector2.Zero();
  26906. var color = new BABYLON.Color4(0, 0, 0, 1);
  26907. _this.calculateError(v0, v1, p, n, uv, color);
  26908. var delTr = [];
  26909. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26910. continue;
  26911. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26912. continue;
  26913. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26914. continue;
  26915. }
  26916. v0.normal = n;
  26917. if (v0.uv)
  26918. v0.uv = uv;
  26919. else if (v0.color)
  26920. v0.color = color;
  26921. v0.q = v1.q.add(v0.q);
  26922. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26923. continue;
  26924. if (p.equals(v0.position))
  26925. continue;
  26926. v0.position = p;
  26927. var tStart = _this.references.length;
  26928. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26929. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26930. var tCount = _this.references.length - tStart;
  26931. if (tCount <= v0.triangleCount) {
  26932. if (tCount) {
  26933. for (var c = 0; c < tCount; c++) {
  26934. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26935. }
  26936. }
  26937. }
  26938. else {
  26939. v0.triangleStart = tStart;
  26940. }
  26941. v0.triangleCount = tCount;
  26942. break;
  26943. }
  26944. }
  26945. };
  26946. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26947. return (triangleCount - deletedTriangles <= targetCount);
  26948. });
  26949. }, 0);
  26950. };
  26951. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26952. if (triangleCount - deletedTriangles <= targetCount)
  26953. loop.breakLoop();
  26954. else {
  26955. iterationFunction(loop.index, function () {
  26956. loop.executeNext();
  26957. });
  26958. }
  26959. }, function () {
  26960. setTimeout(function () {
  26961. successCallback(_this.reconstructMesh());
  26962. }, 0);
  26963. });
  26964. };
  26965. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26966. var _this = this;
  26967. if (!mesh)
  26968. return;
  26969. this.vertices = [];
  26970. this.triangles = [];
  26971. this._mesh = mesh;
  26972. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26973. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26974. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26975. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26976. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26977. var indices = mesh.getIndices();
  26978. var vertexInit = function (i) {
  26979. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26980. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26981. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26982. }
  26983. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26984. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26985. }
  26986. _this.vertices.push(vertex);
  26987. };
  26988. var totalVertices = mesh.getTotalVertices();
  26989. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26990. var indicesInit = function (i) {
  26991. var pos = i * 3;
  26992. var i0 = indices[pos + 0];
  26993. var i1 = indices[pos + 1];
  26994. var i2 = indices[pos + 2];
  26995. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26996. _this.triangles.push(triangle);
  26997. };
  26998. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26999. _this.init(callback);
  27000. });
  27001. });
  27002. };
  27003. QuadraticErrorSimplification.prototype.init = function (callback) {
  27004. var _this = this;
  27005. var triangleInit1 = function (i) {
  27006. var t = _this.triangles[i];
  27007. 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();
  27008. for (var j = 0; j < 3; j++) {
  27009. _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))));
  27010. }
  27011. };
  27012. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27013. var triangleInit2 = function (i) {
  27014. var t = _this.triangles[i];
  27015. for (var j = 0; j < 3; ++j) {
  27016. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27017. }
  27018. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27019. };
  27020. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27021. _this.initialised = true;
  27022. callback();
  27023. });
  27024. });
  27025. };
  27026. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27027. var newTriangles = [];
  27028. var i;
  27029. for (i = 0; i < this.vertices.length; ++i) {
  27030. this.vertices[i].triangleCount = 0;
  27031. }
  27032. var t;
  27033. var j;
  27034. for (i = 0; i < this.triangles.length; ++i) {
  27035. if (!this.triangles[i].deleted) {
  27036. t = this.triangles[i];
  27037. for (j = 0; j < 3; ++j) {
  27038. this.vertices[t.vertices[j]].triangleCount = 1;
  27039. }
  27040. newTriangles.push(t);
  27041. }
  27042. }
  27043. var newVerticesOrder = [];
  27044. //compact vertices, get the IDs of the vertices used.
  27045. var dst = 0;
  27046. for (i = 0; i < this.vertices.length; ++i) {
  27047. if (this.vertices[i].triangleCount) {
  27048. this.vertices[i].triangleStart = dst;
  27049. this.vertices[dst].position = this.vertices[i].position;
  27050. this.vertices[dst].normal = this.vertices[i].normal;
  27051. this.vertices[dst].uv = this.vertices[i].uv;
  27052. this.vertices[dst].color = this.vertices[i].color;
  27053. newVerticesOrder.push(i);
  27054. dst++;
  27055. }
  27056. }
  27057. for (i = 0; i < newTriangles.length; ++i) {
  27058. t = newTriangles[i];
  27059. for (j = 0; j < 3; ++j) {
  27060. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27061. }
  27062. }
  27063. this.vertices = this.vertices.slice(0, dst);
  27064. var newPositionData = [];
  27065. var newNormalData = [];
  27066. var newUVsData = [];
  27067. var newColorsData = [];
  27068. for (i = 0; i < newVerticesOrder.length; ++i) {
  27069. newPositionData.push(this.vertices[i].position.x);
  27070. newPositionData.push(this.vertices[i].position.y);
  27071. newPositionData.push(this.vertices[i].position.z);
  27072. newNormalData.push(this.vertices[i].normal.x);
  27073. newNormalData.push(this.vertices[i].normal.y);
  27074. newNormalData.push(this.vertices[i].normal.z);
  27075. if (this.vertices[i].uv) {
  27076. newUVsData.push(this.vertices[i].uv.x);
  27077. newUVsData.push(this.vertices[i].uv.y);
  27078. }
  27079. else if (this.vertices[i].color) {
  27080. newColorsData.push(this.vertices[i].color.r);
  27081. newColorsData.push(this.vertices[i].color.g);
  27082. newColorsData.push(this.vertices[i].color.b);
  27083. newColorsData.push(this.vertices[i].color.a);
  27084. }
  27085. }
  27086. var newIndicesArray = [];
  27087. for (i = 0; i < newTriangles.length; ++i) {
  27088. newIndicesArray.push(newTriangles[i].vertices[0]);
  27089. newIndicesArray.push(newTriangles[i].vertices[1]);
  27090. newIndicesArray.push(newTriangles[i].vertices[2]);
  27091. }
  27092. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27093. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27094. newMesh.material = this._mesh.material;
  27095. newMesh.parent = this._mesh.parent;
  27096. newMesh.setIndices(newIndicesArray);
  27097. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27098. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27099. if (newUVsData.length > 0)
  27100. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27101. if (newColorsData.length > 0)
  27102. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27103. //preparing the skeleton support
  27104. if (this._mesh.skeleton) {
  27105. }
  27106. return newMesh;
  27107. };
  27108. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27109. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27110. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27111. if (t.deleted)
  27112. continue;
  27113. var s = this.references[vertex1.triangleStart + i].vertexId;
  27114. var id1 = t.vertices[(s + 1) % 3];
  27115. var id2 = t.vertices[(s + 2) % 3];
  27116. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27117. deletedArray[i] = true;
  27118. delTr.push(t);
  27119. continue;
  27120. }
  27121. var d1 = this.vertices[id1].position.subtract(point);
  27122. d1 = d1.normalize();
  27123. var d2 = this.vertices[id2].position.subtract(point);
  27124. d2 = d2.normalize();
  27125. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27126. return true;
  27127. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27128. deletedArray[i] = false;
  27129. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27130. return true;
  27131. }
  27132. return false;
  27133. };
  27134. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27135. var newDeleted = deletedTriangles;
  27136. for (var i = 0; i < vertex.triangleCount; ++i) {
  27137. var ref = this.references[vertex.triangleStart + i];
  27138. var t = this.triangles[ref.triangleId];
  27139. if (t.deleted)
  27140. continue;
  27141. if (deletedArray[i]) {
  27142. t.deleted = true;
  27143. newDeleted++;
  27144. continue;
  27145. }
  27146. t.vertices[ref.vertexId] = vertexId;
  27147. t.isDirty = true;
  27148. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27149. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27150. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27151. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27152. this.references.push(ref);
  27153. }
  27154. return newDeleted;
  27155. };
  27156. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27157. for (var i = 0; i < this.vertices.length; ++i) {
  27158. var vCount = [];
  27159. var vId = [];
  27160. var v = this.vertices[i];
  27161. var j;
  27162. for (j = 0; j < v.triangleCount; ++j) {
  27163. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27164. for (var ii = 0; ii < 3; ii++) {
  27165. var ofs = 0;
  27166. var id = triangle.vertices[ii];
  27167. while (ofs < vCount.length) {
  27168. if (vId[ofs] === id)
  27169. break;
  27170. ++ofs;
  27171. }
  27172. if (ofs === vCount.length) {
  27173. vCount.push(1);
  27174. vId.push(id);
  27175. }
  27176. else {
  27177. vCount[ofs]++;
  27178. }
  27179. }
  27180. }
  27181. for (j = 0; j < vCount.length; ++j) {
  27182. if (vCount[j] === 1) {
  27183. this.vertices[vId[j]].isBorder = true;
  27184. }
  27185. else {
  27186. this.vertices[vId[j]].isBorder = false;
  27187. }
  27188. }
  27189. }
  27190. };
  27191. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27192. if (identifyBorders === void 0) { identifyBorders = false; }
  27193. var i;
  27194. if (!identifyBorders) {
  27195. var newTrianglesVector = [];
  27196. for (i = 0; i < this.triangles.length; ++i) {
  27197. if (!this.triangles[i].deleted) {
  27198. newTrianglesVector.push(this.triangles[i]);
  27199. }
  27200. }
  27201. this.triangles = newTrianglesVector;
  27202. }
  27203. for (i = 0; i < this.vertices.length; ++i) {
  27204. this.vertices[i].triangleCount = 0;
  27205. this.vertices[i].triangleStart = 0;
  27206. }
  27207. var t;
  27208. var j;
  27209. var v;
  27210. for (i = 0; i < this.triangles.length; ++i) {
  27211. t = this.triangles[i];
  27212. for (j = 0; j < 3; ++j) {
  27213. v = this.vertices[t.vertices[j]];
  27214. v.triangleCount++;
  27215. }
  27216. }
  27217. var tStart = 0;
  27218. for (i = 0; i < this.vertices.length; ++i) {
  27219. this.vertices[i].triangleStart = tStart;
  27220. tStart += this.vertices[i].triangleCount;
  27221. this.vertices[i].triangleCount = 0;
  27222. }
  27223. var newReferences = new Array(this.triangles.length * 3);
  27224. for (i = 0; i < this.triangles.length; ++i) {
  27225. t = this.triangles[i];
  27226. for (j = 0; j < 3; ++j) {
  27227. v = this.vertices[t.vertices[j]];
  27228. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27229. v.triangleCount++;
  27230. }
  27231. }
  27232. this.references = newReferences;
  27233. if (identifyBorders) {
  27234. this.identifyBorder();
  27235. }
  27236. };
  27237. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27238. var x = point.x;
  27239. var y = point.y;
  27240. var z = point.z;
  27241. 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];
  27242. };
  27243. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27244. var q = vertex1.q.add(vertex2.q);
  27245. var border = vertex1.isBorder && vertex2.isBorder;
  27246. var error = 0;
  27247. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27248. if (qDet !== 0 && !border) {
  27249. if (!pointResult) {
  27250. pointResult = BABYLON.Vector3.Zero();
  27251. }
  27252. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27253. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27254. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27255. error = this.vertexError(q, pointResult);
  27256. //TODO this should be correctly calculated
  27257. if (normalResult) {
  27258. normalResult.copyFrom(vertex1.normal);
  27259. if (vertex1.uv)
  27260. uvResult.copyFrom(vertex1.uv);
  27261. else if (vertex1.color)
  27262. colorResult.copyFrom(vertex1.color);
  27263. }
  27264. }
  27265. else {
  27266. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27267. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27268. var error1 = this.vertexError(q, vertex1.position);
  27269. var error2 = this.vertexError(q, vertex2.position);
  27270. var error3 = this.vertexError(q, p3);
  27271. error = Math.min(error1, error2, error3);
  27272. if (error === error1) {
  27273. if (pointResult) {
  27274. pointResult.copyFrom(vertex1.position);
  27275. normalResult.copyFrom(vertex1.normal);
  27276. if (vertex1.uv)
  27277. uvResult.copyFrom(vertex1.uv);
  27278. else if (vertex1.color)
  27279. colorResult.copyFrom(vertex1.color);
  27280. }
  27281. }
  27282. else if (error === error2) {
  27283. if (pointResult) {
  27284. pointResult.copyFrom(vertex2.position);
  27285. normalResult.copyFrom(vertex2.normal);
  27286. if (vertex2.uv)
  27287. uvResult.copyFrom(vertex2.uv);
  27288. else if (vertex2.color)
  27289. colorResult.copyFrom(vertex2.color);
  27290. }
  27291. }
  27292. else {
  27293. if (pointResult) {
  27294. pointResult.copyFrom(p3);
  27295. normalResult.copyFrom(vertex1.normal);
  27296. if (vertex1.uv)
  27297. uvResult.copyFrom(vertex1.uv);
  27298. else if (vertex1.color)
  27299. colorResult.copyFrom(vertex1.color);
  27300. }
  27301. }
  27302. }
  27303. return error;
  27304. };
  27305. return QuadraticErrorSimplification;
  27306. })();
  27307. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27308. })(BABYLON || (BABYLON = {}));
  27309. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27310. (function (BABYLON) {
  27311. var Analyser = (function () {
  27312. function Analyser(scene) {
  27313. this.SMOOTHING = 0.75;
  27314. this.FFT_SIZE = 512;
  27315. this.BARGRAPHAMPLITUDE = 256;
  27316. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27317. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27318. this._scene = scene;
  27319. this._audioEngine = BABYLON.Engine.audioEngine;
  27320. if (this._audioEngine.canUseWebAudio) {
  27321. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27322. this._webAudioAnalyser.minDecibels = -140;
  27323. this._webAudioAnalyser.maxDecibels = 0;
  27324. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27325. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27326. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27327. }
  27328. }
  27329. Analyser.prototype.getFrequencyBinCount = function () {
  27330. if (this._audioEngine.canUseWebAudio) {
  27331. return this._webAudioAnalyser.frequencyBinCount;
  27332. }
  27333. else {
  27334. return 0;
  27335. }
  27336. };
  27337. Analyser.prototype.getByteFrequencyData = function () {
  27338. if (this._audioEngine.canUseWebAudio) {
  27339. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27340. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27341. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27342. }
  27343. return this._byteFreqs;
  27344. };
  27345. Analyser.prototype.getByteTimeDomainData = function () {
  27346. if (this._audioEngine.canUseWebAudio) {
  27347. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27348. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27349. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27350. }
  27351. return this._byteTime;
  27352. };
  27353. Analyser.prototype.getFloatFrequencyData = function () {
  27354. if (this._audioEngine.canUseWebAudio) {
  27355. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27356. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27357. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27358. }
  27359. return this._floatFreqs;
  27360. };
  27361. Analyser.prototype.drawDebugCanvas = function () {
  27362. var _this = this;
  27363. if (this._audioEngine.canUseWebAudio) {
  27364. if (!this._debugCanvas) {
  27365. this._debugCanvas = document.createElement("canvas");
  27366. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27367. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27368. this._debugCanvas.style.position = "absolute";
  27369. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27370. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27371. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27372. document.body.appendChild(this._debugCanvas);
  27373. this._registerFunc = function () {
  27374. _this.drawDebugCanvas();
  27375. };
  27376. this._scene.registerBeforeRender(this._registerFunc);
  27377. }
  27378. if (this._registerFunc) {
  27379. var workingArray = this.getByteFrequencyData();
  27380. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27381. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27382. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27383. var value = workingArray[i];
  27384. var percent = value / this.BARGRAPHAMPLITUDE;
  27385. var height = this.DEBUGCANVASSIZE.height * percent;
  27386. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27387. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27388. var hue = i / this.getFrequencyBinCount() * 360;
  27389. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27390. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27391. }
  27392. }
  27393. }
  27394. };
  27395. Analyser.prototype.stopDebugCanvas = function () {
  27396. if (this._debugCanvas) {
  27397. this._scene.unregisterBeforeRender(this._registerFunc);
  27398. this._registerFunc = null;
  27399. document.body.removeChild(this._debugCanvas);
  27400. this._debugCanvas = null;
  27401. this._debugCanvasContext = null;
  27402. }
  27403. };
  27404. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27405. if (this._audioEngine.canUseWebAudio) {
  27406. inputAudioNode.connect(this._webAudioAnalyser);
  27407. this._webAudioAnalyser.connect(outputAudioNode);
  27408. }
  27409. };
  27410. Analyser.prototype.dispose = function () {
  27411. if (this._audioEngine.canUseWebAudio) {
  27412. this._webAudioAnalyser.disconnect();
  27413. }
  27414. };
  27415. return Analyser;
  27416. })();
  27417. BABYLON.Analyser = Analyser;
  27418. })(BABYLON || (BABYLON = {}));
  27419. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27420. (function (BABYLON) {
  27421. var DepthRenderer = (function () {
  27422. function DepthRenderer(scene, type) {
  27423. var _this = this;
  27424. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27425. this._viewMatrix = BABYLON.Matrix.Zero();
  27426. this._projectionMatrix = BABYLON.Matrix.Zero();
  27427. this._transformMatrix = BABYLON.Matrix.Zero();
  27428. this._worldViewProjection = BABYLON.Matrix.Zero();
  27429. this._scene = scene;
  27430. var engine = scene.getEngine();
  27431. // Render target
  27432. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27433. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27434. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27435. this._depthMap.refreshRate = 1;
  27436. this._depthMap.renderParticles = false;
  27437. this._depthMap.renderList = null;
  27438. // Custom render function
  27439. var renderSubMesh = function (subMesh) {
  27440. var mesh = subMesh.getRenderingMesh();
  27441. var scene = _this._scene;
  27442. var engine = scene.getEngine();
  27443. // Culling
  27444. engine.setState(subMesh.getMaterial().backFaceCulling);
  27445. // Managing instances
  27446. var batch = mesh._getInstancesRenderList(subMesh._id);
  27447. if (batch.mustReturn) {
  27448. return;
  27449. }
  27450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27451. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27452. engine.enableEffect(_this._effect);
  27453. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27454. var material = subMesh.getMaterial();
  27455. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27456. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27457. // Alpha test
  27458. if (material && material.needAlphaTesting()) {
  27459. var alphaTexture = material.getAlphaTestTexture();
  27460. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27461. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27462. }
  27463. // Bones
  27464. if (mesh.useBones) {
  27465. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27466. }
  27467. // Draw
  27468. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27469. }
  27470. };
  27471. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27472. var index;
  27473. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27474. renderSubMesh(opaqueSubMeshes.data[index]);
  27475. }
  27476. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27477. renderSubMesh(alphaTestSubMeshes.data[index]);
  27478. }
  27479. };
  27480. }
  27481. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27482. var defines = [];
  27483. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27484. var mesh = subMesh.getMesh();
  27485. var scene = mesh.getScene();
  27486. var material = subMesh.getMaterial();
  27487. // Alpha test
  27488. if (material && material.needAlphaTesting()) {
  27489. defines.push("#define ALPHATEST");
  27490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27491. attribs.push(BABYLON.VertexBuffer.UVKind);
  27492. defines.push("#define UV1");
  27493. }
  27494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27496. defines.push("#define UV2");
  27497. }
  27498. }
  27499. // Bones
  27500. if (mesh.useBones) {
  27501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27503. defines.push("#define BONES");
  27504. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27505. }
  27506. // Instances
  27507. if (useInstances) {
  27508. defines.push("#define INSTANCES");
  27509. attribs.push("world0");
  27510. attribs.push("world1");
  27511. attribs.push("world2");
  27512. attribs.push("world3");
  27513. }
  27514. // Get correct effect
  27515. var join = defines.join("\n");
  27516. if (this._cachedDefines !== join) {
  27517. this._cachedDefines = join;
  27518. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27519. }
  27520. return this._effect.isReady();
  27521. };
  27522. DepthRenderer.prototype.getDepthMap = function () {
  27523. return this._depthMap;
  27524. };
  27525. // Methods
  27526. DepthRenderer.prototype.dispose = function () {
  27527. this._depthMap.dispose();
  27528. };
  27529. return DepthRenderer;
  27530. })();
  27531. BABYLON.DepthRenderer = DepthRenderer;
  27532. })(BABYLON || (BABYLON = {}));
  27533. //# sourceMappingURL=babylon.depthRenderer.js.map
  27534. var BABYLON;
  27535. (function (BABYLON) {
  27536. var SSAORenderingPipeline = (function (_super) {
  27537. __extends(SSAORenderingPipeline, _super);
  27538. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27539. var _this = this;
  27540. if (ratio === void 0) { ratio = 1.0; }
  27541. _super.call(this, scene.getEngine(), name);
  27542. // Members
  27543. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27544. this.SSAORenderEffect = "SSAORenderEffect";
  27545. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27546. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27547. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27548. this._firstUpdate = true;
  27549. this._scene = scene;
  27550. // Set up assets
  27551. this._createRandomTexture();
  27552. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27553. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27554. this._createSSAOPostProcess(ratio);
  27555. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27556. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27557. this._createSSAOCombinePostProcess();
  27558. // Set up pipeline
  27559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27560. return _this._originalColorPostProcess;
  27561. }, true));
  27562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27563. return _this._ssaoPostProcess;
  27564. }, true));
  27565. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27566. return _this._blurHPostProcess;
  27567. }, true));
  27568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27569. return _this._blurVPostProcess;
  27570. }, true));
  27571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27572. return _this._ssaoCombinePostProcess;
  27573. }, true));
  27574. // Finish
  27575. scene.postProcessRenderPipelineManager.addPipeline(this);
  27576. if (cameras)
  27577. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27578. }
  27579. // Public Methods
  27580. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27581. return this._blurHPostProcess;
  27582. };
  27583. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27584. return this._blurVPostProcess;
  27585. };
  27586. SSAORenderingPipeline.prototype.dispose = function () {
  27587. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  27588. this._originalColorPostProcess = undefined;
  27589. this._ssaoPostProcess = undefined;
  27590. this._blurHPostProcess = undefined;
  27591. this._blurVPostProcess = undefined;
  27592. this._ssaoCombinePostProcess = undefined;
  27593. this._randomTexture.dispose();
  27594. };
  27595. // Private Methods
  27596. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27597. var _this = this;
  27598. var sampleSphere = [
  27599. 0.5381,
  27600. 0.1856,
  27601. -0.4319,
  27602. 0.1379,
  27603. 0.2486,
  27604. 0.4430,
  27605. 0.3371,
  27606. 0.5679,
  27607. -0.0057,
  27608. -0.6999,
  27609. -0.0451,
  27610. -0.0019,
  27611. 0.0689,
  27612. -0.1598,
  27613. -0.8547,
  27614. 0.0560,
  27615. 0.0069,
  27616. -0.1843,
  27617. -0.0146,
  27618. 0.1402,
  27619. 0.0762,
  27620. 0.0100,
  27621. -0.1924,
  27622. -0.0344,
  27623. -0.3577,
  27624. -0.5301,
  27625. -0.4358,
  27626. -0.3169,
  27627. 0.1063,
  27628. 0.0158,
  27629. 0.0103,
  27630. -0.5869,
  27631. 0.0046,
  27632. -0.0897,
  27633. -0.4940,
  27634. 0.3287,
  27635. 0.7119,
  27636. -0.0154,
  27637. -0.0918,
  27638. -0.0533,
  27639. 0.0596,
  27640. -0.5411,
  27641. 0.0352,
  27642. -0.0631,
  27643. 0.5460,
  27644. -0.4776,
  27645. 0.2847,
  27646. -0.0271
  27647. ];
  27648. var samplesFactor = 1.0 / 16.0;
  27649. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27650. this._ssaoPostProcess.onApply = function (effect) {
  27651. if (_this._firstUpdate) {
  27652. effect.setArray3("sampleSphere", sampleSphere);
  27653. effect.setFloat("samplesFactor", samplesFactor);
  27654. effect.setFloat("randTextureTiles", 4.0 / ratio);
  27655. _this._firstUpdate = false;
  27656. }
  27657. effect.setTexture("textureSampler", _this._depthTexture);
  27658. effect.setTexture("randomSampler", _this._randomTexture);
  27659. };
  27660. };
  27661. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27662. var _this = this;
  27663. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27664. this._ssaoCombinePostProcess.onApply = function (effect) {
  27665. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27666. };
  27667. };
  27668. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27669. var size = 512;
  27670. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27671. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27672. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27673. var context = this._randomTexture.getContext();
  27674. var rand = function (min, max) {
  27675. return Math.random() * (max - min) + min;
  27676. };
  27677. for (var x = 0; x < size; x++) {
  27678. for (var y = 0; y < size; y++) {
  27679. var randVector = BABYLON.Vector3.Zero();
  27680. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27681. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27682. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27683. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27684. context.fillRect(x, y, 1, 1);
  27685. }
  27686. }
  27687. this._randomTexture.update(false);
  27688. };
  27689. return SSAORenderingPipeline;
  27690. })(BABYLON.PostProcessRenderPipeline);
  27691. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27692. })(BABYLON || (BABYLON = {}));
  27693. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27694. var BABYLON;
  27695. (function (BABYLON) {
  27696. var GodRaysPostProcess = (function (_super) {
  27697. __extends(GodRaysPostProcess, _super);
  27698. function GodRaysPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27699. var _this = this;
  27700. _super.call(this, name, "volumetricLightScattering", ["lightPositionOnScreen"], ["lightScatteringSampler"], ratio, camera, samplingMode, engine, reusable);
  27701. this._screenCoordinates = BABYLON.Vector2.Zero();
  27702. this.invert = true;
  27703. var scene = camera.getScene();
  27704. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27705. // Create billboard
  27706. this.mesh = BABYLON.Mesh.CreatePlane("VolumetricLightScatteringMesh", 2, scene);
  27707. this.mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  27708. this.mesh.material = new BABYLON.StandardMaterial('VolumetricLightScatteringMaterial', scene);
  27709. // Configure
  27710. this._createPass(scene);
  27711. this.onApply = function (effect) {
  27712. _this._updateScreenCoordinates(scene);
  27713. effect.setTexture("lightScatteringSampler", _this._godRaysRTT);
  27714. effect.setVector2("lightPositionOnScreen", _this._screenCoordinates);
  27715. };
  27716. }
  27717. GodRaysPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27718. var mesh = subMesh.getMesh();
  27719. var scene = mesh.getScene();
  27720. var defines = [];
  27721. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27722. var material = subMesh.getMaterial();
  27723. // Render this.mesh as default
  27724. if (mesh === this.mesh)
  27725. defines.push("#define BASIC_RENDER");
  27726. // Alpha test
  27727. if (material) {
  27728. if (material.needAlphaTesting() || mesh === this.mesh)
  27729. defines.push("#define ALPHATEST");
  27730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27731. attribs.push(BABYLON.VertexBuffer.UVKind);
  27732. defines.push("#define UV1");
  27733. }
  27734. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27735. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27736. defines.push("#define UV2");
  27737. }
  27738. }
  27739. // Bones
  27740. if (mesh.useBones) {
  27741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27743. defines.push("#define BONES");
  27744. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27745. }
  27746. // Instances
  27747. if (useInstances) {
  27748. defines.push("#define INSTANCES");
  27749. attribs.push("world0");
  27750. attribs.push("world1");
  27751. attribs.push("world2");
  27752. attribs.push("world3");
  27753. }
  27754. // Get correct effect
  27755. var join = defines.join("\n");
  27756. if (this._cachedDefines !== join) {
  27757. this._cachedDefines = join;
  27758. this._godRaysPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27759. }
  27760. return this._godRaysPass.isReady();
  27761. };
  27762. GodRaysPostProcess.prototype.dispose = function (camera) {
  27763. this._godRaysRTT.dispose();
  27764. _super.prototype.dispose.call(this, camera);
  27765. };
  27766. GodRaysPostProcess.prototype.getPass = function () {
  27767. return this._godRaysRTT;
  27768. };
  27769. // Private methods
  27770. GodRaysPostProcess.prototype._createPass = function (scene) {
  27771. var _this = this;
  27772. var engine = scene.getEngine();
  27773. this._godRaysRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  27774. this._godRaysRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27775. this._godRaysRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27776. this._godRaysRTT.renderList = null;
  27777. this._godRaysRTT.renderParticles = false;
  27778. scene.customRenderTargets.push(this._godRaysRTT);
  27779. // Custom render function for submeshes
  27780. var renderSubMesh = function (subMesh) {
  27781. var mesh = subMesh.getRenderingMesh();
  27782. var scene = mesh.getScene();
  27783. var engine = scene.getEngine();
  27784. // Culling
  27785. engine.setState(subMesh.getMaterial().backFaceCulling);
  27786. // Managing instances
  27787. var batch = mesh._getInstancesRenderList(subMesh._id);
  27788. if (batch.mustReturn) {
  27789. return;
  27790. }
  27791. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27792. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27793. engine.enableEffect(_this._godRaysPass);
  27794. mesh._bind(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode);
  27795. var material = subMesh.getMaterial();
  27796. _this._godRaysPass.setMatrix("viewProjection", scene.getTransformMatrix());
  27797. // Alpha test
  27798. if (material && (mesh === _this.mesh || material.needAlphaTesting())) {
  27799. var alphaTexture = material.getAlphaTestTexture();
  27800. _this._godRaysPass.setTexture("diffuseSampler", alphaTexture);
  27801. _this._godRaysPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27802. }
  27803. // Bones
  27804. if (mesh.useBones) {
  27805. _this._godRaysPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27806. }
  27807. // Draw
  27808. mesh._processRendering(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._godRaysPass.setMatrix("world", world); });
  27809. }
  27810. };
  27811. // Render target texture callbacks
  27812. var savedSceneClearColor;
  27813. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27814. this._godRaysRTT.onBeforeRender = function () {
  27815. savedSceneClearColor = scene.clearColor;
  27816. scene.clearColor = sceneClearColor;
  27817. };
  27818. this._godRaysRTT.onAfterRender = function () {
  27819. scene.clearColor = savedSceneClearColor;
  27820. };
  27821. this._godRaysRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27822. var index;
  27823. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27824. renderSubMesh(opaqueSubMeshes.data[index]);
  27825. }
  27826. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27827. renderSubMesh(alphaTestSubMeshes.data[index]);
  27828. }
  27829. };
  27830. };
  27831. GodRaysPostProcess.prototype._updateScreenCoordinates = function (scene) {
  27832. var transform = scene.getTransformMatrix();
  27833. var pos = BABYLON.Vector3.Project(this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  27834. this._screenCoordinates.x = pos.x / this._viewPort.width;
  27835. this._screenCoordinates.y = pos.y / this._viewPort.height;
  27836. if (this.invert)
  27837. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  27838. };
  27839. return GodRaysPostProcess;
  27840. })(BABYLON.PostProcess);
  27841. BABYLON.GodRaysPostProcess = GodRaysPostProcess;
  27842. })(BABYLON || (BABYLON = {}));
  27843. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map