babylon.2.1-beta.debug.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (r === void 0) { r = 0; }
  6. if (g === void 0) { g = 0; }
  7. if (b === void 0) { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. // Operators
  16. Color3.prototype.toArray = function (array, index) {
  17. if (index === undefined) {
  18. index = 0;
  19. }
  20. array[index] = this.r;
  21. array[index + 1] = this.g;
  22. array[index + 2] = this.b;
  23. return this;
  24. };
  25. Color3.prototype.toColor4 = function (alpha) {
  26. if (alpha === void 0) { alpha = 1; }
  27. return new Color4(this.r, this.g, this.b, alpha);
  28. };
  29. Color3.prototype.asArray = function () {
  30. var result = [];
  31. this.toArray(result, 0);
  32. return result;
  33. };
  34. Color3.prototype.toLuminance = function () {
  35. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  36. };
  37. Color3.prototype.multiply = function (otherColor) {
  38. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  39. };
  40. Color3.prototype.multiplyToRef = function (otherColor, result) {
  41. result.r = this.r * otherColor.r;
  42. result.g = this.g * otherColor.g;
  43. result.b = this.b * otherColor.b;
  44. return this;
  45. };
  46. Color3.prototype.equals = function (otherColor) {
  47. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  48. };
  49. Color3.prototype.scale = function (scale) {
  50. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  51. };
  52. Color3.prototype.scaleToRef = function (scale, result) {
  53. result.r = this.r * scale;
  54. result.g = this.g * scale;
  55. result.b = this.b * scale;
  56. return this;
  57. };
  58. Color3.prototype.add = function (otherColor) {
  59. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  60. };
  61. Color3.prototype.addToRef = function (otherColor, result) {
  62. result.r = this.r + otherColor.r;
  63. result.g = this.g + otherColor.g;
  64. result.b = this.b + otherColor.b;
  65. return this;
  66. };
  67. Color3.prototype.subtract = function (otherColor) {
  68. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  69. };
  70. Color3.prototype.subtractToRef = function (otherColor, result) {
  71. result.r = this.r - otherColor.r;
  72. result.g = this.g - otherColor.g;
  73. result.b = this.b - otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. return this;
  84. };
  85. Color3.prototype.copyFromFloats = function (r, g, b) {
  86. this.r = r;
  87. this.g = g;
  88. this.b = b;
  89. return this;
  90. };
  91. // Statics
  92. Color3.FromArray = function (array, offset) {
  93. if (offset === void 0) { offset = 0; }
  94. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  95. };
  96. Color3.FromInts = function (r, g, b) {
  97. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  98. };
  99. Color3.Lerp = function (start, end, amount) {
  100. var r = start.r + ((end.r - start.r) * amount);
  101. var g = start.g + ((end.g - start.g) * amount);
  102. var b = start.b + ((end.b - start.b) * amount);
  103. return new Color3(r, g, b);
  104. };
  105. Color3.Red = function () {
  106. return new Color3(1, 0, 0);
  107. };
  108. Color3.Green = function () {
  109. return new Color3(0, 1, 0);
  110. };
  111. Color3.Blue = function () {
  112. return new Color3(0, 0, 1);
  113. };
  114. Color3.Black = function () {
  115. return new Color3(0, 0, 0);
  116. };
  117. Color3.White = function () {
  118. return new Color3(1, 1, 1);
  119. };
  120. Color3.Purple = function () {
  121. return new Color3(0.5, 0, 0.5);
  122. };
  123. Color3.Magenta = function () {
  124. return new Color3(1, 0, 1);
  125. };
  126. Color3.Yellow = function () {
  127. return new Color3(1, 1, 0);
  128. };
  129. Color3.Gray = function () {
  130. return new Color3(0.5, 0.5, 0.5);
  131. };
  132. return Color3;
  133. })();
  134. BABYLON.Color3 = Color3;
  135. var Color4 = (function () {
  136. function Color4(r, g, b, a) {
  137. this.r = r;
  138. this.g = g;
  139. this.b = b;
  140. this.a = a;
  141. }
  142. // Operators
  143. Color4.prototype.addInPlace = function (right) {
  144. this.r += right.r;
  145. this.g += right.g;
  146. this.b += right.b;
  147. this.a += right.a;
  148. return this;
  149. };
  150. Color4.prototype.asArray = function () {
  151. var result = [];
  152. this.toArray(result, 0);
  153. return result;
  154. };
  155. Color4.prototype.toArray = function (array, index) {
  156. if (index === undefined) {
  157. index = 0;
  158. }
  159. array[index] = this.r;
  160. array[index + 1] = this.g;
  161. array[index + 2] = this.b;
  162. array[index + 3] = this.a;
  163. return this;
  164. };
  165. Color4.prototype.add = function (right) {
  166. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  167. };
  168. Color4.prototype.subtract = function (right) {
  169. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  170. };
  171. Color4.prototype.subtractToRef = function (right, result) {
  172. result.r = this.r - right.r;
  173. result.g = this.g - right.g;
  174. result.b = this.b - right.b;
  175. result.a = this.a - right.a;
  176. return this;
  177. };
  178. Color4.prototype.scale = function (scale) {
  179. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  180. };
  181. Color4.prototype.scaleToRef = function (scale, result) {
  182. result.r = this.r * scale;
  183. result.g = this.g * scale;
  184. result.b = this.b * scale;
  185. result.a = this.a * scale;
  186. return this;
  187. };
  188. Color4.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  190. };
  191. Color4.prototype.clone = function () {
  192. return new Color4(this.r, this.g, this.b, this.a);
  193. };
  194. Color4.prototype.copyFrom = function (source) {
  195. this.r = source.r;
  196. this.g = source.g;
  197. this.b = source.b;
  198. this.a = source.a;
  199. return this;
  200. };
  201. // Statics
  202. Color4.Lerp = function (left, right, amount) {
  203. var result = new Color4(0, 0, 0, 0);
  204. Color4.LerpToRef(left, right, amount, result);
  205. return result;
  206. };
  207. Color4.LerpToRef = function (left, right, amount, result) {
  208. result.r = left.r + (right.r - left.r) * amount;
  209. result.g = left.g + (right.g - left.g) * amount;
  210. result.b = left.b + (right.b - left.b) * amount;
  211. result.a = left.a + (right.a - left.a) * amount;
  212. };
  213. Color4.FromArray = function (array, offset) {
  214. if (offset === void 0) { offset = 0; }
  215. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  216. };
  217. Color4.FromInts = function (r, g, b, a) {
  218. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  219. };
  220. return Color4;
  221. })();
  222. BABYLON.Color4 = Color4;
  223. var Vector2 = (function () {
  224. function Vector2(x, y) {
  225. this.x = x;
  226. this.y = y;
  227. }
  228. Vector2.prototype.toString = function () {
  229. return "{X: " + this.x + " Y:" + this.y + "}";
  230. };
  231. // Operators
  232. Vector2.prototype.toArray = function (array, index) {
  233. if (index === void 0) { index = 0; }
  234. array[index] = this.x;
  235. array[index + 1] = this.y;
  236. return this;
  237. };
  238. Vector2.prototype.asArray = function () {
  239. var result = [];
  240. this.toArray(result, 0);
  241. return result;
  242. };
  243. Vector2.prototype.copyFrom = function (source) {
  244. this.x = source.x;
  245. this.y = source.y;
  246. return this;
  247. };
  248. Vector2.prototype.copyFromFloats = function (x, y) {
  249. this.x = x;
  250. this.y = y;
  251. return this;
  252. };
  253. Vector2.prototype.add = function (otherVector) {
  254. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  255. };
  256. Vector2.prototype.addVector3 = function (otherVector) {
  257. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  258. };
  259. Vector2.prototype.subtract = function (otherVector) {
  260. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  261. };
  262. Vector2.prototype.subtractInPlace = function (otherVector) {
  263. this.x -= otherVector.x;
  264. this.y -= otherVector.y;
  265. return this;
  266. };
  267. Vector2.prototype.multiplyInPlace = function (otherVector) {
  268. this.x *= otherVector.x;
  269. this.y *= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiply = function (otherVector) {
  273. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  274. };
  275. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  276. result.x = this.x * otherVector.x;
  277. result.y = this.y * otherVector.y;
  278. return this;
  279. };
  280. Vector2.prototype.multiplyByFloats = function (x, y) {
  281. return new Vector2(this.x * x, this.y * y);
  282. };
  283. Vector2.prototype.divide = function (otherVector) {
  284. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  285. };
  286. Vector2.prototype.divideToRef = function (otherVector, result) {
  287. result.x = this.x / otherVector.x;
  288. result.y = this.y / otherVector.y;
  289. return this;
  290. };
  291. Vector2.prototype.negate = function () {
  292. return new Vector2(-this.x, -this.y);
  293. };
  294. Vector2.prototype.scaleInPlace = function (scale) {
  295. this.x *= scale;
  296. this.y *= scale;
  297. return this;
  298. };
  299. Vector2.prototype.scale = function (scale) {
  300. return new Vector2(this.x * scale, this.y * scale);
  301. };
  302. Vector2.prototype.equals = function (otherVector) {
  303. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  304. };
  305. // Properties
  306. Vector2.prototype.length = function () {
  307. return Math.sqrt(this.x * this.x + this.y * this.y);
  308. };
  309. Vector2.prototype.lengthSquared = function () {
  310. return (this.x * this.x + this.y * this.y);
  311. };
  312. // Methods
  313. Vector2.prototype.normalize = function () {
  314. var len = this.length();
  315. if (len === 0)
  316. return this;
  317. var num = 1.0 / len;
  318. this.x *= num;
  319. this.y *= num;
  320. return this;
  321. };
  322. Vector2.prototype.clone = function () {
  323. return new Vector2(this.x, this.y);
  324. };
  325. // Statics
  326. Vector2.Zero = function () {
  327. return new Vector2(0, 0);
  328. };
  329. Vector2.FromArray = function (array, offset) {
  330. if (offset === void 0) { offset = 0; }
  331. return new Vector2(array[offset], array[offset + 1]);
  332. };
  333. Vector2.FromArrayToRef = function (array, offset, result) {
  334. result.x = array[offset];
  335. result.y = array[offset + 1];
  336. };
  337. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  338. var squared = amount * amount;
  339. var cubed = amount * squared;
  340. 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));
  341. 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));
  342. return new Vector2(x, y);
  343. };
  344. Vector2.Clamp = function (value, min, max) {
  345. var x = value.x;
  346. x = (x > max.x) ? max.x : x;
  347. x = (x < min.x) ? min.x : x;
  348. var y = value.y;
  349. y = (y > max.y) ? max.y : y;
  350. y = (y < min.y) ? min.y : y;
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  354. var squared = amount * amount;
  355. var cubed = amount * squared;
  356. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  357. var part2 = (-2.0 * cubed) + (3.0 * squared);
  358. var part3 = (cubed - (2.0 * squared)) + amount;
  359. var part4 = cubed - squared;
  360. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  361. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  362. return new Vector2(x, y);
  363. };
  364. Vector2.Lerp = function (start, end, amount) {
  365. var x = start.x + ((end.x - start.x) * amount);
  366. var y = start.y + ((end.y - start.y) * amount);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Dot = function (left, right) {
  370. return left.x * right.x + left.y * right.y;
  371. };
  372. Vector2.Normalize = function (vector) {
  373. var newVector = vector.clone();
  374. newVector.normalize();
  375. return newVector;
  376. };
  377. Vector2.Minimize = function (left, right) {
  378. var x = (left.x < right.x) ? left.x : right.x;
  379. var y = (left.y < right.y) ? left.y : right.y;
  380. return new Vector2(x, y);
  381. };
  382. Vector2.Maximize = 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.Transform = function (vector, transformation) {
  388. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  389. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Distance = function (value1, value2) {
  393. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  394. };
  395. Vector2.DistanceSquared = function (value1, value2) {
  396. var x = value1.x - value2.x;
  397. var y = value1.y - value2.y;
  398. return (x * x) + (y * y);
  399. };
  400. return Vector2;
  401. })();
  402. BABYLON.Vector2 = Vector2;
  403. var Vector3 = (function () {
  404. function Vector3(x, y, z) {
  405. this.x = x;
  406. this.y = y;
  407. this.z = z;
  408. }
  409. Vector3.prototype.toString = function () {
  410. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  411. };
  412. // Operators
  413. Vector3.prototype.asArray = function () {
  414. var result = [];
  415. this.toArray(result, 0);
  416. return result;
  417. };
  418. Vector3.prototype.toArray = function (array, index) {
  419. if (index === void 0) { index = 0; }
  420. array[index] = this.x;
  421. array[index + 1] = this.y;
  422. array[index + 2] = this.z;
  423. return this;
  424. };
  425. Vector3.prototype.toQuaternion = function () {
  426. var result = new Quaternion(0, 0, 0, 1);
  427. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  428. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  429. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  430. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  431. var cosy = Math.cos(this.y * 0.5);
  432. var siny = Math.sin(this.y * 0.5);
  433. result.x = coszMinusx * siny;
  434. result.y = -sinzMinusx * siny;
  435. result.z = sinxPlusz * cosy;
  436. result.w = cosxPlusz * cosy;
  437. return result;
  438. };
  439. Vector3.prototype.addInPlace = function (otherVector) {
  440. this.x += otherVector.x;
  441. this.y += otherVector.y;
  442. this.z += otherVector.z;
  443. return this;
  444. };
  445. Vector3.prototype.add = function (otherVector) {
  446. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  447. };
  448. Vector3.prototype.addToRef = function (otherVector, result) {
  449. result.x = this.x + otherVector.x;
  450. result.y = this.y + otherVector.y;
  451. result.z = this.z + otherVector.z;
  452. return this;
  453. };
  454. Vector3.prototype.subtractInPlace = function (otherVector) {
  455. this.x -= otherVector.x;
  456. this.y -= otherVector.y;
  457. this.z -= otherVector.z;
  458. return this;
  459. };
  460. Vector3.prototype.subtract = function (otherVector) {
  461. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  462. };
  463. Vector3.prototype.subtractToRef = function (otherVector, result) {
  464. result.x = this.x - otherVector.x;
  465. result.y = this.y - otherVector.y;
  466. result.z = this.z - otherVector.z;
  467. return this;
  468. };
  469. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  470. return new Vector3(this.x - x, this.y - y, this.z - z);
  471. };
  472. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  473. result.x = this.x - x;
  474. result.y = this.y - y;
  475. result.z = this.z - z;
  476. return this;
  477. };
  478. Vector3.prototype.negate = function () {
  479. return new Vector3(-this.x, -this.y, -this.z);
  480. };
  481. Vector3.prototype.scaleInPlace = function (scale) {
  482. this.x *= scale;
  483. this.y *= scale;
  484. this.z *= scale;
  485. return this;
  486. };
  487. Vector3.prototype.scale = function (scale) {
  488. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  489. };
  490. Vector3.prototype.scaleToRef = function (scale, result) {
  491. result.x = this.x * scale;
  492. result.y = this.y * scale;
  493. result.z = this.z * scale;
  494. };
  495. Vector3.prototype.equals = function (otherVector) {
  496. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  497. };
  498. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  499. 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;
  500. };
  501. Vector3.prototype.equalsToFloats = function (x, y, z) {
  502. return this.x === x && this.y === y && this.z === z;
  503. };
  504. Vector3.prototype.multiplyInPlace = function (otherVector) {
  505. this.x *= otherVector.x;
  506. this.y *= otherVector.y;
  507. this.z *= otherVector.z;
  508. return this;
  509. };
  510. Vector3.prototype.multiply = function (otherVector) {
  511. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  512. };
  513. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  514. result.x = this.x * otherVector.x;
  515. result.y = this.y * otherVector.y;
  516. result.z = this.z * otherVector.z;
  517. return this;
  518. };
  519. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  520. return new Vector3(this.x * x, this.y * y, this.z * z);
  521. };
  522. Vector3.prototype.divide = function (otherVector) {
  523. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  524. };
  525. Vector3.prototype.divideToRef = function (otherVector, result) {
  526. result.x = this.x / otherVector.x;
  527. result.y = this.y / otherVector.y;
  528. result.z = this.z / otherVector.z;
  529. return this;
  530. };
  531. Vector3.prototype.MinimizeInPlace = function (other) {
  532. if (other.x < this.x)
  533. this.x = other.x;
  534. if (other.y < this.y)
  535. this.y = other.y;
  536. if (other.z < this.z)
  537. this.z = other.z;
  538. return this;
  539. };
  540. Vector3.prototype.MaximizeInPlace = function (other) {
  541. if (other.x > this.x)
  542. this.x = other.x;
  543. if (other.y > this.y)
  544. this.y = other.y;
  545. if (other.z > this.z)
  546. this.z = other.z;
  547. return this;
  548. };
  549. // Properties
  550. Vector3.prototype.length = function () {
  551. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  552. };
  553. Vector3.prototype.lengthSquared = function () {
  554. return (this.x * this.x + this.y * this.y + this.z * this.z);
  555. };
  556. // Methods
  557. Vector3.prototype.normalize = function () {
  558. var len = this.length();
  559. if (len === 0)
  560. return this;
  561. var num = 1.0 / len;
  562. this.x *= num;
  563. this.y *= num;
  564. this.z *= num;
  565. return this;
  566. };
  567. Vector3.prototype.clone = function () {
  568. return new Vector3(this.x, this.y, this.z);
  569. };
  570. Vector3.prototype.copyFrom = function (source) {
  571. this.x = source.x;
  572. this.y = source.y;
  573. this.z = source.z;
  574. return this;
  575. };
  576. Vector3.prototype.copyFromFloats = function (x, y, z) {
  577. this.x = x;
  578. this.y = y;
  579. this.z = z;
  580. return this;
  581. };
  582. // Statics
  583. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  584. var d0 = Vector3.Dot(vector0, axis) - size;
  585. var d1 = Vector3.Dot(vector1, axis) - size;
  586. var s = d0 / (d0 - d1);
  587. return s;
  588. };
  589. Vector3.FromArray = function (array, offset) {
  590. if (!offset) {
  591. offset = 0;
  592. }
  593. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  594. };
  595. Vector3.FromArrayToRef = function (array, offset, result) {
  596. result.x = array[offset];
  597. result.y = array[offset + 1];
  598. result.z = array[offset + 2];
  599. };
  600. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatsToRef = function (x, y, z, result) {
  606. result.x = x;
  607. result.y = y;
  608. result.z = z;
  609. };
  610. Vector3.Zero = function () {
  611. return new Vector3(0, 0, 0);
  612. };
  613. Vector3.Up = function () {
  614. return new Vector3(0, 1.0, 0);
  615. };
  616. Vector3.TransformCoordinates = function (vector, transformation) {
  617. var result = Vector3.Zero();
  618. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  619. return result;
  620. };
  621. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  622. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  623. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  624. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  625. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  626. result.x = x / w;
  627. result.y = y / w;
  628. result.z = z / w;
  629. };
  630. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  631. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  632. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  633. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  634. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  635. result.x = rx / rw;
  636. result.y = ry / rw;
  637. result.z = rz / rw;
  638. };
  639. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  640. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  641. var m0 = SIMD.float32x4.load(transformation.m, 0);
  642. var m1 = SIMD.float32x4.load(transformation.m, 4);
  643. var m2 = SIMD.float32x4.load(transformation.m, 8);
  644. var m3 = SIMD.float32x4.load(transformation.m, 12);
  645. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  646. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  647. SIMD.float32x4.storeXYZ(result._data, 0, r);
  648. };
  649. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  650. var v0 = SIMD.float32x4.splat(x);
  651. var v1 = SIMD.float32x4.splat(y);
  652. var v2 = SIMD.float32x4.splat(z);
  653. var m0 = SIMD.float32x4.load(transformation.m, 0);
  654. var m1 = SIMD.float32x4.load(transformation.m, 4);
  655. var m2 = SIMD.float32x4.load(transformation.m, 8);
  656. var m3 = SIMD.float32x4.load(transformation.m, 12);
  657. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  658. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  659. SIMD.float32x4.storeXYZ(result._data, 0, r);
  660. };
  661. Vector3.TransformNormal = function (vector, transformation) {
  662. var result = Vector3.Zero();
  663. Vector3.TransformNormalToRef(vector, transformation, result);
  664. return result;
  665. };
  666. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  667. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  668. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  669. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  670. };
  671. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  672. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  673. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  674. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  675. };
  676. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  677. var squared = amount * amount;
  678. var cubed = amount * squared;
  679. 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));
  680. 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));
  681. 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));
  682. return new Vector3(x, y, z);
  683. };
  684. Vector3.Clamp = function (value, min, max) {
  685. var x = value.x;
  686. x = (x > max.x) ? max.x : x;
  687. x = (x < min.x) ? min.x : x;
  688. var y = value.y;
  689. y = (y > max.y) ? max.y : y;
  690. y = (y < min.y) ? min.y : y;
  691. var z = value.z;
  692. z = (z > max.z) ? max.z : z;
  693. z = (z < min.z) ? min.z : z;
  694. return new Vector3(x, y, z);
  695. };
  696. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  697. var squared = amount * amount;
  698. var cubed = amount * squared;
  699. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  700. var part2 = (-2.0 * cubed) + (3.0 * squared);
  701. var part3 = (cubed - (2.0 * squared)) + amount;
  702. var part4 = cubed - squared;
  703. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  704. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  705. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Lerp = function (start, end, amount) {
  709. var x = start.x + ((end.x - start.x) * amount);
  710. var y = start.y + ((end.y - start.y) * amount);
  711. var z = start.z + ((end.z - start.z) * amount);
  712. return new Vector3(x, y, z);
  713. };
  714. Vector3.Dot = function (left, right) {
  715. return (left.x * right.x + left.y * right.y + left.z * right.z);
  716. };
  717. Vector3.Cross = function (left, right) {
  718. var result = Vector3.Zero();
  719. Vector3.CrossToRef(left, right, result);
  720. return result;
  721. };
  722. Vector3.CrossToRef = function (left, right, result) {
  723. result.x = left.y * right.z - left.z * right.y;
  724. result.y = left.z * right.x - left.x * right.z;
  725. result.z = left.x * right.y - left.y * right.x;
  726. };
  727. Vector3.Normalize = function (vector) {
  728. var result = Vector3.Zero();
  729. Vector3.NormalizeToRef(vector, result);
  730. return result;
  731. };
  732. Vector3.NormalizeToRef = function (vector, result) {
  733. result.copyFrom(vector);
  734. result.normalize();
  735. };
  736. Vector3.Project = function (vector, world, transform, viewport) {
  737. var cw = viewport.width;
  738. var ch = viewport.height;
  739. var cx = viewport.x;
  740. var cy = viewport.y;
  741. 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);
  742. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  743. return Vector3.TransformCoordinates(vector, finalMatrix);
  744. };
  745. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  746. var matrix = world.multiply(transform);
  747. matrix.invert();
  748. source.x = source.x / viewportWidth * 2 - 1;
  749. source.y = -(source.y / viewportHeight * 2 - 1);
  750. var vector = Vector3.TransformCoordinates(source, matrix);
  751. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  752. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  753. vector = vector.scale(1.0 / num);
  754. }
  755. return vector;
  756. };
  757. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  758. var matrix = world.multiply(view).multiply(projection);
  759. matrix.invert();
  760. source.x = source.x / viewportWidth * 2 - 1;
  761. source.y = -(source.y / viewportHeight * 2 - 1);
  762. var vector = Vector3.TransformCoordinates(source, matrix);
  763. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  764. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  765. vector = vector.scale(1.0 / num);
  766. }
  767. return vector;
  768. };
  769. Vector3.Minimize = function (left, right) {
  770. var min = left.clone();
  771. min.MinimizeInPlace(right);
  772. return min;
  773. };
  774. Vector3.Maximize = function (left, right) {
  775. var max = left.clone();
  776. max.MaximizeInPlace(right);
  777. return max;
  778. };
  779. Vector3.Distance = function (value1, value2) {
  780. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  781. };
  782. Vector3.DistanceSquared = function (value1, value2) {
  783. var x = value1.x - value2.x;
  784. var y = value1.y - value2.y;
  785. var z = value1.z - value2.z;
  786. return (x * x) + (y * y) + (z * z);
  787. };
  788. Vector3.Center = function (value1, value2) {
  789. var center = value1.add(value2);
  790. center.scaleInPlace(0.5);
  791. return center;
  792. };
  793. return Vector3;
  794. })();
  795. BABYLON.Vector3 = Vector3;
  796. //Vector4 class created for EulerAngle class conversion to Quaternion
  797. var Vector4 = (function () {
  798. function Vector4(x, y, z, w) {
  799. this.x = x;
  800. this.y = y;
  801. this.z = z;
  802. this.w = w;
  803. }
  804. Vector4.prototype.toString = function () {
  805. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  806. };
  807. // Operators
  808. Vector4.prototype.asArray = function () {
  809. var result = [];
  810. this.toArray(result, 0);
  811. return result;
  812. };
  813. Vector4.prototype.toArray = function (array, index) {
  814. if (index === undefined) {
  815. index = 0;
  816. }
  817. array[index] = this.x;
  818. array[index + 1] = this.y;
  819. array[index + 2] = this.z;
  820. array[index + 3] = this.w;
  821. return this;
  822. };
  823. Vector4.prototype.addInPlace = function (otherVector) {
  824. this.x += otherVector.x;
  825. this.y += otherVector.y;
  826. this.z += otherVector.z;
  827. this.w += otherVector.w;
  828. return this;
  829. };
  830. Vector4.prototype.add = function (otherVector) {
  831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  832. };
  833. Vector4.prototype.addToRef = function (otherVector, result) {
  834. result.x = this.x + otherVector.x;
  835. result.y = this.y + otherVector.y;
  836. result.z = this.z + otherVector.z;
  837. result.w = this.w + otherVector.w;
  838. return this;
  839. };
  840. Vector4.prototype.subtractInPlace = function (otherVector) {
  841. this.x -= otherVector.x;
  842. this.y -= otherVector.y;
  843. this.z -= otherVector.z;
  844. this.w -= otherVector.w;
  845. return this;
  846. };
  847. Vector4.prototype.subtract = function (otherVector) {
  848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  849. };
  850. Vector4.prototype.subtractToRef = function (otherVector, result) {
  851. result.x = this.x - otherVector.x;
  852. result.y = this.y - otherVector.y;
  853. result.z = this.z - otherVector.z;
  854. result.w = this.w - otherVector.w;
  855. return this;
  856. };
  857. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  858. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  859. };
  860. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  861. result.x = this.x - x;
  862. result.y = this.y - y;
  863. result.z = this.z - z;
  864. result.w = this.w - w;
  865. return this;
  866. };
  867. Vector4.prototype.negate = function () {
  868. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  869. };
  870. Vector4.prototype.scaleInPlace = function (scale) {
  871. this.x *= scale;
  872. this.y *= scale;
  873. this.z *= scale;
  874. this.w *= scale;
  875. return this;
  876. };
  877. Vector4.prototype.scale = function (scale) {
  878. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  879. };
  880. Vector4.prototype.scaleToRef = function (scale, result) {
  881. result.x = this.x * scale;
  882. result.y = this.y * scale;
  883. result.z = this.z * scale;
  884. result.w = this.w * scale;
  885. };
  886. Vector4.prototype.equals = function (otherVector) {
  887. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  888. };
  889. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  890. 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;
  891. };
  892. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  893. return this.x === x && this.y === y && this.z === z && this.w === w;
  894. };
  895. Vector4.prototype.multiplyInPlace = function (otherVector) {
  896. this.x *= otherVector.x;
  897. this.y *= otherVector.y;
  898. this.z *= otherVector.z;
  899. this.w *= otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.multiply = function (otherVector) {
  903. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  904. };
  905. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  906. result.x = this.x * otherVector.x;
  907. result.y = this.y * otherVector.y;
  908. result.z = this.z * otherVector.z;
  909. result.w = this.w * otherVector.w;
  910. return this;
  911. };
  912. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  913. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  914. };
  915. Vector4.prototype.divide = function (otherVector) {
  916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  917. };
  918. Vector4.prototype.divideToRef = function (otherVector, result) {
  919. result.x = this.x / otherVector.x;
  920. result.y = this.y / otherVector.y;
  921. result.z = this.z / otherVector.z;
  922. result.w = this.w / otherVector.w;
  923. return this;
  924. };
  925. Vector4.prototype.MinimizeInPlace = function (other) {
  926. if (other.x < this.x)
  927. this.x = other.x;
  928. if (other.y < this.y)
  929. this.y = other.y;
  930. if (other.z < this.z)
  931. this.z = other.z;
  932. if (other.w < this.w)
  933. this.w = other.w;
  934. return this;
  935. };
  936. Vector4.prototype.MaximizeInPlace = function (other) {
  937. if (other.x > this.x)
  938. this.x = other.x;
  939. if (other.y > this.y)
  940. this.y = other.y;
  941. if (other.z > this.z)
  942. this.z = other.z;
  943. if (other.w > this.w)
  944. this.w = other.w;
  945. return this;
  946. };
  947. // Properties
  948. Vector4.prototype.length = function () {
  949. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  950. };
  951. Vector4.prototype.lengthSquared = function () {
  952. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  953. };
  954. // Methods
  955. Vector4.prototype.normalize = function () {
  956. var len = this.length();
  957. if (len === 0)
  958. return this;
  959. var num = 1.0 / len;
  960. this.x *= num;
  961. this.y *= num;
  962. this.z *= num;
  963. this.w *= num;
  964. return this;
  965. };
  966. Vector4.prototype.clone = function () {
  967. return new Vector4(this.x, this.y, this.z, this.w);
  968. };
  969. Vector4.prototype.copyFrom = function (source) {
  970. this.x = source.x;
  971. this.y = source.y;
  972. this.z = source.z;
  973. this.w = source.w;
  974. return this;
  975. };
  976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. return this;
  982. };
  983. // Statics
  984. Vector4.FromArray = function (array, offset) {
  985. if (!offset) {
  986. offset = 0;
  987. }
  988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  989. };
  990. Vector4.FromArrayToRef = function (array, offset, result) {
  991. result.x = array[offset];
  992. result.y = array[offset + 1];
  993. result.z = array[offset + 2];
  994. result.w = array[offset + 3];
  995. };
  996. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  997. result.x = array[offset];
  998. result.y = array[offset + 1];
  999. result.z = array[offset + 2];
  1000. result.w = array[offset + 3];
  1001. };
  1002. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1003. result.x = x;
  1004. result.y = y;
  1005. result.z = z;
  1006. result.w = w;
  1007. };
  1008. Vector4.Zero = function () {
  1009. return new Vector4(0, 0, 0, 0);
  1010. };
  1011. Vector4.Normalize = function (vector) {
  1012. var result = Vector4.Zero();
  1013. Vector4.NormalizeToRef(vector, result);
  1014. return result;
  1015. };
  1016. Vector4.NormalizeToRef = function (vector, result) {
  1017. result.copyFrom(vector);
  1018. result.normalize();
  1019. };
  1020. Vector4.Minimize = function (left, right) {
  1021. var min = left.clone();
  1022. min.MinimizeInPlace(right);
  1023. return min;
  1024. };
  1025. Vector4.Maximize = function (left, right) {
  1026. var max = left.clone();
  1027. max.MaximizeInPlace(right);
  1028. return max;
  1029. };
  1030. Vector4.Distance = function (value1, value2) {
  1031. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1032. };
  1033. Vector4.DistanceSquared = function (value1, value2) {
  1034. var x = value1.x - value2.x;
  1035. var y = value1.y - value2.y;
  1036. var z = value1.z - value2.z;
  1037. var w = value1.w - value2.w;
  1038. return (x * x) + (y * y) + (z * z) + (w * w);
  1039. };
  1040. Vector4.Center = function (value1, value2) {
  1041. var center = value1.add(value2);
  1042. center.scaleInPlace(0.5);
  1043. return center;
  1044. };
  1045. return Vector4;
  1046. })();
  1047. BABYLON.Vector4 = Vector4;
  1048. var Quaternion = (function () {
  1049. function Quaternion(x, y, z, w) {
  1050. if (x === void 0) { x = 0; }
  1051. if (y === void 0) { y = 0; }
  1052. if (z === void 0) { z = 0; }
  1053. if (w === void 0) { w = 1; }
  1054. this.x = x;
  1055. this.y = y;
  1056. this.z = z;
  1057. this.w = w;
  1058. }
  1059. Quaternion.prototype.toString = function () {
  1060. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1061. };
  1062. Quaternion.prototype.asArray = function () {
  1063. return [this.x, this.y, this.z, this.w];
  1064. };
  1065. Quaternion.prototype.equals = function (otherQuaternion) {
  1066. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1067. };
  1068. Quaternion.prototype.clone = function () {
  1069. return new Quaternion(this.x, this.y, this.z, this.w);
  1070. };
  1071. Quaternion.prototype.copyFrom = function (other) {
  1072. this.x = other.x;
  1073. this.y = other.y;
  1074. this.z = other.z;
  1075. this.w = other.w;
  1076. return this;
  1077. };
  1078. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1079. this.x = x;
  1080. this.y = y;
  1081. this.z = z;
  1082. this.w = w;
  1083. return this;
  1084. };
  1085. Quaternion.prototype.add = function (other) {
  1086. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1087. };
  1088. Quaternion.prototype.subtract = function (other) {
  1089. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1090. };
  1091. Quaternion.prototype.scale = function (value) {
  1092. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1093. };
  1094. Quaternion.prototype.multiply = function (q1) {
  1095. var result = new Quaternion(0, 0, 0, 1.0);
  1096. this.multiplyToRef(q1, result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1100. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1101. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1102. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1103. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1104. return this;
  1105. };
  1106. Quaternion.prototype.length = function () {
  1107. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1108. };
  1109. Quaternion.prototype.normalize = function () {
  1110. var length = 1.0 / this.length();
  1111. this.x *= length;
  1112. this.y *= length;
  1113. this.z *= length;
  1114. this.w *= length;
  1115. return this;
  1116. };
  1117. Quaternion.prototype.toEulerAngles = function () {
  1118. var result = Vector3.Zero();
  1119. this.toEulerAnglesToRef(result);
  1120. return result;
  1121. };
  1122. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1123. //result is an EulerAngles in the in the z-x-z convention
  1124. var qx = this.x;
  1125. var qy = this.y;
  1126. var qz = this.z;
  1127. var qw = this.w;
  1128. var qxy = qx * qy;
  1129. var qxz = qx * qz;
  1130. var qwy = qw * qy;
  1131. var qwz = qw * qz;
  1132. var qwx = qw * qx;
  1133. var qyz = qy * qz;
  1134. var sqx = qx * qx;
  1135. var sqy = qy * qy;
  1136. var determinant = sqx + sqy;
  1137. if (determinant !== 0.000 && determinant !== 1.000) {
  1138. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1139. result.y = Math.acos(1 - 2 * determinant);
  1140. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1141. }
  1142. else {
  1143. if (determinant === 0.0) {
  1144. result.x = 0.0;
  1145. result.y = 0.0;
  1146. 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)
  1147. }
  1148. else {
  1149. 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)
  1150. result.y = Math.PI;
  1151. result.z = 0.0;
  1152. }
  1153. }
  1154. return this;
  1155. };
  1156. Quaternion.prototype.toRotationMatrix = function (result) {
  1157. var xx = this.x * this.x;
  1158. var yy = this.y * this.y;
  1159. var zz = this.z * this.z;
  1160. var xy = this.x * this.y;
  1161. var zw = this.z * this.w;
  1162. var zx = this.z * this.x;
  1163. var yw = this.y * this.w;
  1164. var yz = this.y * this.z;
  1165. var xw = this.x * this.w;
  1166. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1167. result.m[1] = 2.0 * (xy + zw);
  1168. result.m[2] = 2.0 * (zx - yw);
  1169. result.m[3] = 0;
  1170. result.m[4] = 2.0 * (xy - zw);
  1171. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1172. result.m[6] = 2.0 * (yz + xw);
  1173. result.m[7] = 0;
  1174. result.m[8] = 2.0 * (zx + yw);
  1175. result.m[9] = 2.0 * (yz - xw);
  1176. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1177. result.m[11] = 0;
  1178. result.m[12] = 0;
  1179. result.m[13] = 0;
  1180. result.m[14] = 0;
  1181. result.m[15] = 1.0;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1185. Quaternion.FromRotationMatrixToRef(matrix, this);
  1186. return this;
  1187. };
  1188. // Statics
  1189. Quaternion.FromRotationMatrix = function (matrix) {
  1190. var result = new Quaternion();
  1191. Quaternion.FromRotationMatrixToRef(matrix, result);
  1192. return result;
  1193. };
  1194. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1195. var data = matrix.m;
  1196. var m11 = data[0], m12 = data[4], m13 = data[8];
  1197. var m21 = data[1], m22 = data[5], m23 = data[9];
  1198. var m31 = data[2], m32 = data[6], m33 = data[10];
  1199. var trace = m11 + m22 + m33;
  1200. var s;
  1201. if (trace > 0) {
  1202. s = 0.5 / Math.sqrt(trace + 1.0);
  1203. result.w = 0.25 / s;
  1204. result.x = (m32 - m23) * s;
  1205. result.y = (m13 - m31) * s;
  1206. result.z = (m21 - m12) * s;
  1207. }
  1208. else if (m11 > m22 && m11 > m33) {
  1209. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1210. result.w = (m32 - m23) / s;
  1211. result.x = 0.25 * s;
  1212. result.y = (m12 + m21) / s;
  1213. result.z = (m13 + m31) / s;
  1214. }
  1215. else if (m22 > m33) {
  1216. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1217. result.w = (m13 - m31) / s;
  1218. result.x = (m12 + m21) / s;
  1219. result.y = 0.25 * s;
  1220. result.z = (m23 + m32) / s;
  1221. }
  1222. else {
  1223. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1224. result.w = (m21 - m12) / s;
  1225. result.x = (m13 + m31) / s;
  1226. result.y = (m23 + m32) / s;
  1227. result.z = 0.25 * s;
  1228. }
  1229. };
  1230. Quaternion.Inverse = function (q) {
  1231. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1232. };
  1233. Quaternion.Identity = function () {
  1234. return new Quaternion(0, 0, 0, 1);
  1235. };
  1236. Quaternion.RotationAxis = function (axis, angle) {
  1237. var result = new Quaternion();
  1238. var sin = Math.sin(angle / 2);
  1239. result.w = Math.cos(angle / 2);
  1240. result.x = axis.x * sin;
  1241. result.y = axis.y * sin;
  1242. result.z = axis.z * sin;
  1243. return result;
  1244. };
  1245. Quaternion.FromArray = function (array, offset) {
  1246. if (!offset) {
  1247. offset = 0;
  1248. }
  1249. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1250. };
  1251. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1252. var result = new Quaternion();
  1253. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1254. return result;
  1255. };
  1256. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1257. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1258. var halfRoll = roll * 0.5;
  1259. var halfPitch = pitch * 0.5;
  1260. var halfYaw = yaw * 0.5;
  1261. var sinRoll = Math.sin(halfRoll);
  1262. var cosRoll = Math.cos(halfRoll);
  1263. var sinPitch = Math.sin(halfPitch);
  1264. var cosPitch = Math.cos(halfPitch);
  1265. var sinYaw = Math.sin(halfYaw);
  1266. var cosYaw = Math.cos(halfYaw);
  1267. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1268. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1269. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1270. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1271. };
  1272. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1273. var result = new Quaternion();
  1274. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1275. return result;
  1276. };
  1277. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1278. // Produces a quaternion from Euler angles in the z-x-z orientation
  1279. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1280. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1281. var halfBeta = beta * 0.5;
  1282. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1284. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1286. };
  1287. Quaternion.Slerp = function (left, right, amount) {
  1288. var num2;
  1289. var num3;
  1290. var num = amount;
  1291. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1292. var flag = false;
  1293. if (num4 < 0) {
  1294. flag = true;
  1295. num4 = -num4;
  1296. }
  1297. if (num4 > 0.999999) {
  1298. num3 = 1 - num;
  1299. num2 = flag ? -num : num;
  1300. }
  1301. else {
  1302. var num5 = Math.acos(num4);
  1303. var num6 = (1.0 / Math.sin(num5));
  1304. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1305. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1306. }
  1307. 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));
  1308. };
  1309. return Quaternion;
  1310. })();
  1311. BABYLON.Quaternion = Quaternion;
  1312. var Matrix = (function () {
  1313. function Matrix() {
  1314. this.m = new Float32Array(16);
  1315. }
  1316. // Properties
  1317. Matrix.prototype.isIdentity = function () {
  1318. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1319. return false;
  1320. 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)
  1321. return false;
  1322. return true;
  1323. };
  1324. Matrix.prototype.determinant = function () {
  1325. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1326. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1327. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1328. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1329. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1330. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1331. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (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))));
  1332. };
  1333. // Methods
  1334. Matrix.prototype.toArray = function () {
  1335. return this.m;
  1336. };
  1337. Matrix.prototype.asArray = function () {
  1338. return this.toArray();
  1339. };
  1340. Matrix.prototype.invert = function () {
  1341. this.invertToRef(this);
  1342. return this;
  1343. };
  1344. Matrix.prototype.invertToRef = function (other) {
  1345. var l1 = this.m[0];
  1346. var l2 = this.m[1];
  1347. var l3 = this.m[2];
  1348. var l4 = this.m[3];
  1349. var l5 = this.m[4];
  1350. var l6 = this.m[5];
  1351. var l7 = this.m[6];
  1352. var l8 = this.m[7];
  1353. var l9 = this.m[8];
  1354. var l10 = this.m[9];
  1355. var l11 = this.m[10];
  1356. var l12 = this.m[11];
  1357. var l13 = this.m[12];
  1358. var l14 = this.m[13];
  1359. var l15 = this.m[14];
  1360. var l16 = this.m[15];
  1361. var l17 = (l11 * l16) - (l12 * l15);
  1362. var l18 = (l10 * l16) - (l12 * l14);
  1363. var l19 = (l10 * l15) - (l11 * l14);
  1364. var l20 = (l9 * l16) - (l12 * l13);
  1365. var l21 = (l9 * l15) - (l11 * l13);
  1366. var l22 = (l9 * l14) - (l10 * l13);
  1367. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1368. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1369. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1370. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1371. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1372. var l28 = (l7 * l16) - (l8 * l15);
  1373. var l29 = (l6 * l16) - (l8 * l14);
  1374. var l30 = (l6 * l15) - (l7 * l14);
  1375. var l31 = (l5 * l16) - (l8 * l13);
  1376. var l32 = (l5 * l15) - (l7 * l13);
  1377. var l33 = (l5 * l14) - (l6 * l13);
  1378. var l34 = (l7 * l12) - (l8 * l11);
  1379. var l35 = (l6 * l12) - (l8 * l10);
  1380. var l36 = (l6 * l11) - (l7 * l10);
  1381. var l37 = (l5 * l12) - (l8 * l9);
  1382. var l38 = (l5 * l11) - (l7 * l9);
  1383. var l39 = (l5 * l10) - (l6 * l9);
  1384. other.m[0] = l23 * l27;
  1385. other.m[4] = l24 * l27;
  1386. other.m[8] = l25 * l27;
  1387. other.m[12] = l26 * l27;
  1388. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1389. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1390. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1391. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1392. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1393. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1394. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1395. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1396. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1397. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1398. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1399. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1400. return this;
  1401. };
  1402. Matrix.prototype.invertToRefSIMD = function (other) {
  1403. var src = this.m;
  1404. var dest = other.m;
  1405. var row0, row1, row2, row3;
  1406. var tmp1;
  1407. var minor0, minor1, minor2, minor3;
  1408. var det;
  1409. // Load the 4 rows
  1410. var src0 = SIMD.float32x4.load(src, 0);
  1411. var src1 = SIMD.float32x4.load(src, 4);
  1412. var src2 = SIMD.float32x4.load(src, 8);
  1413. var src3 = SIMD.float32x4.load(src, 12);
  1414. // Transpose the source matrix. Sort of. Not a true transpose operation
  1415. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1416. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1417. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1418. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1419. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1420. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1421. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1422. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1423. // This is a true transposition, but it will lead to an incorrect result
  1424. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1425. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1426. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1427. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1428. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1429. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1430. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1431. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1432. // ----
  1433. tmp1 = SIMD.float32x4.mul(row2, row3);
  1434. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1435. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1436. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1437. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1438. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1439. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1440. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1441. // ----
  1442. tmp1 = SIMD.float32x4.mul(row1, row2);
  1443. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1444. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1445. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1446. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1447. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1448. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1449. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1450. // ----
  1451. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1452. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1453. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1454. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1455. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1456. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1457. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1458. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1459. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1460. // ----
  1461. tmp1 = SIMD.float32x4.mul(row0, row1);
  1462. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1463. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1464. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1465. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1466. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1467. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1468. // ----
  1469. tmp1 = SIMD.float32x4.mul(row0, row3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1471. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1472. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1473. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1474. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1475. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1476. // ----
  1477. tmp1 = SIMD.float32x4.mul(row0, row2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1480. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1481. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1482. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1483. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1484. // Compute determinant
  1485. det = SIMD.float32x4.mul(row0, minor0);
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1487. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1488. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1489. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1490. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1491. // These shuffles aren't necessary if the faulty transposition is done
  1492. // up at the top of this function.
  1493. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1494. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1495. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1496. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1497. // Compute final values by multiplying with 1/det
  1498. minor0 = SIMD.float32x4.mul(det, minor0);
  1499. minor1 = SIMD.float32x4.mul(det, minor1);
  1500. minor2 = SIMD.float32x4.mul(det, minor2);
  1501. minor3 = SIMD.float32x4.mul(det, minor3);
  1502. SIMD.float32x4.store(dest, 0, minor0);
  1503. SIMD.float32x4.store(dest, 4, minor1);
  1504. SIMD.float32x4.store(dest, 8, minor2);
  1505. SIMD.float32x4.store(dest, 12, minor3);
  1506. return this;
  1507. };
  1508. Matrix.prototype.setTranslation = function (vector3) {
  1509. this.m[12] = vector3.x;
  1510. this.m[13] = vector3.y;
  1511. this.m[14] = vector3.z;
  1512. return this;
  1513. };
  1514. Matrix.prototype.multiply = function (other) {
  1515. var result = new Matrix();
  1516. this.multiplyToRef(other, result);
  1517. return result;
  1518. };
  1519. Matrix.prototype.copyFrom = function (other) {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = other.m[index];
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.copyToArray = function (array, offset) {
  1526. if (offset === void 0) { offset = 0; }
  1527. for (var index = 0; index < 16; index++) {
  1528. array[offset + index] = this.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.multiplyToRef = function (other, result) {
  1533. this.multiplyToArray(other, result.m, 0);
  1534. return this;
  1535. };
  1536. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1537. var tm0 = this.m[0];
  1538. var tm1 = this.m[1];
  1539. var tm2 = this.m[2];
  1540. var tm3 = this.m[3];
  1541. var tm4 = this.m[4];
  1542. var tm5 = this.m[5];
  1543. var tm6 = this.m[6];
  1544. var tm7 = this.m[7];
  1545. var tm8 = this.m[8];
  1546. var tm9 = this.m[9];
  1547. var tm10 = this.m[10];
  1548. var tm11 = this.m[11];
  1549. var tm12 = this.m[12];
  1550. var tm13 = this.m[13];
  1551. var tm14 = this.m[14];
  1552. var tm15 = this.m[15];
  1553. var om0 = other.m[0];
  1554. var om1 = other.m[1];
  1555. var om2 = other.m[2];
  1556. var om3 = other.m[3];
  1557. var om4 = other.m[4];
  1558. var om5 = other.m[5];
  1559. var om6 = other.m[6];
  1560. var om7 = other.m[7];
  1561. var om8 = other.m[8];
  1562. var om9 = other.m[9];
  1563. var om10 = other.m[10];
  1564. var om11 = other.m[11];
  1565. var om12 = other.m[12];
  1566. var om13 = other.m[13];
  1567. var om14 = other.m[14];
  1568. var om15 = other.m[15];
  1569. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1570. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1571. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1572. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1573. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1574. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1575. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1576. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1577. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1578. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1579. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1580. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1581. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1582. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1583. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1584. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1585. return this;
  1586. };
  1587. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1588. if (offset === void 0) { offset = 0; }
  1589. var tm = this.m;
  1590. var om = other.m;
  1591. var om0 = SIMD.float32x4.load(om, 0);
  1592. var om1 = SIMD.float32x4.load(om, 4);
  1593. var om2 = SIMD.float32x4.load(om, 8);
  1594. var om3 = SIMD.float32x4.load(om, 12);
  1595. var tm0 = SIMD.float32x4.load(tm, 0);
  1596. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1597. var tm1 = SIMD.float32x4.load(tm, 4);
  1598. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1599. var tm2 = SIMD.float32x4.load(tm, 8);
  1600. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1601. var tm3 = SIMD.float32x4.load(tm, 12);
  1602. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1603. };
  1604. Matrix.prototype.equals = function (value) {
  1605. 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]);
  1606. };
  1607. Matrix.prototype.clone = function () {
  1608. 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]);
  1609. };
  1610. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1611. translation.x = this.m[12];
  1612. translation.y = this.m[13];
  1613. translation.z = this.m[14];
  1614. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1615. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1616. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1617. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1618. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1619. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1620. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1621. rotation.x = 0;
  1622. rotation.y = 0;
  1623. rotation.z = 0;
  1624. rotation.w = 1;
  1625. return false;
  1626. }
  1627. 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);
  1628. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1629. return true;
  1630. };
  1631. // Statics
  1632. Matrix.FromArray = function (array, offset) {
  1633. var result = new Matrix();
  1634. if (!offset) {
  1635. offset = 0;
  1636. }
  1637. Matrix.FromArrayToRef(array, offset, result);
  1638. return result;
  1639. };
  1640. Matrix.FromArrayToRef = function (array, offset, result) {
  1641. for (var index = 0; index < 16; index++) {
  1642. result.m[index] = array[index + offset];
  1643. }
  1644. };
  1645. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1646. result.m[0] = initialM11;
  1647. result.m[1] = initialM12;
  1648. result.m[2] = initialM13;
  1649. result.m[3] = initialM14;
  1650. result.m[4] = initialM21;
  1651. result.m[5] = initialM22;
  1652. result.m[6] = initialM23;
  1653. result.m[7] = initialM24;
  1654. result.m[8] = initialM31;
  1655. result.m[9] = initialM32;
  1656. result.m[10] = initialM33;
  1657. result.m[11] = initialM34;
  1658. result.m[12] = initialM41;
  1659. result.m[13] = initialM42;
  1660. result.m[14] = initialM43;
  1661. result.m[15] = initialM44;
  1662. };
  1663. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1664. var result = new Matrix();
  1665. result.m[0] = initialM11;
  1666. result.m[1] = initialM12;
  1667. result.m[2] = initialM13;
  1668. result.m[3] = initialM14;
  1669. result.m[4] = initialM21;
  1670. result.m[5] = initialM22;
  1671. result.m[6] = initialM23;
  1672. result.m[7] = initialM24;
  1673. result.m[8] = initialM31;
  1674. result.m[9] = initialM32;
  1675. result.m[10] = initialM33;
  1676. result.m[11] = initialM34;
  1677. result.m[12] = initialM41;
  1678. result.m[13] = initialM42;
  1679. result.m[14] = initialM43;
  1680. result.m[15] = initialM44;
  1681. return result;
  1682. };
  1683. Matrix.Compose = function (scale, rotation, translation) {
  1684. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1685. var rotationMatrix = Matrix.Identity();
  1686. rotation.toRotationMatrix(rotationMatrix);
  1687. result = result.multiply(rotationMatrix);
  1688. result.setTranslation(translation);
  1689. return result;
  1690. };
  1691. Matrix.Identity = function () {
  1692. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1693. };
  1694. Matrix.IdentityToRef = function (result) {
  1695. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1696. };
  1697. Matrix.Zero = function () {
  1698. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1699. };
  1700. Matrix.RotationX = function (angle) {
  1701. var result = new Matrix();
  1702. Matrix.RotationXToRef(angle, result);
  1703. return result;
  1704. };
  1705. Matrix.Invert = function (source) {
  1706. var result = new Matrix();
  1707. source.invertToRef(result);
  1708. return result;
  1709. };
  1710. Matrix.RotationXToRef = function (angle, result) {
  1711. var s = Math.sin(angle);
  1712. var c = Math.cos(angle);
  1713. result.m[0] = 1.0;
  1714. result.m[15] = 1.0;
  1715. result.m[5] = c;
  1716. result.m[10] = c;
  1717. result.m[9] = -s;
  1718. result.m[6] = s;
  1719. result.m[1] = 0;
  1720. result.m[2] = 0;
  1721. result.m[3] = 0;
  1722. result.m[4] = 0;
  1723. result.m[7] = 0;
  1724. result.m[8] = 0;
  1725. result.m[11] = 0;
  1726. result.m[12] = 0;
  1727. result.m[13] = 0;
  1728. result.m[14] = 0;
  1729. };
  1730. Matrix.RotationY = function (angle) {
  1731. var result = new Matrix();
  1732. Matrix.RotationYToRef(angle, result);
  1733. return result;
  1734. };
  1735. Matrix.RotationYToRef = function (angle, result) {
  1736. var s = Math.sin(angle);
  1737. var c = Math.cos(angle);
  1738. result.m[5] = 1.0;
  1739. result.m[15] = 1.0;
  1740. result.m[0] = c;
  1741. result.m[2] = -s;
  1742. result.m[8] = s;
  1743. result.m[10] = c;
  1744. result.m[1] = 0;
  1745. result.m[3] = 0;
  1746. result.m[4] = 0;
  1747. result.m[6] = 0;
  1748. result.m[7] = 0;
  1749. result.m[9] = 0;
  1750. result.m[11] = 0;
  1751. result.m[12] = 0;
  1752. result.m[13] = 0;
  1753. result.m[14] = 0;
  1754. };
  1755. Matrix.RotationZ = function (angle) {
  1756. var result = new Matrix();
  1757. Matrix.RotationZToRef(angle, result);
  1758. return result;
  1759. };
  1760. Matrix.RotationZToRef = function (angle, result) {
  1761. var s = Math.sin(angle);
  1762. var c = Math.cos(angle);
  1763. result.m[10] = 1.0;
  1764. result.m[15] = 1.0;
  1765. result.m[0] = c;
  1766. result.m[1] = s;
  1767. result.m[4] = -s;
  1768. result.m[5] = c;
  1769. result.m[2] = 0;
  1770. result.m[3] = 0;
  1771. result.m[6] = 0;
  1772. result.m[7] = 0;
  1773. result.m[8] = 0;
  1774. result.m[9] = 0;
  1775. result.m[11] = 0;
  1776. result.m[12] = 0;
  1777. result.m[13] = 0;
  1778. result.m[14] = 0;
  1779. };
  1780. Matrix.RotationAxis = function (axis, angle) {
  1781. var s = Math.sin(-angle);
  1782. var c = Math.cos(-angle);
  1783. var c1 = 1 - c;
  1784. axis.normalize();
  1785. var result = Matrix.Zero();
  1786. result.m[0] = (axis.x * axis.x) * c1 + c;
  1787. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1788. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1789. result.m[3] = 0.0;
  1790. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1791. result.m[5] = (axis.y * axis.y) * c1 + c;
  1792. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1793. result.m[7] = 0.0;
  1794. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1795. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1796. result.m[10] = (axis.z * axis.z) * c1 + c;
  1797. result.m[11] = 0.0;
  1798. result.m[15] = 1.0;
  1799. return result;
  1800. };
  1801. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1802. var result = new Matrix();
  1803. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1807. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1808. this._tempQuaternion.toRotationMatrix(result);
  1809. };
  1810. Matrix.Scaling = function (x, y, z) {
  1811. var result = Matrix.Zero();
  1812. Matrix.ScalingToRef(x, y, z, result);
  1813. return result;
  1814. };
  1815. Matrix.ScalingToRef = function (x, y, z, result) {
  1816. result.m[0] = x;
  1817. result.m[1] = 0;
  1818. result.m[2] = 0;
  1819. result.m[3] = 0;
  1820. result.m[4] = 0;
  1821. result.m[5] = y;
  1822. result.m[6] = 0;
  1823. result.m[7] = 0;
  1824. result.m[8] = 0;
  1825. result.m[9] = 0;
  1826. result.m[10] = z;
  1827. result.m[11] = 0;
  1828. result.m[12] = 0;
  1829. result.m[13] = 0;
  1830. result.m[14] = 0;
  1831. result.m[15] = 1.0;
  1832. };
  1833. Matrix.Translation = function (x, y, z) {
  1834. var result = Matrix.Identity();
  1835. Matrix.TranslationToRef(x, y, z, result);
  1836. return result;
  1837. };
  1838. Matrix.TranslationToRef = function (x, y, z, result) {
  1839. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1840. };
  1841. Matrix.LookAtLH = function (eye, target, up) {
  1842. var result = Matrix.Zero();
  1843. Matrix.LookAtLHToRef(eye, target, up, result);
  1844. return result;
  1845. };
  1846. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1847. // Z axis
  1848. target.subtractToRef(eye, this._zAxis);
  1849. this._zAxis.normalize();
  1850. // X axis
  1851. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1852. this._xAxis.normalize();
  1853. // Y axis
  1854. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1855. this._yAxis.normalize();
  1856. // Eye angles
  1857. var ex = -Vector3.Dot(this._xAxis, eye);
  1858. var ey = -Vector3.Dot(this._yAxis, eye);
  1859. var ez = -Vector3.Dot(this._zAxis, eye);
  1860. 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);
  1861. };
  1862. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1863. var out = result.m;
  1864. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1865. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1866. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1867. // cc.kmVec3Subtract(f, pCenter, pEye);
  1868. var f = SIMD.float32x4.sub(center, eye);
  1869. // cc.kmVec3Normalize(f, f);
  1870. var tmp = SIMD.float32x4.mul(f, f);
  1871. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1872. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1873. // cc.kmVec3Assign(up, pUp);
  1874. // cc.kmVec3Normalize(up, up);
  1875. tmp = SIMD.float32x4.mul(up, up);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Cross(s, f, up);
  1879. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1880. // cc.kmVec3Normalize(s, s);
  1881. tmp = SIMD.float32x4.mul(s, s);
  1882. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1883. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1884. // cc.kmVec3Cross(u, s, f);
  1885. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1886. // cc.kmVec3Normalize(s, s);
  1887. tmp = SIMD.float32x4.mul(s, s);
  1888. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1889. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1890. var zero = SIMD.float32x4.splat(0.0);
  1891. s = SIMD.float32x4.neg(s);
  1892. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1893. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1894. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1895. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1896. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1897. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1898. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1899. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1900. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1901. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1902. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1903. var b3 = SIMD.float32x4.neg(eye);
  1904. b3 = SIMD.float32x4.withW(b3, 1.0);
  1905. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1906. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1907. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1908. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1909. };
  1910. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1911. var matrix = Matrix.Zero();
  1912. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1913. return matrix;
  1914. };
  1915. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1916. var hw = 2.0 / width;
  1917. var hh = 2.0 / height;
  1918. var id = 1.0 / (zfar - znear);
  1919. var nid = znear / (znear - zfar);
  1920. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1921. };
  1922. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1923. var matrix = Matrix.Zero();
  1924. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1925. return matrix;
  1926. };
  1927. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1928. result.m[0] = 2.0 / (right - left);
  1929. result.m[1] = result.m[2] = result.m[3] = 0;
  1930. result.m[5] = 2.0 / (top - bottom);
  1931. result.m[4] = result.m[6] = result.m[7] = 0;
  1932. result.m[10] = -1.0 / (znear - zfar);
  1933. result.m[8] = result.m[9] = result.m[11] = 0;
  1934. result.m[12] = (left + right) / (left - right);
  1935. result.m[13] = (top + bottom) / (bottom - top);
  1936. result.m[14] = znear / (znear - zfar);
  1937. result.m[15] = 1.0;
  1938. };
  1939. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. matrix.m[0] = (2.0 * znear) / width;
  1942. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1943. matrix.m[5] = (2.0 * znear) / height;
  1944. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1945. matrix.m[10] = -zfar / (znear - zfar);
  1946. matrix.m[8] = matrix.m[9] = 0.0;
  1947. matrix.m[11] = 1.0;
  1948. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1949. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1950. return matrix;
  1951. };
  1952. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1953. var matrix = Matrix.Zero();
  1954. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1958. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1959. var tan = 1.0 / (Math.tan(fov * 0.5));
  1960. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1961. if (v_fixed) {
  1962. result.m[0] = tan / aspect;
  1963. }
  1964. else {
  1965. result.m[0] = tan;
  1966. }
  1967. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1968. if (v_fixed) {
  1969. result.m[5] = tan;
  1970. }
  1971. else {
  1972. result.m[5] = tan * aspect;
  1973. }
  1974. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1975. result.m[8] = result.m[9] = 0.0;
  1976. result.m[10] = -zfar / (znear - zfar);
  1977. result.m[11] = 1.0;
  1978. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1979. result.m[14] = (znear * zfar) / (znear - zfar);
  1980. };
  1981. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1982. var cw = viewport.width;
  1983. var ch = viewport.height;
  1984. var cx = viewport.x;
  1985. var cy = viewport.y;
  1986. 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);
  1987. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1988. };
  1989. Matrix.Transpose = function (matrix) {
  1990. var result = new Matrix();
  1991. result.m[0] = matrix.m[0];
  1992. result.m[1] = matrix.m[4];
  1993. result.m[2] = matrix.m[8];
  1994. result.m[3] = matrix.m[12];
  1995. result.m[4] = matrix.m[1];
  1996. result.m[5] = matrix.m[5];
  1997. result.m[6] = matrix.m[9];
  1998. result.m[7] = matrix.m[13];
  1999. result.m[8] = matrix.m[2];
  2000. result.m[9] = matrix.m[6];
  2001. result.m[10] = matrix.m[10];
  2002. result.m[11] = matrix.m[14];
  2003. result.m[12] = matrix.m[3];
  2004. result.m[13] = matrix.m[7];
  2005. result.m[14] = matrix.m[11];
  2006. result.m[15] = matrix.m[15];
  2007. return result;
  2008. };
  2009. Matrix.Reflection = function (plane) {
  2010. var matrix = new Matrix();
  2011. Matrix.ReflectionToRef(plane, matrix);
  2012. return matrix;
  2013. };
  2014. Matrix.ReflectionToRef = function (plane, result) {
  2015. plane.normalize();
  2016. var x = plane.normal.x;
  2017. var y = plane.normal.y;
  2018. var z = plane.normal.z;
  2019. var temp = -2 * x;
  2020. var temp2 = -2 * y;
  2021. var temp3 = -2 * z;
  2022. result.m[0] = (temp * x) + 1;
  2023. result.m[1] = temp2 * x;
  2024. result.m[2] = temp3 * x;
  2025. result.m[3] = 0.0;
  2026. result.m[4] = temp * y;
  2027. result.m[5] = (temp2 * y) + 1;
  2028. result.m[6] = temp3 * y;
  2029. result.m[7] = 0.0;
  2030. result.m[8] = temp * z;
  2031. result.m[9] = temp2 * z;
  2032. result.m[10] = (temp3 * z) + 1;
  2033. result.m[11] = 0.0;
  2034. result.m[12] = temp * plane.d;
  2035. result.m[13] = temp2 * plane.d;
  2036. result.m[14] = temp3 * plane.d;
  2037. result.m[15] = 1.0;
  2038. };
  2039. Matrix._tempQuaternion = new Quaternion();
  2040. Matrix._xAxis = Vector3.Zero();
  2041. Matrix._yAxis = Vector3.Zero();
  2042. Matrix._zAxis = Vector3.Zero();
  2043. return Matrix;
  2044. })();
  2045. BABYLON.Matrix = Matrix;
  2046. var Plane = (function () {
  2047. function Plane(a, b, c, d) {
  2048. this.normal = new Vector3(a, b, c);
  2049. this.d = d;
  2050. }
  2051. Plane.prototype.asArray = function () {
  2052. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2053. };
  2054. // Methods
  2055. Plane.prototype.clone = function () {
  2056. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2057. };
  2058. Plane.prototype.normalize = function () {
  2059. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2060. var magnitude = 0;
  2061. if (norm !== 0) {
  2062. magnitude = 1.0 / norm;
  2063. }
  2064. this.normal.x *= magnitude;
  2065. this.normal.y *= magnitude;
  2066. this.normal.z *= magnitude;
  2067. this.d *= magnitude;
  2068. return this;
  2069. };
  2070. Plane.prototype.transform = function (transformation) {
  2071. var transposedMatrix = Matrix.Transpose(transformation);
  2072. var x = this.normal.x;
  2073. var y = this.normal.y;
  2074. var z = this.normal.z;
  2075. var d = this.d;
  2076. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2077. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2078. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2079. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2080. return new Plane(normalX, normalY, normalZ, finalD);
  2081. };
  2082. Plane.prototype.dotCoordinate = function (point) {
  2083. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2084. };
  2085. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2086. var x1 = point2.x - point1.x;
  2087. var y1 = point2.y - point1.y;
  2088. var z1 = point2.z - point1.z;
  2089. var x2 = point3.x - point1.x;
  2090. var y2 = point3.y - point1.y;
  2091. var z2 = point3.z - point1.z;
  2092. var yz = (y1 * z2) - (z1 * y2);
  2093. var xz = (z1 * x2) - (x1 * z2);
  2094. var xy = (x1 * y2) - (y1 * x2);
  2095. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2096. var invPyth;
  2097. if (pyth !== 0) {
  2098. invPyth = 1.0 / pyth;
  2099. }
  2100. else {
  2101. invPyth = 0;
  2102. }
  2103. this.normal.x = yz * invPyth;
  2104. this.normal.y = xz * invPyth;
  2105. this.normal.z = xy * invPyth;
  2106. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2107. return this;
  2108. };
  2109. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2110. var dot = Vector3.Dot(this.normal, direction);
  2111. return (dot <= epsilon);
  2112. };
  2113. Plane.prototype.signedDistanceTo = function (point) {
  2114. return Vector3.Dot(point, this.normal) + this.d;
  2115. };
  2116. // Statics
  2117. Plane.FromArray = function (array) {
  2118. return new Plane(array[0], array[1], array[2], array[3]);
  2119. };
  2120. Plane.FromPoints = function (point1, point2, point3) {
  2121. var result = new Plane(0, 0, 0, 0);
  2122. result.copyFromPoints(point1, point2, point3);
  2123. return result;
  2124. };
  2125. Plane.FromPositionAndNormal = function (origin, normal) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. normal.normalize();
  2128. result.normal = normal;
  2129. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2130. return result;
  2131. };
  2132. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2133. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2134. return Vector3.Dot(point, normal) + d;
  2135. };
  2136. return Plane;
  2137. })();
  2138. BABYLON.Plane = Plane;
  2139. var Viewport = (function () {
  2140. function Viewport(x, y, width, height) {
  2141. this.x = x;
  2142. this.y = y;
  2143. this.width = width;
  2144. this.height = height;
  2145. }
  2146. Viewport.prototype.toGlobal = function (engine) {
  2147. var width = engine.getRenderWidth();
  2148. var height = engine.getRenderHeight();
  2149. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2150. };
  2151. return Viewport;
  2152. })();
  2153. BABYLON.Viewport = Viewport;
  2154. var Frustum = (function () {
  2155. function Frustum() {
  2156. }
  2157. Frustum.GetPlanes = function (transform) {
  2158. var frustumPlanes = [];
  2159. for (var index = 0; index < 6; index++) {
  2160. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2161. }
  2162. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2163. return frustumPlanes;
  2164. };
  2165. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2166. // Near
  2167. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2168. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2169. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2170. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2171. frustumPlanes[0].normalize();
  2172. // Far
  2173. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2174. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2175. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2176. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2177. frustumPlanes[1].normalize();
  2178. // Left
  2179. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2180. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2181. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2182. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2183. frustumPlanes[2].normalize();
  2184. // Right
  2185. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2186. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2187. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2188. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2189. frustumPlanes[3].normalize();
  2190. // Top
  2191. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2192. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2193. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2194. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2195. frustumPlanes[4].normalize();
  2196. // Bottom
  2197. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2198. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2199. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2200. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2201. frustumPlanes[5].normalize();
  2202. };
  2203. return Frustum;
  2204. })();
  2205. BABYLON.Frustum = Frustum;
  2206. var Ray = (function () {
  2207. function Ray(origin, direction, length) {
  2208. if (length === void 0) { length = Number.MAX_VALUE; }
  2209. this.origin = origin;
  2210. this.direction = direction;
  2211. this.length = length;
  2212. }
  2213. // Methods
  2214. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2215. var d = 0.0;
  2216. var maxValue = Number.MAX_VALUE;
  2217. if (Math.abs(this.direction.x) < 0.0000001) {
  2218. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2219. return false;
  2220. }
  2221. }
  2222. else {
  2223. var inv = 1.0 / this.direction.x;
  2224. var min = (minimum.x - this.origin.x) * inv;
  2225. var max = (maximum.x - this.origin.x) * inv;
  2226. if (max === -Infinity) {
  2227. max = Infinity;
  2228. }
  2229. if (min > max) {
  2230. var temp = min;
  2231. min = max;
  2232. max = temp;
  2233. }
  2234. d = Math.max(min, d);
  2235. maxValue = Math.min(max, maxValue);
  2236. if (d > maxValue) {
  2237. return false;
  2238. }
  2239. }
  2240. if (Math.abs(this.direction.y) < 0.0000001) {
  2241. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2242. return false;
  2243. }
  2244. }
  2245. else {
  2246. inv = 1.0 / this.direction.y;
  2247. min = (minimum.y - this.origin.y) * inv;
  2248. max = (maximum.y - this.origin.y) * inv;
  2249. if (max === -Infinity) {
  2250. max = Infinity;
  2251. }
  2252. if (min > max) {
  2253. temp = min;
  2254. min = max;
  2255. max = temp;
  2256. }
  2257. d = Math.max(min, d);
  2258. maxValue = Math.min(max, maxValue);
  2259. if (d > maxValue) {
  2260. return false;
  2261. }
  2262. }
  2263. if (Math.abs(this.direction.z) < 0.0000001) {
  2264. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2265. return false;
  2266. }
  2267. }
  2268. else {
  2269. inv = 1.0 / this.direction.z;
  2270. min = (minimum.z - this.origin.z) * inv;
  2271. max = (maximum.z - this.origin.z) * inv;
  2272. if (max === -Infinity) {
  2273. max = Infinity;
  2274. }
  2275. if (min > max) {
  2276. temp = min;
  2277. min = max;
  2278. max = temp;
  2279. }
  2280. d = Math.max(min, d);
  2281. maxValue = Math.min(max, maxValue);
  2282. if (d > maxValue) {
  2283. return false;
  2284. }
  2285. }
  2286. return true;
  2287. };
  2288. Ray.prototype.intersectsBox = function (box) {
  2289. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2290. };
  2291. Ray.prototype.intersectsSphere = function (sphere) {
  2292. var x = sphere.center.x - this.origin.x;
  2293. var y = sphere.center.y - this.origin.y;
  2294. var z = sphere.center.z - this.origin.z;
  2295. var pyth = (x * x) + (y * y) + (z * z);
  2296. var rr = sphere.radius * sphere.radius;
  2297. if (pyth <= rr) {
  2298. return true;
  2299. }
  2300. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2301. if (dot < 0.0) {
  2302. return false;
  2303. }
  2304. var temp = pyth - (dot * dot);
  2305. return temp <= rr;
  2306. };
  2307. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2308. if (!this._edge1) {
  2309. this._edge1 = Vector3.Zero();
  2310. this._edge2 = Vector3.Zero();
  2311. this._pvec = Vector3.Zero();
  2312. this._tvec = Vector3.Zero();
  2313. this._qvec = Vector3.Zero();
  2314. }
  2315. vertex1.subtractToRef(vertex0, this._edge1);
  2316. vertex2.subtractToRef(vertex0, this._edge2);
  2317. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2318. var det = Vector3.Dot(this._edge1, this._pvec);
  2319. if (det === 0) {
  2320. return null;
  2321. }
  2322. var invdet = 1 / det;
  2323. this.origin.subtractToRef(vertex0, this._tvec);
  2324. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2325. if (bu < 0 || bu > 1.0) {
  2326. return null;
  2327. }
  2328. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2329. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2330. if (bv < 0 || bu + bv > 1.0) {
  2331. return null;
  2332. }
  2333. //check if the distance is longer than the predefined length.
  2334. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2335. if (distance > this.length) {
  2336. return null;
  2337. }
  2338. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2339. };
  2340. // Statics
  2341. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2342. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2343. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2344. var direction = end.subtract(start);
  2345. direction.normalize();
  2346. return new Ray(start, direction);
  2347. };
  2348. /**
  2349. * 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
  2350. * transformed to the given world matrix.
  2351. * @param origin The origin point
  2352. * @param end The end point
  2353. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2354. */
  2355. Ray.CreateNewFromTo = function (origin, end, world) {
  2356. if (world === void 0) { world = Matrix.Identity(); }
  2357. var direction = end.subtract(origin);
  2358. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2359. direction.normalize();
  2360. return Ray.Transform(new Ray(origin, direction, length), world);
  2361. };
  2362. Ray.Transform = function (ray, matrix) {
  2363. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2364. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2365. return new Ray(newOrigin, newDirection, ray.length);
  2366. };
  2367. return Ray;
  2368. })();
  2369. BABYLON.Ray = Ray;
  2370. (function (Space) {
  2371. Space[Space["LOCAL"] = 0] = "LOCAL";
  2372. Space[Space["WORLD"] = 1] = "WORLD";
  2373. })(BABYLON.Space || (BABYLON.Space = {}));
  2374. var Space = BABYLON.Space;
  2375. var Axis = (function () {
  2376. function Axis() {
  2377. }
  2378. Axis.X = new Vector3(1, 0, 0);
  2379. Axis.Y = new Vector3(0, 1, 0);
  2380. Axis.Z = new Vector3(0, 0, 1);
  2381. return Axis;
  2382. })();
  2383. BABYLON.Axis = Axis;
  2384. ;
  2385. var BezierCurve = (function () {
  2386. function BezierCurve() {
  2387. }
  2388. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2389. // Extract X (which is equal to time here)
  2390. var f0 = 1 - 3 * x2 + 3 * x1;
  2391. var f1 = 3 * x2 - 6 * x1;
  2392. var f2 = 3 * x1;
  2393. var refinedT = t;
  2394. for (var i = 0; i < 5; i++) {
  2395. var refinedT2 = refinedT * refinedT;
  2396. var refinedT3 = refinedT2 * refinedT;
  2397. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2398. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2399. refinedT -= (x - t) * slope;
  2400. refinedT = Math.min(1, Math.max(0, refinedT));
  2401. }
  2402. // Resolve cubic bezier for the given x
  2403. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2404. };
  2405. return BezierCurve;
  2406. })();
  2407. BABYLON.BezierCurve = BezierCurve;
  2408. (function (Orientation) {
  2409. Orientation[Orientation["CW"] = 0] = "CW";
  2410. Orientation[Orientation["CCW"] = 1] = "CCW";
  2411. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2412. var Orientation = BABYLON.Orientation;
  2413. var Angle = (function () {
  2414. function Angle(radians) {
  2415. var _this = this;
  2416. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2417. this.radians = function () { return _this._radians; };
  2418. this._radians = radians;
  2419. if (this._radians < 0)
  2420. this._radians += (2 * Math.PI);
  2421. }
  2422. Angle.BetweenTwoPoints = function (a, b) {
  2423. var delta = b.subtract(a);
  2424. var theta = Math.atan2(delta.y, delta.x);
  2425. return new Angle(theta);
  2426. };
  2427. Angle.FromRadians = function (radians) {
  2428. return new Angle(radians);
  2429. };
  2430. Angle.FromDegrees = function (degrees) {
  2431. return new Angle(degrees * Math.PI / 180);
  2432. };
  2433. return Angle;
  2434. })();
  2435. BABYLON.Angle = Angle;
  2436. var Arc2 = (function () {
  2437. function Arc2(startPoint, midPoint, endPoint) {
  2438. this.startPoint = startPoint;
  2439. this.midPoint = midPoint;
  2440. this.endPoint = endPoint;
  2441. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2442. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2443. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2444. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2445. 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);
  2446. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2447. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2448. var a1 = this.startAngle.degrees();
  2449. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2450. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2451. // angles correction
  2452. if (a2 - a1 > +180.0)
  2453. a2 -= 360.0;
  2454. if (a2 - a1 < -180.0)
  2455. a2 += 360.0;
  2456. if (a3 - a2 > +180.0)
  2457. a3 -= 360.0;
  2458. if (a3 - a2 < -180.0)
  2459. a3 += 360.0;
  2460. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2461. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2462. }
  2463. return Arc2;
  2464. })();
  2465. BABYLON.Arc2 = Arc2;
  2466. var PathCursor = (function () {
  2467. function PathCursor(path) {
  2468. this.path = path;
  2469. this._onchange = new Array();
  2470. this.value = 0;
  2471. this.animations = new Array();
  2472. }
  2473. PathCursor.prototype.getPoint = function () {
  2474. var point = this.path.getPointAtLengthPosition(this.value);
  2475. return new Vector3(point.x, 0, point.y);
  2476. };
  2477. PathCursor.prototype.moveAhead = function (step) {
  2478. if (step === void 0) { step = 0.002; }
  2479. this.move(step);
  2480. return this;
  2481. };
  2482. PathCursor.prototype.moveBack = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(-step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.move = function (step) {
  2488. if (Math.abs(step) > 1) {
  2489. throw "step size should be less than 1.";
  2490. }
  2491. this.value += step;
  2492. this.ensureLimits();
  2493. this.raiseOnChange();
  2494. return this;
  2495. };
  2496. PathCursor.prototype.ensureLimits = function () {
  2497. while (this.value > 1) {
  2498. this.value -= 1;
  2499. }
  2500. while (this.value < 0) {
  2501. this.value += 1;
  2502. }
  2503. return this;
  2504. };
  2505. // used by animation engine
  2506. PathCursor.prototype.markAsDirty = function (propertyName) {
  2507. this.ensureLimits();
  2508. this.raiseOnChange();
  2509. return this;
  2510. };
  2511. PathCursor.prototype.raiseOnChange = function () {
  2512. var _this = this;
  2513. this._onchange.forEach(function (f) { return f(_this); });
  2514. return this;
  2515. };
  2516. PathCursor.prototype.onchange = function (f) {
  2517. this._onchange.push(f);
  2518. return this;
  2519. };
  2520. return PathCursor;
  2521. })();
  2522. BABYLON.PathCursor = PathCursor;
  2523. var Path2 = (function () {
  2524. function Path2(x, y) {
  2525. this._points = new Array();
  2526. this._length = 0;
  2527. this.closed = false;
  2528. this._points.push(new Vector2(x, y));
  2529. }
  2530. Path2.prototype.addLineTo = function (x, y) {
  2531. if (closed) {
  2532. BABYLON.Tools.Error("cannot add lines to closed paths");
  2533. return this;
  2534. }
  2535. var newPoint = new Vector2(x, y);
  2536. var previousPoint = this._points[this._points.length - 1];
  2537. this._points.push(newPoint);
  2538. this._length += newPoint.subtract(previousPoint).length();
  2539. return this;
  2540. };
  2541. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2542. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2543. if (closed) {
  2544. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2545. return this;
  2546. }
  2547. var startPoint = this._points[this._points.length - 1];
  2548. var midPoint = new Vector2(midX, midY);
  2549. var endPoint = new Vector2(endX, endY);
  2550. var arc = new Arc2(startPoint, midPoint, endPoint);
  2551. var increment = arc.angle.radians() / numberOfSegments;
  2552. if (arc.orientation === 0 /* CW */)
  2553. increment *= -1;
  2554. var currentAngle = arc.startAngle.radians() + increment;
  2555. for (var i = 0; i < numberOfSegments; i++) {
  2556. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2557. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2558. this.addLineTo(x, y);
  2559. currentAngle += increment;
  2560. }
  2561. return this;
  2562. };
  2563. Path2.prototype.close = function () {
  2564. this.closed = true;
  2565. return this;
  2566. };
  2567. Path2.prototype.length = function () {
  2568. var result = this._length;
  2569. if (!this.closed) {
  2570. var lastPoint = this._points[this._points.length - 1];
  2571. var firstPoint = this._points[0];
  2572. result += (firstPoint.subtract(lastPoint).length());
  2573. }
  2574. return result;
  2575. };
  2576. Path2.prototype.getPoints = function () {
  2577. return this._points;
  2578. };
  2579. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2580. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2581. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2582. return Vector2.Zero();
  2583. }
  2584. var lengthPosition = normalizedLengthPosition * this.length();
  2585. var previousOffset = 0;
  2586. for (var i = 0; i < this._points.length; i++) {
  2587. var j = (i + 1) % this._points.length;
  2588. var a = this._points[i];
  2589. var b = this._points[j];
  2590. var bToA = b.subtract(a);
  2591. var nextOffset = (bToA.length() + previousOffset);
  2592. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2593. var dir = bToA.normalize();
  2594. var localOffset = lengthPosition - previousOffset;
  2595. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2596. }
  2597. previousOffset = nextOffset;
  2598. }
  2599. BABYLON.Tools.Error("internal error");
  2600. return Vector2.Zero();
  2601. };
  2602. Path2.StartingAt = function (x, y) {
  2603. return new Path2(x, y);
  2604. };
  2605. return Path2;
  2606. })();
  2607. BABYLON.Path2 = Path2;
  2608. var Path3D = (function () {
  2609. function Path3D(path, firstNormal) {
  2610. this.path = path;
  2611. this._curve = new Array();
  2612. this._distances = new Array();
  2613. this._tangents = new Array();
  2614. this._normals = new Array();
  2615. this._binormals = new Array();
  2616. for (var p = 0; p < path.length; p++) {
  2617. this._curve[p] = path[p].clone(); // hard copy
  2618. }
  2619. this._compute(firstNormal);
  2620. }
  2621. Path3D.prototype.getCurve = function () {
  2622. return this._curve;
  2623. };
  2624. Path3D.prototype.getTangents = function () {
  2625. return this._tangents;
  2626. };
  2627. Path3D.prototype.getNormals = function () {
  2628. return this._normals;
  2629. };
  2630. Path3D.prototype.getBinormals = function () {
  2631. return this._binormals;
  2632. };
  2633. Path3D.prototype.getDistances = function () {
  2634. return this._distances;
  2635. };
  2636. Path3D.prototype.update = function (path, firstNormal) {
  2637. for (var p = 0; p < path.length; p++) {
  2638. this._curve[p].x = path[p].x;
  2639. this._curve[p].y = path[p].y;
  2640. this._curve[p].z = path[p].z;
  2641. }
  2642. this._compute(firstNormal);
  2643. return this;
  2644. };
  2645. // private function compute() : computes tangents, normals and binormals
  2646. Path3D.prototype._compute = function (firstNormal) {
  2647. var l = this._curve.length;
  2648. // first and last tangents
  2649. this._tangents[0] = this._getFirstNonNullVector(0);
  2650. this._tangents[0].normalize();
  2651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2652. this._tangents[l - 1].normalize();
  2653. // normals and binormals at first point : arbitrary vector with _normalVector()
  2654. var tg0 = this._tangents[0];
  2655. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2656. this._normals[0] = pp0;
  2657. this._normals[0].normalize();
  2658. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2659. this._binormals[0].normalize();
  2660. this._distances[0] = 0;
  2661. // normals and binormals : next points
  2662. var prev; // previous vector (segment)
  2663. var cur; // current vector (segment)
  2664. var curTang; // current tangent
  2665. var prevNorm; // previous normal
  2666. var prevBinor; // previous binormal
  2667. for (var i = 1; i < l; i++) {
  2668. // tangents
  2669. prev = this._getLastNonNullVector(i);
  2670. if (i < l - 1) {
  2671. cur = this._getFirstNonNullVector(i);
  2672. this._tangents[i] = prev.add(cur);
  2673. this._tangents[i].normalize();
  2674. }
  2675. this._distances[i] = this._distances[i - 1] + prev.length();
  2676. // normals and binormals
  2677. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2678. curTang = this._tangents[i];
  2679. prevNorm = this._normals[i - 1];
  2680. prevBinor = this._binormals[i - 1];
  2681. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2682. this._normals[i].normalize();
  2683. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2684. this._binormals[i].normalize();
  2685. }
  2686. };
  2687. // private function getFirstNonNullVector(index)
  2688. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2689. Path3D.prototype._getFirstNonNullVector = function (index) {
  2690. var i = 1;
  2691. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2692. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2693. i++;
  2694. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2695. }
  2696. return nNVector;
  2697. };
  2698. // private function getLastNonNullVector(index)
  2699. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2700. Path3D.prototype._getLastNonNullVector = function (index) {
  2701. var i = 1;
  2702. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2703. while (nLVector.length() == 0 && index > i + 1) {
  2704. i++;
  2705. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2706. }
  2707. return nLVector;
  2708. };
  2709. // private function normalVector(v0, vt, va) :
  2710. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2711. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2712. Path3D.prototype._normalVector = function (v0, vt, va) {
  2713. var normal0;
  2714. if (va === undefined || va === null) {
  2715. var point;
  2716. if (vt.y !== 1) {
  2717. point = new Vector3(0, -1, 0);
  2718. }
  2719. else if (vt.x !== 1) {
  2720. point = new Vector3(1, 0, 0);
  2721. }
  2722. else if (vt.z !== 1) {
  2723. point = new Vector3(0, 0, 1);
  2724. }
  2725. normal0 = Vector3.Cross(vt, point);
  2726. }
  2727. else {
  2728. normal0 = Vector3.Cross(vt, va);
  2729. Vector3.CrossToRef(normal0, vt, normal0);
  2730. }
  2731. normal0.normalize();
  2732. return normal0;
  2733. };
  2734. return Path3D;
  2735. })();
  2736. BABYLON.Path3D = Path3D;
  2737. var Curve3 = (function () {
  2738. function Curve3(points) {
  2739. this._length = 0;
  2740. this._points = points;
  2741. this._length = this._computeLength(points);
  2742. }
  2743. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2744. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2745. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2746. var bez = new Array();
  2747. var equation = function (t, val0, val1, val2) {
  2748. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2749. return res;
  2750. };
  2751. for (var i = 0; i <= nbPoints; i++) {
  2752. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2753. }
  2754. return new Curve3(bez);
  2755. };
  2756. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2757. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2758. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2759. var bez = new Array();
  2760. var equation = function (t, val0, val1, val2, val3) {
  2761. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2762. return res;
  2763. };
  2764. for (var i = 0; i <= nbPoints; i++) {
  2765. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2766. }
  2767. return new Curve3(bez);
  2768. };
  2769. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2770. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2771. var hermite = new Array();
  2772. var step = 1 / nbPoints;
  2773. for (var i = 0; i <= nbPoints; i++) {
  2774. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2775. }
  2776. return new Curve3(hermite);
  2777. };
  2778. Curve3.prototype.getPoints = function () {
  2779. return this._points;
  2780. };
  2781. Curve3.prototype.length = function () {
  2782. return this._length;
  2783. };
  2784. Curve3.prototype.continue = function (curve) {
  2785. var lastPoint = this._points[this._points.length - 1];
  2786. var continuedPoints = this._points.slice();
  2787. var curvePoints = curve.getPoints();
  2788. for (var i = 1; i < curvePoints.length; i++) {
  2789. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2790. }
  2791. var continuedCurve = new Curve3(continuedPoints);
  2792. return continuedCurve;
  2793. };
  2794. Curve3.prototype._computeLength = function (path) {
  2795. var l = 0;
  2796. for (var i = 1; i < path.length; i++) {
  2797. l += (path[i].subtract(path[i - 1])).length();
  2798. }
  2799. return l;
  2800. };
  2801. return Curve3;
  2802. })();
  2803. BABYLON.Curve3 = Curve3;
  2804. // Vertex formats
  2805. var PositionNormalVertex = (function () {
  2806. function PositionNormalVertex(position, normal) {
  2807. if (position === void 0) { position = Vector3.Zero(); }
  2808. if (normal === void 0) { normal = Vector3.Up(); }
  2809. this.position = position;
  2810. this.normal = normal;
  2811. }
  2812. PositionNormalVertex.prototype.clone = function () {
  2813. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2814. };
  2815. return PositionNormalVertex;
  2816. })();
  2817. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2818. var PositionNormalTextureVertex = (function () {
  2819. function PositionNormalTextureVertex(position, normal, uv) {
  2820. if (position === void 0) { position = Vector3.Zero(); }
  2821. if (normal === void 0) { normal = Vector3.Up(); }
  2822. if (uv === void 0) { uv = Vector2.Zero(); }
  2823. this.position = position;
  2824. this.normal = normal;
  2825. this.uv = uv;
  2826. }
  2827. PositionNormalTextureVertex.prototype.clone = function () {
  2828. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2829. };
  2830. return PositionNormalTextureVertex;
  2831. })();
  2832. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2833. // SIMD
  2834. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2835. var previousInvertToRef = Matrix.prototype.invertToRef;
  2836. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2837. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2838. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2839. var SIMDHelper = (function () {
  2840. function SIMDHelper() {
  2841. }
  2842. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2843. get: function () {
  2844. return SIMDHelper._isEnabled;
  2845. },
  2846. enumerable: true,
  2847. configurable: true
  2848. });
  2849. SIMDHelper.DisableSIMD = function () {
  2850. // Replace functions
  2851. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2852. Matrix.prototype.invertToRef = previousInvertToRef;
  2853. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2854. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2855. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2856. SIMDHelper._isEnabled = false;
  2857. };
  2858. SIMDHelper.EnableSIMD = function () {
  2859. if (window.SIMD === undefined) {
  2860. return;
  2861. }
  2862. // Replace functions
  2863. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2864. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2865. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2866. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2867. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2868. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2869. get: function () {
  2870. return this._data[0];
  2871. },
  2872. set: function (value) {
  2873. if (!this._data) {
  2874. this._data = new Float32Array(3);
  2875. }
  2876. this._data[0] = value;
  2877. }
  2878. });
  2879. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2880. get: function () {
  2881. return this._data[1];
  2882. },
  2883. set: function (value) {
  2884. this._data[1] = value;
  2885. }
  2886. });
  2887. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2888. get: function () {
  2889. return this._data[2];
  2890. },
  2891. set: function (value) {
  2892. this._data[2] = value;
  2893. }
  2894. });
  2895. SIMDHelper._isEnabled = true;
  2896. };
  2897. SIMDHelper._isEnabled = false;
  2898. return SIMDHelper;
  2899. })();
  2900. BABYLON.SIMDHelper = SIMDHelper;
  2901. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  2902. SIMDHelper.EnableSIMD();
  2903. }
  2904. })(BABYLON || (BABYLON = {}));
  2905. //# sourceMappingURL=babylon.math.js.map
  2906. var BABYLON;
  2907. (function (BABYLON) {
  2908. var Database = (function () {
  2909. function Database(urlToScene, callbackManifestChecked) {
  2910. // Handling various flavors of prefixed version of IndexedDB
  2911. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2912. this.callbackManifestChecked = callbackManifestChecked;
  2913. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  2914. this.db = null;
  2915. this.enableSceneOffline = false;
  2916. this.enableTexturesOffline = false;
  2917. this.manifestVersionFound = 0;
  2918. this.mustUpdateRessources = false;
  2919. this.hasReachedQuota = false;
  2920. this.checkManifestFile();
  2921. }
  2922. Database.prototype.checkManifestFile = function () {
  2923. var _this = this;
  2924. function noManifestFile() {
  2925. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  2926. that.enableSceneOffline = false;
  2927. that.enableTexturesOffline = false;
  2928. that.callbackManifestChecked(false);
  2929. }
  2930. var that = this;
  2931. var manifestURL = this.currentSceneUrl + ".manifest";
  2932. var xhr = new XMLHttpRequest();
  2933. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2934. xhr.open("GET", manifestURLTimeStamped, true);
  2935. xhr.addEventListener("load", function () {
  2936. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2937. try {
  2938. var manifestFile = JSON.parse(xhr.response);
  2939. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2940. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2941. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2942. _this.manifestVersionFound = manifestFile.version;
  2943. }
  2944. if (_this.callbackManifestChecked) {
  2945. _this.callbackManifestChecked(true);
  2946. }
  2947. }
  2948. catch (ex) {
  2949. noManifestFile();
  2950. }
  2951. }
  2952. else {
  2953. noManifestFile();
  2954. }
  2955. }, false);
  2956. xhr.addEventListener("error", function (event) {
  2957. noManifestFile();
  2958. }, false);
  2959. try {
  2960. xhr.send();
  2961. }
  2962. catch (ex) {
  2963. BABYLON.Tools.Error("Error on XHR send request.");
  2964. that.callbackManifestChecked(false);
  2965. }
  2966. };
  2967. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2968. var _this = this;
  2969. function handleError() {
  2970. that.isSupported = false;
  2971. if (errorCallback)
  2972. errorCallback();
  2973. }
  2974. var that = this;
  2975. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2976. // Your browser doesn't support IndexedDB
  2977. this.isSupported = false;
  2978. if (errorCallback)
  2979. errorCallback();
  2980. }
  2981. else {
  2982. // If the DB hasn't been opened or created yet
  2983. if (!this.db) {
  2984. this.hasReachedQuota = false;
  2985. this.isSupported = true;
  2986. var request = this.idbFactory.open("babylonjs", 1);
  2987. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2988. request.onerror = function (event) {
  2989. handleError();
  2990. };
  2991. // executes when a version change transaction cannot complete due to other active transactions
  2992. request.onblocked = function (event) {
  2993. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2994. handleError();
  2995. };
  2996. // DB has been opened successfully
  2997. request.onsuccess = function (event) {
  2998. _this.db = request.result;
  2999. successCallback();
  3000. };
  3001. // Initialization of the DB. Creating Scenes & Textures stores
  3002. request.onupgradeneeded = function (event) {
  3003. _this.db = (event.target).result;
  3004. try {
  3005. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3006. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3007. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3008. }
  3009. catch (ex) {
  3010. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3011. handleError();
  3012. }
  3013. };
  3014. }
  3015. else {
  3016. if (successCallback)
  3017. successCallback();
  3018. }
  3019. }
  3020. };
  3021. Database.prototype.loadImageFromDB = function (url, image) {
  3022. var _this = this;
  3023. var completeURL = Database.ReturnFullUrlLocation(url);
  3024. var saveAndLoadImage = function () {
  3025. if (!_this.hasReachedQuota && _this.db !== null) {
  3026. // the texture is not yet in the DB, let's try to save it
  3027. _this._saveImageIntoDBAsync(completeURL, image);
  3028. }
  3029. else {
  3030. image.src = url;
  3031. }
  3032. };
  3033. if (!this.mustUpdateRessources) {
  3034. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3035. }
  3036. else {
  3037. saveAndLoadImage();
  3038. }
  3039. };
  3040. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3041. if (this.isSupported && this.db !== null) {
  3042. var texture;
  3043. var transaction = this.db.transaction(["textures"]);
  3044. transaction.onabort = function (event) {
  3045. image.src = url;
  3046. };
  3047. transaction.oncomplete = function (event) {
  3048. var blobTextureURL;
  3049. if (texture) {
  3050. var URL = window.URL || window.webkitURL;
  3051. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3052. image.onerror = function () {
  3053. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3054. image.src = url;
  3055. };
  3056. image.src = blobTextureURL;
  3057. }
  3058. else {
  3059. notInDBCallback();
  3060. }
  3061. };
  3062. var getRequest = transaction.objectStore("textures").get(url);
  3063. getRequest.onsuccess = function (event) {
  3064. texture = (event.target).result;
  3065. };
  3066. getRequest.onerror = function (event) {
  3067. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3068. image.src = url;
  3069. };
  3070. }
  3071. else {
  3072. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3073. image.src = url;
  3074. }
  3075. };
  3076. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3077. var _this = this;
  3078. if (this.isSupported) {
  3079. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3080. var generateBlobUrl = function () {
  3081. var blobTextureURL;
  3082. if (blob) {
  3083. var URL = window.URL || window.webkitURL;
  3084. try {
  3085. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3086. }
  3087. catch (ex) {
  3088. blobTextureURL = URL.createObjectURL(blob);
  3089. }
  3090. }
  3091. image.src = blobTextureURL;
  3092. };
  3093. if (Database.isUASupportingBlobStorage) {
  3094. var xhr = new XMLHttpRequest(), blob;
  3095. xhr.open("GET", url, true);
  3096. xhr.responseType = "blob";
  3097. xhr.addEventListener("load", function () {
  3098. if (xhr.status === 200) {
  3099. // Blob as response (XHR2)
  3100. blob = xhr.response;
  3101. var transaction = _this.db.transaction(["textures"], "readwrite");
  3102. // the transaction could abort because of a QuotaExceededError error
  3103. transaction.onabort = function (event) {
  3104. try {
  3105. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3106. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3107. this.hasReachedQuota = true;
  3108. }
  3109. }
  3110. catch (ex) {
  3111. }
  3112. generateBlobUrl();
  3113. };
  3114. transaction.oncomplete = function (event) {
  3115. generateBlobUrl();
  3116. };
  3117. var newTexture = { textureUrl: url, data: blob };
  3118. try {
  3119. // Put the blob into the dabase
  3120. var addRequest = transaction.objectStore("textures").put(newTexture);
  3121. addRequest.onsuccess = function (event) {
  3122. };
  3123. addRequest.onerror = function (event) {
  3124. generateBlobUrl();
  3125. };
  3126. }
  3127. catch (ex) {
  3128. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3129. if (ex.code === 25) {
  3130. Database.isUASupportingBlobStorage = false;
  3131. }
  3132. image.src = url;
  3133. }
  3134. }
  3135. else {
  3136. image.src = url;
  3137. }
  3138. }, false);
  3139. xhr.addEventListener("error", function (event) {
  3140. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3141. image.src = url;
  3142. }, false);
  3143. xhr.send();
  3144. }
  3145. else {
  3146. image.src = url;
  3147. }
  3148. }
  3149. else {
  3150. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3151. image.src = url;
  3152. }
  3153. };
  3154. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3155. var _this = this;
  3156. var updateVersion = function (event) {
  3157. // the version is not yet in the DB or we need to update it
  3158. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3159. };
  3160. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3161. };
  3162. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3163. var _this = this;
  3164. if (this.isSupported) {
  3165. var version;
  3166. try {
  3167. var transaction = this.db.transaction(["versions"]);
  3168. transaction.oncomplete = function (event) {
  3169. if (version) {
  3170. // If the version in the JSON file is > than the version in DB
  3171. if (_this.manifestVersionFound > version.data) {
  3172. _this.mustUpdateRessources = true;
  3173. updateInDBCallback();
  3174. }
  3175. else {
  3176. callback(version.data);
  3177. }
  3178. }
  3179. else {
  3180. _this.mustUpdateRessources = true;
  3181. updateInDBCallback();
  3182. }
  3183. };
  3184. transaction.onabort = function (event) {
  3185. callback(-1);
  3186. };
  3187. var getRequest = transaction.objectStore("versions").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. version = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3193. callback(-1);
  3194. };
  3195. }
  3196. catch (ex) {
  3197. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3198. callback(-1);
  3199. }
  3200. }
  3201. else {
  3202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3203. callback(-1);
  3204. }
  3205. };
  3206. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3207. var _this = this;
  3208. if (this.isSupported && !this.hasReachedQuota) {
  3209. try {
  3210. // Open a transaction to the database
  3211. var transaction = this.db.transaction(["versions"], "readwrite");
  3212. // the transaction could abort because of a QuotaExceededError error
  3213. transaction.onabort = function (event) {
  3214. try {
  3215. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3216. _this.hasReachedQuota = true;
  3217. }
  3218. }
  3219. catch (ex) {
  3220. }
  3221. callback(-1);
  3222. };
  3223. transaction.oncomplete = function (event) {
  3224. callback(_this.manifestVersionFound);
  3225. };
  3226. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3227. // Put the scene into the database
  3228. var addRequest = transaction.objectStore("versions").put(newVersion);
  3229. addRequest.onsuccess = function (event) {
  3230. };
  3231. addRequest.onerror = function (event) {
  3232. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3233. };
  3234. }
  3235. catch (ex) {
  3236. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3237. callback(-1);
  3238. }
  3239. }
  3240. else {
  3241. callback(-1);
  3242. }
  3243. };
  3244. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3245. var _this = this;
  3246. var completeUrl = Database.ReturnFullUrlLocation(url);
  3247. var saveAndLoadFile = function (event) {
  3248. // the scene is not yet in the DB, let's try to save it
  3249. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3250. };
  3251. this._checkVersionFromDB(completeUrl, function (version) {
  3252. if (version !== -1) {
  3253. if (!_this.mustUpdateRessources) {
  3254. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3255. }
  3256. else {
  3257. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3258. }
  3259. }
  3260. else {
  3261. errorCallback();
  3262. }
  3263. });
  3264. };
  3265. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3266. if (this.isSupported) {
  3267. var targetStore;
  3268. if (url.indexOf(".babylon") !== -1) {
  3269. targetStore = "scenes";
  3270. }
  3271. else {
  3272. targetStore = "textures";
  3273. }
  3274. var file;
  3275. var transaction = this.db.transaction([targetStore]);
  3276. transaction.oncomplete = function (event) {
  3277. if (file) {
  3278. callback(file.data);
  3279. }
  3280. else {
  3281. notInDBCallback();
  3282. }
  3283. };
  3284. transaction.onabort = function (event) {
  3285. notInDBCallback();
  3286. };
  3287. var getRequest = transaction.objectStore(targetStore).get(url);
  3288. getRequest.onsuccess = function (event) {
  3289. file = (event.target).result;
  3290. };
  3291. getRequest.onerror = function (event) {
  3292. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3293. notInDBCallback();
  3294. };
  3295. }
  3296. else {
  3297. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3298. callback();
  3299. }
  3300. };
  3301. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3302. var _this = this;
  3303. if (this.isSupported) {
  3304. var targetStore;
  3305. if (url.indexOf(".babylon") !== -1) {
  3306. targetStore = "scenes";
  3307. }
  3308. else {
  3309. targetStore = "textures";
  3310. }
  3311. // Create XHR
  3312. var xhr = new XMLHttpRequest(), fileData;
  3313. xhr.open("GET", url, true);
  3314. if (useArrayBuffer) {
  3315. xhr.responseType = "arraybuffer";
  3316. }
  3317. xhr.onprogress = progressCallback;
  3318. xhr.addEventListener("load", function () {
  3319. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3320. // Blob as response (XHR2)
  3321. //fileData = xhr.responseText;
  3322. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3323. if (!_this.hasReachedQuota) {
  3324. // Open a transaction to the database
  3325. var transaction = _this.db.transaction([targetStore], "readwrite");
  3326. // the transaction could abort because of a QuotaExceededError error
  3327. transaction.onabort = function (event) {
  3328. try {
  3329. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3330. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3331. this.hasReachedQuota = true;
  3332. }
  3333. }
  3334. catch (ex) {
  3335. }
  3336. callback(fileData);
  3337. };
  3338. transaction.oncomplete = function (event) {
  3339. callback(fileData);
  3340. };
  3341. var newFile;
  3342. if (targetStore === "scenes") {
  3343. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3344. }
  3345. else {
  3346. newFile = { textureUrl: url, data: fileData };
  3347. }
  3348. try {
  3349. // Put the scene into the database
  3350. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3351. addRequest.onsuccess = function (event) {
  3352. };
  3353. addRequest.onerror = function (event) {
  3354. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3355. };
  3356. }
  3357. catch (ex) {
  3358. callback(fileData);
  3359. }
  3360. }
  3361. else {
  3362. callback(fileData);
  3363. }
  3364. }
  3365. else {
  3366. callback();
  3367. }
  3368. }, false);
  3369. xhr.addEventListener("error", function (event) {
  3370. BABYLON.Tools.Error("error on XHR request.");
  3371. callback();
  3372. }, false);
  3373. xhr.send();
  3374. }
  3375. else {
  3376. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3377. callback();
  3378. }
  3379. };
  3380. Database.isUASupportingBlobStorage = true;
  3381. Database.parseURL = function (url) {
  3382. var a = document.createElement('a');
  3383. a.href = url;
  3384. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3385. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3386. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3387. return absLocation;
  3388. };
  3389. Database.ReturnFullUrlLocation = function (url) {
  3390. if (url.indexOf("http:/") === -1) {
  3391. return (BABYLON.Database.parseURL(window.location.href) + url);
  3392. }
  3393. else {
  3394. return url;
  3395. }
  3396. };
  3397. return Database;
  3398. })();
  3399. BABYLON.Database = Database;
  3400. })(BABYLON || (BABYLON = {}));
  3401. //# sourceMappingURL=babylon.database.js.map
  3402. var BABYLON;
  3403. (function (BABYLON) {
  3404. var Internals;
  3405. (function (Internals) {
  3406. /*
  3407. * Based on jsTGALoader - Javascript loader for TGA file
  3408. * By Vincent Thibault
  3409. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3410. */
  3411. var TGATools = (function () {
  3412. function TGATools() {
  3413. }
  3414. TGATools.GetTGAHeader = function (data) {
  3415. var offset = 0;
  3416. var header = {
  3417. id_length: data[offset++],
  3418. colormap_type: data[offset++],
  3419. image_type: data[offset++],
  3420. colormap_index: data[offset++] | data[offset++] << 8,
  3421. colormap_length: data[offset++] | data[offset++] << 8,
  3422. colormap_size: data[offset++],
  3423. origin: [
  3424. data[offset++] | data[offset++] << 8,
  3425. data[offset++] | data[offset++] << 8
  3426. ],
  3427. width: data[offset++] | data[offset++] << 8,
  3428. height: data[offset++] | data[offset++] << 8,
  3429. pixel_size: data[offset++],
  3430. flags: data[offset++]
  3431. };
  3432. return header;
  3433. };
  3434. TGATools.UploadContent = function (gl, data) {
  3435. // Not enough data to contain header ?
  3436. if (data.length < 19) {
  3437. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3438. return;
  3439. }
  3440. // Read Header
  3441. var offset = 18;
  3442. var header = TGATools.GetTGAHeader(data);
  3443. // Assume it's a valid Targa file.
  3444. if (header.id_length + offset > data.length) {
  3445. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3446. return;
  3447. }
  3448. // Skip not needed data
  3449. offset += header.id_length;
  3450. var use_rle = false;
  3451. var use_pal = false;
  3452. var use_rgb = false;
  3453. var use_grey = false;
  3454. switch (header.image_type) {
  3455. case TGATools._TYPE_RLE_INDEXED:
  3456. use_rle = true;
  3457. case TGATools._TYPE_INDEXED:
  3458. use_pal = true;
  3459. break;
  3460. case TGATools._TYPE_RLE_RGB:
  3461. use_rle = true;
  3462. case TGATools._TYPE_RGB:
  3463. use_rgb = true;
  3464. break;
  3465. case TGATools._TYPE_RLE_GREY:
  3466. use_rle = true;
  3467. case TGATools._TYPE_GREY:
  3468. use_grey = true;
  3469. break;
  3470. }
  3471. var pixel_data;
  3472. var numAlphaBits = header.flags & 0xf;
  3473. var pixel_size = header.pixel_size >> 3;
  3474. var pixel_total = header.width * header.height * pixel_size;
  3475. // Read palettes
  3476. var palettes;
  3477. if (use_pal) {
  3478. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3479. }
  3480. // Read LRE
  3481. if (use_rle) {
  3482. pixel_data = new Uint8Array(pixel_total);
  3483. var c, count, i;
  3484. var localOffset = 0;
  3485. var pixels = new Uint8Array(pixel_size);
  3486. while (offset < pixel_total && localOffset < pixel_total) {
  3487. c = data[offset++];
  3488. count = (c & 0x7f) + 1;
  3489. // RLE pixels
  3490. if (c & 0x80) {
  3491. for (i = 0; i < pixel_size; ++i) {
  3492. pixels[i] = data[offset++];
  3493. }
  3494. for (i = 0; i < count; ++i) {
  3495. pixel_data.set(pixels, localOffset + i * pixel_size);
  3496. }
  3497. localOffset += pixel_size * count;
  3498. }
  3499. else {
  3500. count *= pixel_size;
  3501. for (i = 0; i < count; ++i) {
  3502. pixel_data[localOffset + i] = data[offset++];
  3503. }
  3504. localOffset += count;
  3505. }
  3506. }
  3507. }
  3508. else {
  3509. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3510. }
  3511. // Load to texture
  3512. var x_start, y_start, x_step, y_step, y_end, x_end;
  3513. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3514. default:
  3515. case TGATools._ORIGIN_UL:
  3516. x_start = 0;
  3517. x_step = 1;
  3518. x_end = header.width;
  3519. y_start = 0;
  3520. y_step = 1;
  3521. y_end = header.height;
  3522. break;
  3523. case TGATools._ORIGIN_BL:
  3524. x_start = 0;
  3525. x_step = 1;
  3526. x_end = header.width;
  3527. y_start = header.height - 1;
  3528. y_step = -1;
  3529. y_end = -1;
  3530. break;
  3531. case TGATools._ORIGIN_UR:
  3532. x_start = header.width - 1;
  3533. x_step = -1;
  3534. x_end = -1;
  3535. y_start = 0;
  3536. y_step = 1;
  3537. y_end = header.height;
  3538. break;
  3539. case TGATools._ORIGIN_BR:
  3540. x_start = header.width - 1;
  3541. x_step = -1;
  3542. x_end = -1;
  3543. y_start = header.height - 1;
  3544. y_step = -1;
  3545. y_end = -1;
  3546. break;
  3547. }
  3548. // Load the specify method
  3549. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3550. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3551. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3552. };
  3553. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3554. var image = pixel_data, colormap = palettes;
  3555. var width = header.width, height = header.height;
  3556. var color, i = 0, x, y;
  3557. var imageData = new Uint8Array(width * height * 4);
  3558. for (y = y_start; y !== y_end; y += y_step) {
  3559. for (x = x_start; x !== x_end; x += x_step, i++) {
  3560. color = image[i];
  3561. imageData[(x + width * y) * 4 + 3] = 255;
  3562. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3563. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3564. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3565. }
  3566. }
  3567. return imageData;
  3568. };
  3569. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3570. var image = pixel_data;
  3571. var width = header.width, height = header.height;
  3572. var color, i = 0, x, y;
  3573. var imageData = new Uint8Array(width * height * 4);
  3574. for (y = y_start; y !== y_end; y += y_step) {
  3575. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3576. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3577. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3578. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3579. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3580. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3581. }
  3582. }
  3583. return imageData;
  3584. };
  3585. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3586. var image = pixel_data;
  3587. var width = header.width, height = header.height;
  3588. var i = 0, x, y;
  3589. var imageData = new Uint8Array(width * height * 4);
  3590. for (y = y_start; y !== y_end; y += y_step) {
  3591. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3592. imageData[(x + width * y) * 4 + 3] = 255;
  3593. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3594. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3595. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3596. }
  3597. }
  3598. return imageData;
  3599. };
  3600. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3601. var image = pixel_data;
  3602. var width = header.width, height = header.height;
  3603. var i = 0, x, y;
  3604. var imageData = new Uint8Array(width * height * 4);
  3605. for (y = y_start; y !== y_end; y += y_step) {
  3606. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3607. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3608. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3609. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3610. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3611. }
  3612. }
  3613. return imageData;
  3614. };
  3615. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3616. var image = pixel_data;
  3617. var width = header.width, height = header.height;
  3618. var color, i = 0, x, y;
  3619. var imageData = new Uint8Array(width * height * 4);
  3620. for (y = y_start; y !== y_end; y += y_step) {
  3621. for (x = x_start; x !== x_end; x += x_step, i++) {
  3622. color = image[i];
  3623. imageData[(x + width * y) * 4 + 0] = color;
  3624. imageData[(x + width * y) * 4 + 1] = color;
  3625. imageData[(x + width * y) * 4 + 2] = color;
  3626. imageData[(x + width * y) * 4 + 3] = 255;
  3627. }
  3628. }
  3629. return imageData;
  3630. };
  3631. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3632. var image = pixel_data;
  3633. var width = header.width, height = header.height;
  3634. var i = 0, x, y;
  3635. var imageData = new Uint8Array(width * height * 4);
  3636. for (y = y_start; y !== y_end; y += y_step) {
  3637. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3638. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3639. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3640. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3641. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3642. }
  3643. }
  3644. return imageData;
  3645. };
  3646. TGATools._TYPE_NO_DATA = 0;
  3647. TGATools._TYPE_INDEXED = 1;
  3648. TGATools._TYPE_RGB = 2;
  3649. TGATools._TYPE_GREY = 3;
  3650. TGATools._TYPE_RLE_INDEXED = 9;
  3651. TGATools._TYPE_RLE_RGB = 10;
  3652. TGATools._TYPE_RLE_GREY = 11;
  3653. TGATools._ORIGIN_MASK = 0x30;
  3654. TGATools._ORIGIN_SHIFT = 0x04;
  3655. TGATools._ORIGIN_BL = 0x00;
  3656. TGATools._ORIGIN_BR = 0x01;
  3657. TGATools._ORIGIN_UL = 0x02;
  3658. TGATools._ORIGIN_UR = 0x03;
  3659. return TGATools;
  3660. })();
  3661. Internals.TGATools = TGATools;
  3662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3663. })(BABYLON || (BABYLON = {}));
  3664. //# sourceMappingURL=babylon.tools.tga.js.map
  3665. var BABYLON;
  3666. (function (BABYLON) {
  3667. var Internals;
  3668. (function (Internals) {
  3669. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3670. // All values and structures referenced from:
  3671. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3672. var DDS_MAGIC = 0x20534444;
  3673. 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;
  3674. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3675. 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;
  3676. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3677. function FourCCToInt32(value) {
  3678. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  3679. }
  3680. function Int32ToFourCC(value) {
  3681. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3682. }
  3683. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3684. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3685. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3686. var headerLengthInt = 31; // The header length in 32 bit ints
  3687. // Offsets into the header array
  3688. var off_magic = 0;
  3689. var off_size = 1;
  3690. var off_flags = 2;
  3691. var off_height = 3;
  3692. var off_width = 4;
  3693. var off_mipmapCount = 7;
  3694. var off_pfFlags = 20;
  3695. var off_pfFourCC = 21;
  3696. var off_RGBbpp = 22;
  3697. var off_RMask = 23;
  3698. var off_GMask = 24;
  3699. var off_BMask = 25;
  3700. var off_AMask = 26;
  3701. var off_caps1 = 27;
  3702. var off_caps2 = 28;
  3703. ;
  3704. var DDSTools = (function () {
  3705. function DDSTools() {
  3706. }
  3707. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3708. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3709. var mipmapCount = 1;
  3710. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3711. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3712. }
  3713. return {
  3714. width: header[off_width],
  3715. height: header[off_height],
  3716. mipmapCount: mipmapCount,
  3717. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3718. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3719. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3720. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3721. };
  3722. };
  3723. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3724. var byteArray = new Uint8Array(dataLength);
  3725. var srcData = new Uint8Array(arrayBuffer);
  3726. var index = 0;
  3727. for (var y = height - 1; y >= 0; y--) {
  3728. for (var x = 0; x < width; x++) {
  3729. var srcPos = dataOffset + (x + y * width) * 4;
  3730. byteArray[index + 2] = srcData[srcPos];
  3731. byteArray[index + 1] = srcData[srcPos + 1];
  3732. byteArray[index] = srcData[srcPos + 2];
  3733. byteArray[index + 3] = srcData[srcPos + 3];
  3734. index += 4;
  3735. }
  3736. }
  3737. return byteArray;
  3738. };
  3739. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3740. var byteArray = new Uint8Array(dataLength);
  3741. var srcData = new Uint8Array(arrayBuffer);
  3742. var index = 0;
  3743. for (var y = height - 1; y >= 0; y--) {
  3744. for (var x = 0; x < width; x++) {
  3745. var srcPos = dataOffset + (x + y * width) * 3;
  3746. byteArray[index + 2] = srcData[srcPos];
  3747. byteArray[index + 1] = srcData[srcPos + 1];
  3748. byteArray[index] = srcData[srcPos + 2];
  3749. index += 3;
  3750. }
  3751. }
  3752. return byteArray;
  3753. };
  3754. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3755. var byteArray = new Uint8Array(dataLength);
  3756. var srcData = new Uint8Array(arrayBuffer);
  3757. var index = 0;
  3758. for (var y = height - 1; y >= 0; y--) {
  3759. for (var x = 0; x < width; x++) {
  3760. var srcPos = dataOffset + (x + y * width);
  3761. byteArray[index] = srcData[srcPos];
  3762. index++;
  3763. }
  3764. }
  3765. return byteArray;
  3766. };
  3767. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3768. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3769. if (header[off_magic] != DDS_MAGIC) {
  3770. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3771. return;
  3772. }
  3773. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3774. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3775. return;
  3776. }
  3777. if (info.isFourCC) {
  3778. fourCC = header[off_pfFourCC];
  3779. switch (fourCC) {
  3780. case FOURCC_DXT1:
  3781. blockBytes = 8;
  3782. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3783. break;
  3784. case FOURCC_DXT3:
  3785. blockBytes = 16;
  3786. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3787. break;
  3788. case FOURCC_DXT5:
  3789. blockBytes = 16;
  3790. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3791. break;
  3792. default:
  3793. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3794. return;
  3795. }
  3796. }
  3797. mipmapCount = 1;
  3798. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3799. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3800. }
  3801. var bpp = header[off_RGBbpp];
  3802. for (var face = 0; face < faces; face++) {
  3803. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3804. width = header[off_width];
  3805. height = header[off_height];
  3806. dataOffset = header[off_size] + 4;
  3807. for (i = 0; i < mipmapCount; ++i) {
  3808. if (info.isRGB) {
  3809. if (bpp == 24) {
  3810. dataLength = width * height * 3;
  3811. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3812. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3813. }
  3814. else {
  3815. dataLength = width * height * 4;
  3816. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3817. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3818. }
  3819. }
  3820. else if (info.isLuminance) {
  3821. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3822. var unpaddedRowSize = width;
  3823. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3824. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3825. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3826. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3827. }
  3828. else {
  3829. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3830. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3831. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3832. }
  3833. dataOffset += dataLength;
  3834. width *= 0.5;
  3835. height *= 0.5;
  3836. width = Math.max(1.0, width);
  3837. height = Math.max(1.0, height);
  3838. }
  3839. }
  3840. };
  3841. return DDSTools;
  3842. })();
  3843. Internals.DDSTools = DDSTools;
  3844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3845. })(BABYLON || (BABYLON = {}));
  3846. //# sourceMappingURL=babylon.tools.dds.js.map
  3847. var BABYLON;
  3848. (function (BABYLON) {
  3849. var SmartArray = (function () {
  3850. function SmartArray(capacity) {
  3851. this.length = 0;
  3852. this._duplicateId = 0;
  3853. this.data = new Array(capacity);
  3854. this._id = SmartArray._GlobalId++;
  3855. }
  3856. SmartArray.prototype.push = function (value) {
  3857. this.data[this.length++] = value;
  3858. if (this.length > this.data.length) {
  3859. this.data.length *= 2;
  3860. }
  3861. if (!value.__smartArrayFlags) {
  3862. value.__smartArrayFlags = {};
  3863. }
  3864. value.__smartArrayFlags[this._id] = this._duplicateId;
  3865. };
  3866. SmartArray.prototype.pushNoDuplicate = function (value) {
  3867. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3868. return;
  3869. }
  3870. this.push(value);
  3871. };
  3872. SmartArray.prototype.sort = function (compareFn) {
  3873. this.data.sort(compareFn);
  3874. };
  3875. SmartArray.prototype.reset = function () {
  3876. this.length = 0;
  3877. this._duplicateId++;
  3878. };
  3879. SmartArray.prototype.concat = function (array) {
  3880. if (array.length === 0) {
  3881. return;
  3882. }
  3883. if (this.length + array.length > this.data.length) {
  3884. this.data.length = (this.length + array.length) * 2;
  3885. }
  3886. for (var index = 0; index < array.length; index++) {
  3887. this.data[this.length++] = (array.data || array)[index];
  3888. }
  3889. };
  3890. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3891. if (array.length === 0) {
  3892. return;
  3893. }
  3894. if (this.length + array.length > this.data.length) {
  3895. this.data.length = (this.length + array.length) * 2;
  3896. }
  3897. for (var index = 0; index < array.length; index++) {
  3898. var item = (array.data || array)[index];
  3899. this.pushNoDuplicate(item);
  3900. }
  3901. };
  3902. SmartArray.prototype.indexOf = function (value) {
  3903. var position = this.data.indexOf(value);
  3904. if (position >= this.length) {
  3905. return -1;
  3906. }
  3907. return position;
  3908. };
  3909. // Statics
  3910. SmartArray._GlobalId = 0;
  3911. return SmartArray;
  3912. })();
  3913. BABYLON.SmartArray = SmartArray;
  3914. })(BABYLON || (BABYLON = {}));
  3915. //# sourceMappingURL=babylon.smartArray.js.map
  3916. var BABYLON;
  3917. (function (BABYLON) {
  3918. var SmartCollection = (function () {
  3919. function SmartCollection(capacity) {
  3920. if (capacity === void 0) { capacity = 10; }
  3921. this.count = 0;
  3922. this._initialCapacity = capacity;
  3923. this.items = {};
  3924. this._keys = new Array(this._initialCapacity);
  3925. }
  3926. SmartCollection.prototype.add = function (key, item) {
  3927. if (this.items[key] != undefined) {
  3928. return -1;
  3929. }
  3930. this.items[key] = item;
  3931. //literal keys are always strings, but we keep source type of key in _keys array
  3932. this._keys[this.count++] = key;
  3933. if (this.count > this._keys.length) {
  3934. this._keys.length *= 2;
  3935. }
  3936. return this.count;
  3937. };
  3938. SmartCollection.prototype.remove = function (key) {
  3939. if (this.items[key] == undefined) {
  3940. return -1;
  3941. }
  3942. return this.removeItemOfIndex(this.indexOf(key));
  3943. };
  3944. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3945. if (index < this.count && index > -1) {
  3946. delete this.items[this._keys[index]];
  3947. while (index < this.count) {
  3948. this._keys[index] = this._keys[index + 1];
  3949. index++;
  3950. }
  3951. }
  3952. else {
  3953. return -1;
  3954. }
  3955. return --this.count;
  3956. };
  3957. SmartCollection.prototype.indexOf = function (key) {
  3958. for (var i = 0; i !== this.count; i++) {
  3959. if (this._keys[i] === key) {
  3960. return i;
  3961. }
  3962. }
  3963. return -1;
  3964. };
  3965. SmartCollection.prototype.item = function (key) {
  3966. return this.items[key];
  3967. };
  3968. SmartCollection.prototype.getAllKeys = function () {
  3969. if (this.count > 0) {
  3970. var keys = new Array(this.count);
  3971. for (var i = 0; i < this.count; i++) {
  3972. keys[i] = this._keys[i];
  3973. }
  3974. return keys;
  3975. }
  3976. else {
  3977. return undefined;
  3978. }
  3979. };
  3980. SmartCollection.prototype.getKeyByIndex = function (index) {
  3981. if (index < this.count && index > -1) {
  3982. return this._keys[index];
  3983. }
  3984. else {
  3985. return undefined;
  3986. }
  3987. };
  3988. SmartCollection.prototype.getItemByIndex = function (index) {
  3989. if (index < this.count && index > -1) {
  3990. return this.items[this._keys[index]];
  3991. }
  3992. else {
  3993. return undefined;
  3994. }
  3995. };
  3996. SmartCollection.prototype.empty = function () {
  3997. if (this.count > 0) {
  3998. this.count = 0;
  3999. this.items = {};
  4000. this._keys = new Array(this._initialCapacity);
  4001. }
  4002. };
  4003. SmartCollection.prototype.forEach = function (block) {
  4004. var key;
  4005. for (key in this.items) {
  4006. if (this.items.hasOwnProperty(key)) {
  4007. block(this.items[key]);
  4008. }
  4009. }
  4010. };
  4011. return SmartCollection;
  4012. })();
  4013. BABYLON.SmartCollection = SmartCollection;
  4014. })(BABYLON || (BABYLON = {}));
  4015. //# sourceMappingURL=babylon.smartCollection.js.map
  4016. var BABYLON;
  4017. (function (BABYLON) {
  4018. // Screenshots
  4019. var screenshotCanvas;
  4020. var cloneValue = function (source, destinationObject) {
  4021. if (!source)
  4022. return null;
  4023. if (source instanceof BABYLON.Mesh) {
  4024. return null;
  4025. }
  4026. if (source instanceof BABYLON.SubMesh) {
  4027. return source.clone(destinationObject);
  4028. }
  4029. else if (source.clone) {
  4030. return source.clone();
  4031. }
  4032. return null;
  4033. };
  4034. var Tools = (function () {
  4035. function Tools() {
  4036. }
  4037. Tools.SetImmediate = function (action) {
  4038. if (window.setImmediate) {
  4039. window.setImmediate(action);
  4040. }
  4041. else {
  4042. setTimeout(action, 1);
  4043. }
  4044. };
  4045. Tools.GetFilename = function (path) {
  4046. var index = path.lastIndexOf("/");
  4047. if (index < 0)
  4048. return path;
  4049. return path.substring(index + 1);
  4050. };
  4051. Tools.GetDOMTextContent = function (element) {
  4052. var result = "";
  4053. var child = element.firstChild;
  4054. while (child) {
  4055. if (child.nodeType === 3) {
  4056. result += child.textContent;
  4057. }
  4058. child = child.nextSibling;
  4059. }
  4060. return result;
  4061. };
  4062. Tools.ToDegrees = function (angle) {
  4063. return angle * 180 / Math.PI;
  4064. };
  4065. Tools.ToRadians = function (angle) {
  4066. return angle * Math.PI / 180;
  4067. };
  4068. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4069. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4070. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4071. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4072. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4073. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4074. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4075. }
  4076. return {
  4077. minimum: minimum,
  4078. maximum: maximum
  4079. };
  4080. };
  4081. Tools.ExtractMinAndMax = function (positions, start, count) {
  4082. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4083. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4084. for (var index = start; index < start + count; index++) {
  4085. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4086. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4087. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4088. }
  4089. return {
  4090. minimum: minimum,
  4091. maximum: maximum
  4092. };
  4093. };
  4094. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4095. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4096. return undefined;
  4097. return Array.isArray(obj) ? obj : [obj];
  4098. };
  4099. // Misc.
  4100. Tools.GetPointerPrefix = function () {
  4101. var eventPrefix = "pointer";
  4102. // Check if hand.js is referenced or if the browser natively supports pointer events
  4103. if (!navigator.pointerEnabled) {
  4104. eventPrefix = "mouse";
  4105. }
  4106. return eventPrefix;
  4107. };
  4108. Tools.QueueNewFrame = function (func) {
  4109. if (window.requestAnimationFrame)
  4110. window.requestAnimationFrame(func);
  4111. else if (window.msRequestAnimationFrame)
  4112. window.msRequestAnimationFrame(func);
  4113. else if (window.webkitRequestAnimationFrame)
  4114. window.webkitRequestAnimationFrame(func);
  4115. else if (window.mozRequestAnimationFrame)
  4116. window.mozRequestAnimationFrame(func);
  4117. else if (window.oRequestAnimationFrame)
  4118. window.oRequestAnimationFrame(func);
  4119. else {
  4120. window.setTimeout(func, 16);
  4121. }
  4122. };
  4123. Tools.RequestFullscreen = function (element) {
  4124. if (element.requestFullscreen)
  4125. element.requestFullscreen();
  4126. else if (element.msRequestFullscreen)
  4127. element.msRequestFullscreen();
  4128. else if (element.webkitRequestFullscreen)
  4129. element.webkitRequestFullscreen();
  4130. else if (element.mozRequestFullScreen)
  4131. element.mozRequestFullScreen();
  4132. };
  4133. Tools.ExitFullscreen = function () {
  4134. if (document.exitFullscreen) {
  4135. document.exitFullscreen();
  4136. }
  4137. else if (document.mozCancelFullScreen) {
  4138. document.mozCancelFullScreen();
  4139. }
  4140. else if (document.webkitCancelFullScreen) {
  4141. document.webkitCancelFullScreen();
  4142. }
  4143. else if (document.msCancelFullScreen) {
  4144. document.msCancelFullScreen();
  4145. }
  4146. };
  4147. // External files
  4148. Tools.CleanUrl = function (url) {
  4149. url = url.replace(/#/mg, "%23");
  4150. return url;
  4151. };
  4152. Tools.LoadImage = function (url, onload, onerror, database) {
  4153. url = Tools.CleanUrl(url);
  4154. var img = new Image();
  4155. if (url.substr(0, 5) !== "data:")
  4156. img.crossOrigin = 'anonymous';
  4157. img.onload = function () {
  4158. onload(img);
  4159. };
  4160. img.onerror = function (err) {
  4161. onerror(img, err);
  4162. };
  4163. var noIndexedDB = function () {
  4164. img.src = url;
  4165. };
  4166. var loadFromIndexedDB = function () {
  4167. database.loadImageFromDB(url, img);
  4168. };
  4169. //ANY database to do!
  4170. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4171. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4172. }
  4173. else {
  4174. if (url.indexOf("file:") === -1) {
  4175. noIndexedDB();
  4176. }
  4177. else {
  4178. try {
  4179. var textureName = url.substring(5);
  4180. var blobURL;
  4181. try {
  4182. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4183. }
  4184. catch (ex) {
  4185. // Chrome doesn't support oneTimeOnly parameter
  4186. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4187. }
  4188. img.src = blobURL;
  4189. }
  4190. catch (e) {
  4191. Tools.Log("Error while trying to load texture: " + textureName);
  4192. img.src = null;
  4193. }
  4194. }
  4195. }
  4196. return img;
  4197. };
  4198. //ANY
  4199. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4200. url = Tools.CleanUrl(url);
  4201. var noIndexedDB = function () {
  4202. var request = new XMLHttpRequest();
  4203. var loadUrl = Tools.BaseUrl + url;
  4204. request.open('GET', loadUrl, true);
  4205. if (useArrayBuffer) {
  4206. request.responseType = "arraybuffer";
  4207. }
  4208. request.onprogress = progressCallBack;
  4209. request.onreadystatechange = function () {
  4210. if (request.readyState === 4) {
  4211. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4212. callback(!useArrayBuffer ? request.responseText : request.response);
  4213. }
  4214. else {
  4215. if (onError) {
  4216. onError();
  4217. }
  4218. else {
  4219. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4220. }
  4221. }
  4222. }
  4223. };
  4224. request.send(null);
  4225. };
  4226. var loadFromIndexedDB = function () {
  4227. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4228. };
  4229. if (url.indexOf("file:") !== -1) {
  4230. var fileName = url.substring(5);
  4231. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4232. }
  4233. else {
  4234. // Caching all files
  4235. if (database && database.enableSceneOffline) {
  4236. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4237. }
  4238. else {
  4239. noIndexedDB();
  4240. }
  4241. }
  4242. };
  4243. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4244. var reader = new FileReader();
  4245. reader.onload = function (e) {
  4246. //target doesn't have result from ts 1.3
  4247. callback(e.target['result']);
  4248. };
  4249. reader.onprogress = progressCallback;
  4250. reader.readAsDataURL(fileToLoad);
  4251. };
  4252. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4253. var reader = new FileReader();
  4254. reader.onerror = function (e) {
  4255. Tools.Log("Error while reading file: " + fileToLoad.name);
  4256. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4257. };
  4258. reader.onload = function (e) {
  4259. //target doesn't have result from ts 1.3
  4260. callback(e.target['result']);
  4261. };
  4262. reader.onprogress = progressCallBack;
  4263. if (!useArrayBuffer) {
  4264. // Asynchronous read
  4265. reader.readAsText(fileToLoad);
  4266. }
  4267. else {
  4268. reader.readAsArrayBuffer(fileToLoad);
  4269. }
  4270. };
  4271. // Misc.
  4272. Tools.Clamp = function (value, min, max) {
  4273. if (min === void 0) { min = 0; }
  4274. if (max === void 0) { max = 1; }
  4275. return Math.min(max, Math.max(min, value));
  4276. };
  4277. // Returns -1 when value is a negative number and
  4278. // +1 when value is a positive number.
  4279. Tools.Sign = function (value) {
  4280. value = +value; // convert to a number
  4281. if (value === 0 || isNaN(value))
  4282. return value;
  4283. return value > 0 ? 1 : -1;
  4284. };
  4285. Tools.Format = function (value, decimals) {
  4286. if (decimals === void 0) { decimals = 2; }
  4287. return value.toFixed(decimals);
  4288. };
  4289. Tools.CheckExtends = function (v, min, max) {
  4290. if (v.x < min.x)
  4291. min.x = v.x;
  4292. if (v.y < min.y)
  4293. min.y = v.y;
  4294. if (v.z < min.z)
  4295. min.z = v.z;
  4296. if (v.x > max.x)
  4297. max.x = v.x;
  4298. if (v.y > max.y)
  4299. max.y = v.y;
  4300. if (v.z > max.z)
  4301. max.z = v.z;
  4302. };
  4303. Tools.WithinEpsilon = function (a, b, epsilon) {
  4304. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4305. var num = a - b;
  4306. return -epsilon <= num && num <= epsilon;
  4307. };
  4308. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4309. for (var prop in source) {
  4310. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4311. continue;
  4312. }
  4313. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4314. continue;
  4315. }
  4316. var sourceValue = source[prop];
  4317. var typeOfSourceValue = typeof sourceValue;
  4318. if (typeOfSourceValue === "function") {
  4319. continue;
  4320. }
  4321. if (typeOfSourceValue === "object") {
  4322. if (sourceValue instanceof Array) {
  4323. destination[prop] = [];
  4324. if (sourceValue.length > 0) {
  4325. if (typeof sourceValue[0] == "object") {
  4326. for (var index = 0; index < sourceValue.length; index++) {
  4327. var clonedValue = cloneValue(sourceValue[index], destination);
  4328. if (destination[prop].indexOf(clonedValue) === -1) {
  4329. destination[prop].push(clonedValue);
  4330. }
  4331. }
  4332. }
  4333. else {
  4334. destination[prop] = sourceValue.slice(0);
  4335. }
  4336. }
  4337. }
  4338. else {
  4339. destination[prop] = cloneValue(sourceValue, destination);
  4340. }
  4341. }
  4342. else {
  4343. destination[prop] = sourceValue;
  4344. }
  4345. }
  4346. };
  4347. Tools.IsEmpty = function (obj) {
  4348. for (var i in obj) {
  4349. return false;
  4350. }
  4351. return true;
  4352. };
  4353. Tools.RegisterTopRootEvents = function (events) {
  4354. for (var index = 0; index < events.length; index++) {
  4355. var event = events[index];
  4356. window.addEventListener(event.name, event.handler, false);
  4357. try {
  4358. if (window.parent) {
  4359. window.parent.addEventListener(event.name, event.handler, false);
  4360. }
  4361. }
  4362. catch (e) {
  4363. }
  4364. }
  4365. };
  4366. Tools.UnregisterTopRootEvents = function (events) {
  4367. for (var index = 0; index < events.length; index++) {
  4368. var event = events[index];
  4369. window.removeEventListener(event.name, event.handler);
  4370. try {
  4371. if (window.parent) {
  4372. window.parent.removeEventListener(event.name, event.handler);
  4373. }
  4374. }
  4375. catch (e) {
  4376. }
  4377. }
  4378. };
  4379. Tools.DumpFramebuffer = function (width, height, engine) {
  4380. // Read the contents of the framebuffer
  4381. var numberOfChannelsByLine = width * 4;
  4382. var halfHeight = height / 2;
  4383. //Reading datas from WebGL
  4384. var data = engine.readPixels(0, 0, width, height);
  4385. for (var i = 0; i < halfHeight; i++) {
  4386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4387. var currentCell = j + i * numberOfChannelsByLine;
  4388. var targetLine = height - i - 1;
  4389. var targetCell = j + targetLine * numberOfChannelsByLine;
  4390. var temp = data[currentCell];
  4391. data[currentCell] = data[targetCell];
  4392. data[targetCell] = temp;
  4393. }
  4394. }
  4395. // Create a 2D canvas to store the result
  4396. if (!screenshotCanvas) {
  4397. screenshotCanvas = document.createElement('canvas');
  4398. }
  4399. screenshotCanvas.width = width;
  4400. screenshotCanvas.height = height;
  4401. var context = screenshotCanvas.getContext('2d');
  4402. // Copy the pixels to a 2D canvas
  4403. var imageData = context.createImageData(width, height);
  4404. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4405. var castData = imageData.data;
  4406. castData.set(data);
  4407. context.putImageData(imageData, 0, 0);
  4408. var base64Image = screenshotCanvas.toDataURL();
  4409. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4410. if (("download" in document.createElement("a"))) {
  4411. var a = window.document.createElement("a");
  4412. a.href = base64Image;
  4413. var date = new Date();
  4414. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4415. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4416. window.document.body.appendChild(a);
  4417. a.addEventListener("click", function () {
  4418. a.parentElement.removeChild(a);
  4419. });
  4420. a.click();
  4421. }
  4422. else {
  4423. var newWindow = window.open("");
  4424. var img = newWindow.document.createElement("img");
  4425. img.src = base64Image;
  4426. newWindow.document.body.appendChild(img);
  4427. }
  4428. };
  4429. Tools.CreateScreenshot = function (engine, camera, size) {
  4430. var width;
  4431. var height;
  4432. var scene = camera.getScene();
  4433. var previousCamera = null;
  4434. if (scene.activeCamera !== camera) {
  4435. previousCamera = scene.activeCamera;
  4436. scene.activeCamera = camera;
  4437. }
  4438. //If a precision value is specified
  4439. if (size.precision) {
  4440. width = Math.round(engine.getRenderWidth() * size.precision);
  4441. height = Math.round(width / engine.getAspectRatio(camera));
  4442. size = { width: width, height: height };
  4443. }
  4444. else if (size.width && size.height) {
  4445. width = size.width;
  4446. height = size.height;
  4447. }
  4448. else if (size.width && !size.height) {
  4449. width = size.width;
  4450. height = Math.round(width / engine.getAspectRatio(camera));
  4451. size = { width: width, height: height };
  4452. }
  4453. else if (size.height && !size.width) {
  4454. height = size.height;
  4455. width = Math.round(height * engine.getAspectRatio(camera));
  4456. size = { width: width, height: height };
  4457. }
  4458. else if (!isNaN(size)) {
  4459. height = size;
  4460. width = size;
  4461. }
  4462. else {
  4463. Tools.Error("Invalid 'size' parameter !");
  4464. return;
  4465. }
  4466. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4467. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4468. texture.renderList = scene.meshes;
  4469. texture.onAfterRender = function () {
  4470. Tools.DumpFramebuffer(width, height, engine);
  4471. };
  4472. scene.incrementRenderId();
  4473. texture.render(true);
  4474. texture.dispose();
  4475. if (previousCamera) {
  4476. scene.activeCamera = previousCamera;
  4477. }
  4478. };
  4479. // XHR response validator for local file scenario
  4480. Tools.ValidateXHRData = function (xhr, dataType) {
  4481. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4482. if (dataType === void 0) { dataType = 7; }
  4483. try {
  4484. if (dataType & 1) {
  4485. if (xhr.responseText && xhr.responseText.length > 0) {
  4486. return true;
  4487. }
  4488. else if (dataType === 1) {
  4489. return false;
  4490. }
  4491. }
  4492. if (dataType & 2) {
  4493. // Check header width and height since there is no "TGA" magic number
  4494. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4495. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4496. return true;
  4497. }
  4498. else if (dataType === 2) {
  4499. return false;
  4500. }
  4501. }
  4502. if (dataType & 4) {
  4503. // Check for the "DDS" magic number
  4504. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4505. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4506. return true;
  4507. }
  4508. else {
  4509. return false;
  4510. }
  4511. }
  4512. }
  4513. catch (e) {
  4514. }
  4515. return false;
  4516. };
  4517. Object.defineProperty(Tools, "NoneLogLevel", {
  4518. get: function () {
  4519. return Tools._NoneLogLevel;
  4520. },
  4521. enumerable: true,
  4522. configurable: true
  4523. });
  4524. Object.defineProperty(Tools, "MessageLogLevel", {
  4525. get: function () {
  4526. return Tools._MessageLogLevel;
  4527. },
  4528. enumerable: true,
  4529. configurable: true
  4530. });
  4531. Object.defineProperty(Tools, "WarningLogLevel", {
  4532. get: function () {
  4533. return Tools._WarningLogLevel;
  4534. },
  4535. enumerable: true,
  4536. configurable: true
  4537. });
  4538. Object.defineProperty(Tools, "ErrorLogLevel", {
  4539. get: function () {
  4540. return Tools._ErrorLogLevel;
  4541. },
  4542. enumerable: true,
  4543. configurable: true
  4544. });
  4545. Object.defineProperty(Tools, "AllLogLevel", {
  4546. get: function () {
  4547. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4548. },
  4549. enumerable: true,
  4550. configurable: true
  4551. });
  4552. Tools._AddLogEntry = function (entry) {
  4553. Tools._LogCache = entry + Tools._LogCache;
  4554. if (Tools.OnNewCacheEntry) {
  4555. Tools.OnNewCacheEntry(entry);
  4556. }
  4557. };
  4558. Tools._FormatMessage = function (message) {
  4559. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4560. var date = new Date();
  4561. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4562. };
  4563. Tools._LogDisabled = function (message) {
  4564. // nothing to do
  4565. };
  4566. Tools._LogEnabled = function (message) {
  4567. var formattedMessage = Tools._FormatMessage(message);
  4568. console.log("BJS - " + formattedMessage);
  4569. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4570. Tools._AddLogEntry(entry);
  4571. };
  4572. Tools._WarnDisabled = function (message) {
  4573. // nothing to do
  4574. };
  4575. Tools._WarnEnabled = function (message) {
  4576. var formattedMessage = Tools._FormatMessage(message);
  4577. console.warn("BJS - " + formattedMessage);
  4578. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4579. Tools._AddLogEntry(entry);
  4580. };
  4581. Tools._ErrorDisabled = function (message) {
  4582. // nothing to do
  4583. };
  4584. Tools._ErrorEnabled = function (message) {
  4585. var formattedMessage = Tools._FormatMessage(message);
  4586. console.error("BJS - " + formattedMessage);
  4587. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4588. Tools._AddLogEntry(entry);
  4589. };
  4590. Object.defineProperty(Tools, "LogCache", {
  4591. get: function () {
  4592. return Tools._LogCache;
  4593. },
  4594. enumerable: true,
  4595. configurable: true
  4596. });
  4597. Object.defineProperty(Tools, "LogLevels", {
  4598. set: function (level) {
  4599. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4600. Tools.Log = Tools._LogEnabled;
  4601. }
  4602. else {
  4603. Tools.Log = Tools._LogDisabled;
  4604. }
  4605. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4606. Tools.Warn = Tools._WarnEnabled;
  4607. }
  4608. else {
  4609. Tools.Warn = Tools._WarnDisabled;
  4610. }
  4611. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4612. Tools.Error = Tools._ErrorEnabled;
  4613. }
  4614. else {
  4615. Tools.Error = Tools._ErrorDisabled;
  4616. }
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4622. get: function () {
  4623. return Tools._PerformanceNoneLogLevel;
  4624. },
  4625. enumerable: true,
  4626. configurable: true
  4627. });
  4628. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4629. get: function () {
  4630. return Tools._PerformanceUserMarkLogLevel;
  4631. },
  4632. enumerable: true,
  4633. configurable: true
  4634. });
  4635. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4636. get: function () {
  4637. return Tools._PerformanceConsoleLogLevel;
  4638. },
  4639. enumerable: true,
  4640. configurable: true
  4641. });
  4642. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4643. set: function (level) {
  4644. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4645. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4646. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4647. return;
  4648. }
  4649. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4650. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4651. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4652. return;
  4653. }
  4654. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4655. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4656. },
  4657. enumerable: true,
  4658. configurable: true
  4659. });
  4660. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4661. };
  4662. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4663. };
  4664. Tools._StartUserMark = function (counterName, condition) {
  4665. if (condition === void 0) { condition = true; }
  4666. if (!condition || !Tools._performance.mark) {
  4667. return;
  4668. }
  4669. Tools._performance.mark(counterName + "-Begin");
  4670. };
  4671. Tools._EndUserMark = function (counterName, condition) {
  4672. if (condition === void 0) { condition = true; }
  4673. if (!condition || !Tools._performance.mark) {
  4674. return;
  4675. }
  4676. Tools._performance.mark(counterName + "-End");
  4677. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4678. };
  4679. Tools._StartPerformanceConsole = function (counterName, condition) {
  4680. if (condition === void 0) { condition = true; }
  4681. if (!condition) {
  4682. return;
  4683. }
  4684. Tools._StartUserMark(counterName, condition);
  4685. if (console.time) {
  4686. console.time(counterName);
  4687. }
  4688. };
  4689. Tools._EndPerformanceConsole = function (counterName, condition) {
  4690. if (condition === void 0) { condition = true; }
  4691. if (!condition) {
  4692. return;
  4693. }
  4694. Tools._EndUserMark(counterName, condition);
  4695. if (console.time) {
  4696. console.timeEnd(counterName);
  4697. }
  4698. };
  4699. Object.defineProperty(Tools, "Now", {
  4700. get: function () {
  4701. if (window.performance && window.performance.now) {
  4702. return window.performance.now();
  4703. }
  4704. return new Date().getTime();
  4705. },
  4706. enumerable: true,
  4707. configurable: true
  4708. });
  4709. // Deprecated
  4710. Tools.GetFps = function () {
  4711. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4712. return 0;
  4713. };
  4714. Tools.BaseUrl = "";
  4715. Tools.GetExponantOfTwo = function (value, max) {
  4716. var count = 1;
  4717. do {
  4718. count *= 2;
  4719. } while (count < value);
  4720. if (count > max)
  4721. count = max;
  4722. return count;
  4723. };
  4724. // Logs
  4725. Tools._NoneLogLevel = 0;
  4726. Tools._MessageLogLevel = 1;
  4727. Tools._WarningLogLevel = 2;
  4728. Tools._ErrorLogLevel = 4;
  4729. Tools._LogCache = "";
  4730. Tools.Log = Tools._LogEnabled;
  4731. Tools.Warn = Tools._WarnEnabled;
  4732. Tools.Error = Tools._ErrorEnabled;
  4733. // Performances
  4734. Tools._PerformanceNoneLogLevel = 0;
  4735. Tools._PerformanceUserMarkLogLevel = 1;
  4736. Tools._PerformanceConsoleLogLevel = 2;
  4737. Tools._performance = window.performance;
  4738. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4739. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4740. return Tools;
  4741. })();
  4742. BABYLON.Tools = Tools;
  4743. /**
  4744. * An implementation of a loop for asynchronous functions.
  4745. */
  4746. var AsyncLoop = (function () {
  4747. /**
  4748. * Constroctor.
  4749. * @param iterations the number of iterations.
  4750. * @param _fn the function to run each iteration
  4751. * @param _successCallback the callback that will be called upon succesful execution
  4752. * @param offset starting offset.
  4753. */
  4754. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4755. if (offset === void 0) { offset = 0; }
  4756. this.iterations = iterations;
  4757. this._fn = _fn;
  4758. this._successCallback = _successCallback;
  4759. this.index = offset - 1;
  4760. this._done = false;
  4761. }
  4762. /**
  4763. * Execute the next iteration. Must be called after the last iteration was finished.
  4764. */
  4765. AsyncLoop.prototype.executeNext = function () {
  4766. if (!this._done) {
  4767. if (this.index + 1 < this.iterations) {
  4768. ++this.index;
  4769. this._fn(this);
  4770. }
  4771. else {
  4772. this.breakLoop();
  4773. }
  4774. }
  4775. };
  4776. /**
  4777. * Break the loop and run the success callback.
  4778. */
  4779. AsyncLoop.prototype.breakLoop = function () {
  4780. this._done = true;
  4781. this._successCallback();
  4782. };
  4783. /**
  4784. * Helper function
  4785. */
  4786. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4787. if (offset === void 0) { offset = 0; }
  4788. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4789. loop.executeNext();
  4790. return loop;
  4791. };
  4792. /**
  4793. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4794. * @param iterations total number of iterations
  4795. * @param syncedIterations number of synchronous iterations in each async iteration.
  4796. * @param fn the function to call each iteration.
  4797. * @param callback a success call back that will be called when iterating stops.
  4798. * @param breakFunction a break condition (optional)
  4799. * @param timeout timeout settings for the setTimeout function. default - 0.
  4800. * @constructor
  4801. */
  4802. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4803. if (timeout === void 0) { timeout = 0; }
  4804. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4805. if (breakFunction && breakFunction())
  4806. loop.breakLoop();
  4807. else {
  4808. setTimeout(function () {
  4809. for (var i = 0; i < syncedIterations; ++i) {
  4810. var iteration = (loop.index * syncedIterations) + i;
  4811. if (iteration >= iterations)
  4812. break;
  4813. fn(iteration);
  4814. if (breakFunction && breakFunction()) {
  4815. loop.breakLoop();
  4816. break;
  4817. }
  4818. }
  4819. loop.executeNext();
  4820. }, timeout);
  4821. }
  4822. }, callback);
  4823. };
  4824. return AsyncLoop;
  4825. })();
  4826. BABYLON.AsyncLoop = AsyncLoop;
  4827. })(BABYLON || (BABYLON = {}));
  4828. //# sourceMappingURL=babylon.tools.js.map
  4829. var BABYLON;
  4830. (function (BABYLON) {
  4831. var _DepthCullingState = (function () {
  4832. function _DepthCullingState() {
  4833. this._isDepthTestDirty = false;
  4834. this._isDepthMaskDirty = false;
  4835. this._isDepthFuncDirty = false;
  4836. this._isCullFaceDirty = false;
  4837. this._isCullDirty = false;
  4838. this._isZOffsetDirty = false;
  4839. }
  4840. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4841. get: function () {
  4842. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4843. },
  4844. enumerable: true,
  4845. configurable: true
  4846. });
  4847. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4848. get: function () {
  4849. return this._zOffset;
  4850. },
  4851. set: function (value) {
  4852. if (this._zOffset === value) {
  4853. return;
  4854. }
  4855. this._zOffset = value;
  4856. this._isZOffsetDirty = true;
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4862. get: function () {
  4863. return this._cullFace;
  4864. },
  4865. set: function (value) {
  4866. if (this._cullFace === value) {
  4867. return;
  4868. }
  4869. this._cullFace = value;
  4870. this._isCullFaceDirty = true;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4876. get: function () {
  4877. return this._cull;
  4878. },
  4879. set: function (value) {
  4880. if (this._cull === value) {
  4881. return;
  4882. }
  4883. this._cull = value;
  4884. this._isCullDirty = true;
  4885. },
  4886. enumerable: true,
  4887. configurable: true
  4888. });
  4889. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4890. get: function () {
  4891. return this._depthFunc;
  4892. },
  4893. set: function (value) {
  4894. if (this._depthFunc === value) {
  4895. return;
  4896. }
  4897. this._depthFunc = value;
  4898. this._isDepthFuncDirty = true;
  4899. },
  4900. enumerable: true,
  4901. configurable: true
  4902. });
  4903. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4904. get: function () {
  4905. return this._depthMask;
  4906. },
  4907. set: function (value) {
  4908. if (this._depthMask === value) {
  4909. return;
  4910. }
  4911. this._depthMask = value;
  4912. this._isDepthMaskDirty = true;
  4913. },
  4914. enumerable: true,
  4915. configurable: true
  4916. });
  4917. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4918. get: function () {
  4919. return this._depthTest;
  4920. },
  4921. set: function (value) {
  4922. if (this._depthTest === value) {
  4923. return;
  4924. }
  4925. this._depthTest = value;
  4926. this._isDepthTestDirty = true;
  4927. },
  4928. enumerable: true,
  4929. configurable: true
  4930. });
  4931. _DepthCullingState.prototype.reset = function () {
  4932. this._depthMask = true;
  4933. this._depthTest = true;
  4934. this._depthFunc = null;
  4935. this._cull = null;
  4936. this._cullFace = null;
  4937. this._zOffset = 0;
  4938. this._isDepthTestDirty = true;
  4939. this._isDepthMaskDirty = true;
  4940. this._isDepthFuncDirty = false;
  4941. this._isCullFaceDirty = false;
  4942. this._isCullDirty = false;
  4943. this._isZOffsetDirty = false;
  4944. };
  4945. _DepthCullingState.prototype.apply = function (gl) {
  4946. if (!this.isDirty) {
  4947. return;
  4948. }
  4949. // Cull
  4950. if (this._isCullDirty) {
  4951. if (this.cull) {
  4952. gl.enable(gl.CULL_FACE);
  4953. }
  4954. else {
  4955. gl.disable(gl.CULL_FACE);
  4956. }
  4957. this._isCullDirty = false;
  4958. }
  4959. // Cull face
  4960. if (this._isCullFaceDirty) {
  4961. gl.cullFace(this.cullFace);
  4962. this._isCullFaceDirty = false;
  4963. }
  4964. // Depth mask
  4965. if (this._isDepthMaskDirty) {
  4966. gl.depthMask(this.depthMask);
  4967. this._isDepthMaskDirty = false;
  4968. }
  4969. // Depth test
  4970. if (this._isDepthTestDirty) {
  4971. if (this.depthTest) {
  4972. gl.enable(gl.DEPTH_TEST);
  4973. }
  4974. else {
  4975. gl.disable(gl.DEPTH_TEST);
  4976. }
  4977. this._isDepthTestDirty = false;
  4978. }
  4979. // Depth func
  4980. if (this._isDepthFuncDirty) {
  4981. gl.depthFunc(this.depthFunc);
  4982. this._isDepthFuncDirty = false;
  4983. }
  4984. // zOffset
  4985. if (this._isZOffsetDirty) {
  4986. if (this.zOffset) {
  4987. gl.enable(gl.POLYGON_OFFSET_FILL);
  4988. gl.polygonOffset(this.zOffset, 0);
  4989. }
  4990. else {
  4991. gl.disable(gl.POLYGON_OFFSET_FILL);
  4992. }
  4993. this._isZOffsetDirty = false;
  4994. }
  4995. };
  4996. return _DepthCullingState;
  4997. })();
  4998. BABYLON._DepthCullingState = _DepthCullingState;
  4999. var _AlphaState = (function () {
  5000. function _AlphaState() {
  5001. this._isAlphaBlendDirty = false;
  5002. this._isBlendFunctionParametersDirty = false;
  5003. this._alphaBlend = false;
  5004. this._blendFunctionParameters = new Array(4);
  5005. }
  5006. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5007. get: function () {
  5008. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5009. },
  5010. enumerable: true,
  5011. configurable: true
  5012. });
  5013. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5014. get: function () {
  5015. return this._alphaBlend;
  5016. },
  5017. set: function (value) {
  5018. if (this._alphaBlend === value) {
  5019. return;
  5020. }
  5021. this._alphaBlend = value;
  5022. this._isAlphaBlendDirty = true;
  5023. },
  5024. enumerable: true,
  5025. configurable: true
  5026. });
  5027. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5028. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  5029. return;
  5030. }
  5031. this._blendFunctionParameters[0] = value0;
  5032. this._blendFunctionParameters[1] = value1;
  5033. this._blendFunctionParameters[2] = value2;
  5034. this._blendFunctionParameters[3] = value3;
  5035. this._isBlendFunctionParametersDirty = true;
  5036. };
  5037. _AlphaState.prototype.reset = function () {
  5038. this._alphaBlend = false;
  5039. this._blendFunctionParameters[0] = null;
  5040. this._blendFunctionParameters[1] = null;
  5041. this._blendFunctionParameters[2] = null;
  5042. this._blendFunctionParameters[3] = null;
  5043. this._isAlphaBlendDirty = true;
  5044. this._isBlendFunctionParametersDirty = false;
  5045. };
  5046. _AlphaState.prototype.apply = function (gl) {
  5047. if (!this.isDirty) {
  5048. return;
  5049. }
  5050. // Alpha blend
  5051. if (this._isAlphaBlendDirty) {
  5052. if (this._alphaBlend) {
  5053. gl.enable(gl.BLEND);
  5054. }
  5055. else {
  5056. gl.disable(gl.BLEND);
  5057. }
  5058. this._isAlphaBlendDirty = false;
  5059. }
  5060. // Alpha function
  5061. if (this._isBlendFunctionParametersDirty) {
  5062. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5063. this._isBlendFunctionParametersDirty = false;
  5064. }
  5065. };
  5066. return _AlphaState;
  5067. })();
  5068. BABYLON._AlphaState = _AlphaState;
  5069. var compileShader = function (gl, source, type, defines) {
  5070. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5071. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5072. gl.compileShader(shader);
  5073. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5074. throw new Error(gl.getShaderInfoLog(shader));
  5075. }
  5076. return shader;
  5077. };
  5078. var getWebGLTextureType = function (gl, type) {
  5079. var textureType = gl.UNSIGNED_BYTE;
  5080. if (type === Engine.TEXTURETYPE_FLOAT)
  5081. textureType = gl.FLOAT;
  5082. return textureType;
  5083. };
  5084. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5085. var magFilter = gl.NEAREST;
  5086. var minFilter = gl.NEAREST;
  5087. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5088. magFilter = gl.LINEAR;
  5089. if (generateMipMaps) {
  5090. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5091. }
  5092. else {
  5093. minFilter = gl.LINEAR;
  5094. }
  5095. }
  5096. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5097. magFilter = gl.LINEAR;
  5098. if (generateMipMaps) {
  5099. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5100. }
  5101. else {
  5102. minFilter = gl.LINEAR;
  5103. }
  5104. }
  5105. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5106. magFilter = gl.NEAREST;
  5107. if (generateMipMaps) {
  5108. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5109. }
  5110. else {
  5111. minFilter = gl.NEAREST;
  5112. }
  5113. }
  5114. return {
  5115. min: minFilter,
  5116. mag: magFilter
  5117. };
  5118. };
  5119. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5121. var engine = scene.getEngine();
  5122. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5123. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5124. gl.bindTexture(gl.TEXTURE_2D, texture);
  5125. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5126. texture._baseWidth = width;
  5127. texture._baseHeight = height;
  5128. texture._width = potWidth;
  5129. texture._height = potHeight;
  5130. texture.isReady = true;
  5131. processFunction(potWidth, potHeight);
  5132. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5135. if (!noMipmap && !isCompressed) {
  5136. gl.generateMipmap(gl.TEXTURE_2D);
  5137. }
  5138. gl.bindTexture(gl.TEXTURE_2D, null);
  5139. engine._activeTexturesCache = [];
  5140. scene._removePendingData(texture);
  5141. };
  5142. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5143. var onload = function () {
  5144. loadedImages[index] = img;
  5145. loadedImages._internalCount++;
  5146. scene._removePendingData(img);
  5147. if (loadedImages._internalCount === 6) {
  5148. onfinish(loadedImages);
  5149. }
  5150. };
  5151. var onerror = function () {
  5152. scene._removePendingData(img);
  5153. };
  5154. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5155. scene._addPendingData(img);
  5156. };
  5157. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5158. var loadedImages = [];
  5159. loadedImages._internalCount = 0;
  5160. for (var index = 0; index < 6; index++) {
  5161. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5162. }
  5163. };
  5164. var EngineCapabilities = (function () {
  5165. function EngineCapabilities() {
  5166. }
  5167. return EngineCapabilities;
  5168. })();
  5169. BABYLON.EngineCapabilities = EngineCapabilities;
  5170. /**
  5171. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5172. */
  5173. var Engine = (function () {
  5174. /**
  5175. * @constructor
  5176. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5177. * @param {boolean} [antialias] - enable antialias
  5178. * @param options - further options to be sent to the getContext function
  5179. */
  5180. function Engine(canvas, antialias, options) {
  5181. var _this = this;
  5182. // Public members
  5183. this.isFullscreen = false;
  5184. this.isPointerLock = false;
  5185. this.cullBackFaces = true;
  5186. this.renderEvenInBackground = true;
  5187. this.scenes = new Array();
  5188. this._windowIsBackground = false;
  5189. this._loadingDivBackgroundColor = "black";
  5190. this._drawCalls = 0;
  5191. this._renderingQueueLaunched = false;
  5192. this._activeRenderLoops = [];
  5193. // FPS
  5194. this.fpsRange = 60;
  5195. this.previousFramesDuration = [];
  5196. this.fps = 60;
  5197. this.deltaTime = 0;
  5198. // States
  5199. this._depthCullingState = new _DepthCullingState();
  5200. this._alphaState = new _AlphaState();
  5201. this._alphaMode = Engine.ALPHA_DISABLE;
  5202. // Cache
  5203. this._loadedTexturesCache = new Array();
  5204. this._activeTexturesCache = new Array();
  5205. this._compiledEffects = {};
  5206. this._uintIndicesCurrentlySet = false;
  5207. this._renderingCanvas = canvas;
  5208. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5209. options = options || {};
  5210. options.antialias = antialias;
  5211. try {
  5212. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5213. }
  5214. catch (e) {
  5215. throw new Error("WebGL not supported");
  5216. }
  5217. if (!this._gl) {
  5218. throw new Error("WebGL not supported");
  5219. }
  5220. this._onBlur = function () {
  5221. _this._windowIsBackground = true;
  5222. };
  5223. this._onFocus = function () {
  5224. _this._windowIsBackground = false;
  5225. };
  5226. window.addEventListener("blur", this._onBlur);
  5227. window.addEventListener("focus", this._onFocus);
  5228. // Viewport
  5229. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5230. this.resize();
  5231. // Caps
  5232. this._caps = new EngineCapabilities();
  5233. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5234. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5235. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5236. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5237. // Infos
  5238. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5239. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5240. if (rendererInfo != null) {
  5241. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5242. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5243. }
  5244. if (!this._glVendor) {
  5245. this._glVendor = "Unknown vendor";
  5246. }
  5247. if (!this._glRenderer) {
  5248. this._glRenderer = "Unknown renderer";
  5249. }
  5250. // Extensions
  5251. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5252. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5253. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5254. 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');
  5255. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5256. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5257. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5258. this._caps.highPrecisionShaderSupported = true;
  5259. if (this._gl.getShaderPrecisionFormat) {
  5260. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5261. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5262. }
  5263. // Depth buffer
  5264. this.setDepthBuffer(true);
  5265. this.setDepthFunctionToLessOrEqual();
  5266. this.setDepthWrite(true);
  5267. // Fullscreen
  5268. this._onFullscreenChange = function () {
  5269. if (document.fullscreen !== undefined) {
  5270. _this.isFullscreen = document.fullscreen;
  5271. }
  5272. else if (document.mozFullScreen !== undefined) {
  5273. _this.isFullscreen = document.mozFullScreen;
  5274. }
  5275. else if (document.webkitIsFullScreen !== undefined) {
  5276. _this.isFullscreen = document.webkitIsFullScreen;
  5277. }
  5278. else if (document.msIsFullScreen !== undefined) {
  5279. _this.isFullscreen = document.msIsFullScreen;
  5280. }
  5281. // Pointer lock
  5282. if (_this.isFullscreen && _this._pointerLockRequested) {
  5283. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  5284. if (canvas.requestPointerLock) {
  5285. canvas.requestPointerLock();
  5286. }
  5287. }
  5288. };
  5289. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5290. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5291. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5292. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5293. // Pointer lock
  5294. this._onPointerLockChange = function () {
  5295. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  5296. };
  5297. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5298. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5299. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5300. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5301. if (!Engine.audioEngine) {
  5302. Engine.audioEngine = new BABYLON.AudioEngine();
  5303. }
  5304. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5305. }
  5306. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5307. get: function () {
  5308. return Engine._ALPHA_DISABLE;
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. Object.defineProperty(Engine, "ALPHA_ADD", {
  5314. get: function () {
  5315. return Engine._ALPHA_ADD;
  5316. },
  5317. enumerable: true,
  5318. configurable: true
  5319. });
  5320. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5321. get: function () {
  5322. return Engine._ALPHA_COMBINE;
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5328. get: function () {
  5329. return Engine._DELAYLOADSTATE_NONE;
  5330. },
  5331. enumerable: true,
  5332. configurable: true
  5333. });
  5334. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5335. get: function () {
  5336. return Engine._DELAYLOADSTATE_LOADED;
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5342. get: function () {
  5343. return Engine._DELAYLOADSTATE_LOADING;
  5344. },
  5345. enumerable: true,
  5346. configurable: true
  5347. });
  5348. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5349. get: function () {
  5350. return Engine._DELAYLOADSTATE_NOTLOADED;
  5351. },
  5352. enumerable: true,
  5353. configurable: true
  5354. });
  5355. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5356. get: function () {
  5357. return Engine._TEXTUREFORMAT_ALPHA;
  5358. },
  5359. enumerable: true,
  5360. configurable: true
  5361. });
  5362. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5363. get: function () {
  5364. return Engine._TEXTUREFORMAT_LUMINANCE;
  5365. },
  5366. enumerable: true,
  5367. configurable: true
  5368. });
  5369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5370. get: function () {
  5371. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5372. },
  5373. enumerable: true,
  5374. configurable: true
  5375. });
  5376. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5377. get: function () {
  5378. return Engine._TEXTUREFORMAT_RGB;
  5379. },
  5380. enumerable: true,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5384. get: function () {
  5385. return Engine._TEXTUREFORMAT_RGBA;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5391. get: function () {
  5392. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5398. get: function () {
  5399. return Engine._TEXTURETYPE_FLOAT;
  5400. },
  5401. enumerable: true,
  5402. configurable: true
  5403. });
  5404. Object.defineProperty(Engine, "Version", {
  5405. get: function () {
  5406. return "2.1.0 beta";
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Engine.prototype._prepareWorkingCanvas = function () {
  5412. if (this._workingCanvas) {
  5413. return;
  5414. }
  5415. this._workingCanvas = document.createElement("canvas");
  5416. this._workingContext = this._workingCanvas.getContext("2d");
  5417. };
  5418. Engine.prototype.getGlInfo = function () {
  5419. return {
  5420. vendor: this._glVendor,
  5421. renderer: this._glRenderer,
  5422. version: this._glVersion
  5423. };
  5424. };
  5425. Engine.prototype.getAspectRatio = function (camera) {
  5426. var viewport = camera.viewport;
  5427. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5428. };
  5429. Engine.prototype.getRenderWidth = function () {
  5430. if (this._currentRenderTarget) {
  5431. return this._currentRenderTarget._width;
  5432. }
  5433. return this._renderingCanvas.width;
  5434. };
  5435. Engine.prototype.getRenderHeight = function () {
  5436. if (this._currentRenderTarget) {
  5437. return this._currentRenderTarget._height;
  5438. }
  5439. return this._renderingCanvas.height;
  5440. };
  5441. Engine.prototype.getRenderingCanvas = function () {
  5442. return this._renderingCanvas;
  5443. };
  5444. Engine.prototype.getRenderingCanvasClientRect = function () {
  5445. return this._renderingCanvas.getBoundingClientRect();
  5446. };
  5447. Engine.prototype.setHardwareScalingLevel = function (level) {
  5448. this._hardwareScalingLevel = level;
  5449. this.resize();
  5450. };
  5451. Engine.prototype.getHardwareScalingLevel = function () {
  5452. return this._hardwareScalingLevel;
  5453. };
  5454. Engine.prototype.getLoadedTexturesCache = function () {
  5455. return this._loadedTexturesCache;
  5456. };
  5457. Engine.prototype.getCaps = function () {
  5458. return this._caps;
  5459. };
  5460. Object.defineProperty(Engine.prototype, "drawCalls", {
  5461. get: function () {
  5462. return this._drawCalls;
  5463. },
  5464. enumerable: true,
  5465. configurable: true
  5466. });
  5467. // Methods
  5468. Engine.prototype.resetDrawCalls = function () {
  5469. this._drawCalls = 0;
  5470. };
  5471. Engine.prototype.setDepthFunctionToGreater = function () {
  5472. this._depthCullingState.depthFunc = this._gl.GREATER;
  5473. };
  5474. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5475. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5476. };
  5477. Engine.prototype.setDepthFunctionToLess = function () {
  5478. this._depthCullingState.depthFunc = this._gl.LESS;
  5479. };
  5480. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5481. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5482. };
  5483. /**
  5484. * stop executing a render loop function and remove it from the execution array
  5485. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5486. */
  5487. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5488. if (!renderFunction) {
  5489. this._activeRenderLoops = [];
  5490. return;
  5491. }
  5492. var index = this._activeRenderLoops.indexOf(renderFunction);
  5493. if (index >= 0) {
  5494. this._activeRenderLoops.splice(index, 1);
  5495. }
  5496. };
  5497. Engine.prototype._renderLoop = function () {
  5498. var _this = this;
  5499. var shouldRender = true;
  5500. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5501. shouldRender = false;
  5502. }
  5503. if (shouldRender) {
  5504. // Start new frame
  5505. this.beginFrame();
  5506. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5507. var renderFunction = this._activeRenderLoops[index];
  5508. renderFunction();
  5509. }
  5510. // Present
  5511. this.endFrame();
  5512. }
  5513. if (this._activeRenderLoops.length > 0) {
  5514. // Register new frame
  5515. BABYLON.Tools.QueueNewFrame(function () {
  5516. _this._renderLoop();
  5517. });
  5518. }
  5519. else {
  5520. this._renderingQueueLaunched = false;
  5521. }
  5522. };
  5523. /**
  5524. * Register and execute a render loop. The engine can have more than one render function.
  5525. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5526. * @example
  5527. * engine.runRenderLoop(function () {
  5528. * scene.render()
  5529. * })
  5530. */
  5531. Engine.prototype.runRenderLoop = function (renderFunction) {
  5532. var _this = this;
  5533. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5534. return;
  5535. }
  5536. this._activeRenderLoops.push(renderFunction);
  5537. if (!this._renderingQueueLaunched) {
  5538. this._renderingQueueLaunched = true;
  5539. BABYLON.Tools.QueueNewFrame(function () {
  5540. _this._renderLoop();
  5541. });
  5542. }
  5543. };
  5544. /**
  5545. * Toggle full screen mode.
  5546. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5547. */
  5548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5549. if (this.isFullscreen) {
  5550. BABYLON.Tools.ExitFullscreen();
  5551. }
  5552. else {
  5553. this._pointerLockRequested = requestPointerLock;
  5554. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5555. }
  5556. };
  5557. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5558. this.applyStates();
  5559. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5560. if (this._depthCullingState.depthMask) {
  5561. this._gl.clearDepth(1.0);
  5562. }
  5563. var mode = 0;
  5564. if (backBuffer)
  5565. mode |= this._gl.COLOR_BUFFER_BIT;
  5566. if (depthStencil && this._depthCullingState.depthMask)
  5567. mode |= this._gl.DEPTH_BUFFER_BIT;
  5568. this._gl.clear(mode);
  5569. };
  5570. /**
  5571. * Set the WebGL's viewport
  5572. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5573. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5574. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5575. */
  5576. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5577. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5578. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5579. var x = viewport.x || 0;
  5580. var y = viewport.y || 0;
  5581. this._cachedViewport = viewport;
  5582. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5583. };
  5584. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5585. this._cachedViewport = null;
  5586. this._gl.viewport(x, y, width, height);
  5587. };
  5588. Engine.prototype.beginFrame = function () {
  5589. this._measureFps();
  5590. };
  5591. Engine.prototype.endFrame = function () {
  5592. //this.flushFramebuffer();
  5593. };
  5594. /**
  5595. * resize the view according to the canvas' size.
  5596. * @example
  5597. * window.addEventListener("resize", function () {
  5598. * engine.resize();
  5599. * });
  5600. */
  5601. Engine.prototype.resize = function () {
  5602. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5603. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5604. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5605. };
  5606. /**
  5607. * force a specific size of the canvas
  5608. * @param {number} width - the new canvas' width
  5609. * @param {number} height - the new canvas' height
  5610. */
  5611. Engine.prototype.setSize = function (width, height) {
  5612. this._renderingCanvas.width = width;
  5613. this._renderingCanvas.height = height;
  5614. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5615. for (var index = 0; index < this.scenes.length; index++) {
  5616. var scene = this.scenes[index];
  5617. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5618. var cam = scene.cameras[camIndex];
  5619. cam._currentRenderId = 0;
  5620. }
  5621. }
  5622. };
  5623. Engine.prototype.bindFramebuffer = function (texture) {
  5624. this._currentRenderTarget = texture;
  5625. var gl = this._gl;
  5626. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5627. this._gl.viewport(0, 0, texture._width, texture._height);
  5628. this.wipeCaches();
  5629. };
  5630. Engine.prototype.unBindFramebuffer = function (texture) {
  5631. this._currentRenderTarget = null;
  5632. if (texture.generateMipMaps) {
  5633. var gl = this._gl;
  5634. gl.bindTexture(gl.TEXTURE_2D, texture);
  5635. gl.generateMipmap(gl.TEXTURE_2D);
  5636. gl.bindTexture(gl.TEXTURE_2D, null);
  5637. }
  5638. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5639. };
  5640. Engine.prototype.flushFramebuffer = function () {
  5641. this._gl.flush();
  5642. };
  5643. Engine.prototype.restoreDefaultFramebuffer = function () {
  5644. this._currentRenderTarget = null;
  5645. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5646. this.setViewport(this._cachedViewport);
  5647. this.wipeCaches();
  5648. };
  5649. // VBOs
  5650. Engine.prototype._resetVertexBufferBinding = function () {
  5651. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5652. this._cachedVertexBuffers = null;
  5653. };
  5654. Engine.prototype.createVertexBuffer = function (vertices) {
  5655. var vbo = this._gl.createBuffer();
  5656. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5657. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5658. this._resetVertexBufferBinding();
  5659. vbo.references = 1;
  5660. return vbo;
  5661. };
  5662. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5663. var vbo = this._gl.createBuffer();
  5664. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5665. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5666. this._resetVertexBufferBinding();
  5667. vbo.references = 1;
  5668. return vbo;
  5669. };
  5670. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5671. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5672. if (offset === undefined) {
  5673. offset = 0;
  5674. }
  5675. if (vertices instanceof Float32Array) {
  5676. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5677. }
  5678. else {
  5679. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5680. }
  5681. this._resetVertexBufferBinding();
  5682. };
  5683. Engine.prototype._resetIndexBufferBinding = function () {
  5684. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5685. this._cachedIndexBuffer = null;
  5686. };
  5687. Engine.prototype.createIndexBuffer = function (indices) {
  5688. var vbo = this._gl.createBuffer();
  5689. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5690. // Check for 32 bits indices
  5691. var arrayBuffer;
  5692. var need32Bits = false;
  5693. if (this._caps.uintIndices) {
  5694. for (var index = 0; index < indices.length; index++) {
  5695. if (indices[index] > 65535) {
  5696. need32Bits = true;
  5697. break;
  5698. }
  5699. }
  5700. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5701. }
  5702. else {
  5703. arrayBuffer = new Uint16Array(indices);
  5704. }
  5705. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5706. this._resetIndexBufferBinding();
  5707. vbo.references = 1;
  5708. vbo.is32Bits = need32Bits;
  5709. return vbo;
  5710. };
  5711. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5712. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5713. this._cachedVertexBuffers = vertexBuffer;
  5714. this._cachedEffectForVertexBuffers = effect;
  5715. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5716. var offset = 0;
  5717. for (var index = 0; index < vertexDeclaration.length; index++) {
  5718. var order = effect.getAttributeLocation(index);
  5719. if (order >= 0) {
  5720. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5721. }
  5722. offset += vertexDeclaration[index] * 4;
  5723. }
  5724. }
  5725. if (this._cachedIndexBuffer !== indexBuffer) {
  5726. this._cachedIndexBuffer = indexBuffer;
  5727. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5728. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5729. }
  5730. };
  5731. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5732. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5733. this._cachedVertexBuffers = vertexBuffers;
  5734. this._cachedEffectForVertexBuffers = effect;
  5735. var attributes = effect.getAttributesNames();
  5736. for (var index = 0; index < attributes.length; index++) {
  5737. var order = effect.getAttributeLocation(index);
  5738. if (order >= 0) {
  5739. var vertexBuffer = vertexBuffers[attributes[index]];
  5740. if (!vertexBuffer) {
  5741. continue;
  5742. }
  5743. var stride = vertexBuffer.getStrideSize();
  5744. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5745. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5746. }
  5747. }
  5748. }
  5749. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5750. this._cachedIndexBuffer = indexBuffer;
  5751. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5752. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5753. }
  5754. };
  5755. Engine.prototype._releaseBuffer = function (buffer) {
  5756. buffer.references--;
  5757. if (buffer.references === 0) {
  5758. this._gl.deleteBuffer(buffer);
  5759. return true;
  5760. }
  5761. return false;
  5762. };
  5763. Engine.prototype.createInstancesBuffer = function (capacity) {
  5764. var buffer = this._gl.createBuffer();
  5765. buffer.capacity = capacity;
  5766. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5767. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5768. return buffer;
  5769. };
  5770. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5771. this._gl.deleteBuffer(buffer);
  5772. };
  5773. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5774. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5775. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5776. for (var index = 0; index < 4; index++) {
  5777. var offsetLocation = offsetLocations[index];
  5778. this._gl.enableVertexAttribArray(offsetLocation);
  5779. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5780. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5781. }
  5782. };
  5783. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5785. for (var index = 0; index < 4; index++) {
  5786. var offsetLocation = offsetLocations[index];
  5787. this._gl.disableVertexAttribArray(offsetLocation);
  5788. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5789. }
  5790. };
  5791. Engine.prototype.applyStates = function () {
  5792. this._depthCullingState.apply(this._gl);
  5793. this._alphaState.apply(this._gl);
  5794. };
  5795. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5796. // Apply states
  5797. this.applyStates();
  5798. this._drawCalls++;
  5799. // Render
  5800. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5801. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5802. if (instancesCount) {
  5803. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5804. return;
  5805. }
  5806. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5807. };
  5808. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5809. // Apply states
  5810. this.applyStates();
  5811. this._drawCalls++;
  5812. if (instancesCount) {
  5813. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5814. return;
  5815. }
  5816. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5817. };
  5818. // Shaders
  5819. Engine.prototype._releaseEffect = function (effect) {
  5820. if (this._compiledEffects[effect._key]) {
  5821. delete this._compiledEffects[effect._key];
  5822. if (effect.getProgram()) {
  5823. this._gl.deleteProgram(effect.getProgram());
  5824. }
  5825. }
  5826. };
  5827. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5828. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5829. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5830. var name = vertex + "+" + fragment + "@" + defines;
  5831. if (this._compiledEffects[name]) {
  5832. return this._compiledEffects[name];
  5833. }
  5834. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5835. effect._key = name;
  5836. this._compiledEffects[name] = effect;
  5837. return effect;
  5838. };
  5839. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5840. if (uniformsNames === void 0) { uniformsNames = []; }
  5841. if (samplers === void 0) { samplers = []; }
  5842. if (defines === void 0) { defines = ""; }
  5843. return this.createEffect({
  5844. vertex: "particles",
  5845. fragmentElement: fragmentName
  5846. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5847. };
  5848. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5849. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5850. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5851. var shaderProgram = this._gl.createProgram();
  5852. this._gl.attachShader(shaderProgram, vertexShader);
  5853. this._gl.attachShader(shaderProgram, fragmentShader);
  5854. this._gl.linkProgram(shaderProgram);
  5855. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5856. if (!linked) {
  5857. var error = this._gl.getProgramInfoLog(shaderProgram);
  5858. if (error) {
  5859. throw new Error(error);
  5860. }
  5861. }
  5862. this._gl.deleteShader(vertexShader);
  5863. this._gl.deleteShader(fragmentShader);
  5864. return shaderProgram;
  5865. };
  5866. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5867. var results = [];
  5868. for (var index = 0; index < uniformsNames.length; index++) {
  5869. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5870. }
  5871. return results;
  5872. };
  5873. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5874. var results = [];
  5875. for (var index = 0; index < attributesNames.length; index++) {
  5876. try {
  5877. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5878. }
  5879. catch (e) {
  5880. results.push(-1);
  5881. }
  5882. }
  5883. return results;
  5884. };
  5885. Engine.prototype.enableEffect = function (effect) {
  5886. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5887. if (effect && effect.onBind) {
  5888. effect.onBind(effect);
  5889. }
  5890. return;
  5891. }
  5892. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5893. // Use program
  5894. this._gl.useProgram(effect.getProgram());
  5895. for (var i in this._vertexAttribArrays) {
  5896. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5897. continue;
  5898. }
  5899. this._vertexAttribArrays[i] = false;
  5900. this._gl.disableVertexAttribArray(i);
  5901. }
  5902. var attributesCount = effect.getAttributesCount();
  5903. for (var index = 0; index < attributesCount; index++) {
  5904. // Attributes
  5905. var order = effect.getAttributeLocation(index);
  5906. if (order >= 0) {
  5907. this._vertexAttribArrays[order] = true;
  5908. this._gl.enableVertexAttribArray(order);
  5909. }
  5910. }
  5911. this._currentEffect = effect;
  5912. if (effect.onBind) {
  5913. effect.onBind(effect);
  5914. }
  5915. };
  5916. Engine.prototype.setArray = function (uniform, array) {
  5917. if (!uniform)
  5918. return;
  5919. this._gl.uniform1fv(uniform, array);
  5920. };
  5921. Engine.prototype.setArray2 = function (uniform, array) {
  5922. if (!uniform || array.length % 2 !== 0)
  5923. return;
  5924. this._gl.uniform2fv(uniform, array);
  5925. };
  5926. Engine.prototype.setArray3 = function (uniform, array) {
  5927. if (!uniform || array.length % 3 !== 0)
  5928. return;
  5929. this._gl.uniform3fv(uniform, array);
  5930. };
  5931. Engine.prototype.setArray4 = function (uniform, array) {
  5932. if (!uniform || array.length % 4 !== 0)
  5933. return;
  5934. this._gl.uniform4fv(uniform, array);
  5935. };
  5936. Engine.prototype.setMatrices = function (uniform, matrices) {
  5937. if (!uniform)
  5938. return;
  5939. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5940. };
  5941. Engine.prototype.setMatrix = function (uniform, matrix) {
  5942. if (!uniform)
  5943. return;
  5944. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5945. };
  5946. Engine.prototype.setFloat = function (uniform, value) {
  5947. if (!uniform)
  5948. return;
  5949. this._gl.uniform1f(uniform, value);
  5950. };
  5951. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5952. if (!uniform)
  5953. return;
  5954. this._gl.uniform2f(uniform, x, y);
  5955. };
  5956. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5957. if (!uniform)
  5958. return;
  5959. this._gl.uniform3f(uniform, x, y, z);
  5960. };
  5961. Engine.prototype.setBool = function (uniform, bool) {
  5962. if (!uniform)
  5963. return;
  5964. this._gl.uniform1i(uniform, bool);
  5965. };
  5966. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5967. if (!uniform)
  5968. return;
  5969. this._gl.uniform4f(uniform, x, y, z, w);
  5970. };
  5971. Engine.prototype.setColor3 = function (uniform, color3) {
  5972. if (!uniform)
  5973. return;
  5974. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5975. };
  5976. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5977. if (!uniform)
  5978. return;
  5979. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5980. };
  5981. // States
  5982. Engine.prototype.setState = function (culling, zOffset, force) {
  5983. if (zOffset === void 0) { zOffset = 0; }
  5984. // Culling
  5985. if (this._depthCullingState.cull !== culling || force) {
  5986. if (culling) {
  5987. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  5988. this._depthCullingState.cull = true;
  5989. }
  5990. else {
  5991. this._depthCullingState.cull = false;
  5992. }
  5993. }
  5994. // Z offset
  5995. this._depthCullingState.zOffset = zOffset;
  5996. };
  5997. Engine.prototype.setDepthBuffer = function (enable) {
  5998. this._depthCullingState.depthTest = enable;
  5999. };
  6000. Engine.prototype.getDepthWrite = function () {
  6001. return this._depthCullingState.depthMask;
  6002. };
  6003. Engine.prototype.setDepthWrite = function (enable) {
  6004. this._depthCullingState.depthMask = enable;
  6005. };
  6006. Engine.prototype.setColorWrite = function (enable) {
  6007. this._gl.colorMask(enable, enable, enable, enable);
  6008. };
  6009. Engine.prototype.setAlphaMode = function (mode) {
  6010. switch (mode) {
  6011. case Engine.ALPHA_DISABLE:
  6012. this.setDepthWrite(true);
  6013. this._alphaState.alphaBlend = false;
  6014. break;
  6015. case Engine.ALPHA_COMBINE:
  6016. this.setDepthWrite(false);
  6017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6018. this._alphaState.alphaBlend = true;
  6019. break;
  6020. case Engine.ALPHA_ADD:
  6021. this.setDepthWrite(false);
  6022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6023. this._alphaState.alphaBlend = true;
  6024. break;
  6025. }
  6026. this._alphaMode = mode;
  6027. };
  6028. Engine.prototype.getAlphaMode = function () {
  6029. return this._alphaMode;
  6030. };
  6031. Engine.prototype.setAlphaTesting = function (enable) {
  6032. this._alphaTest = enable;
  6033. };
  6034. Engine.prototype.getAlphaTesting = function () {
  6035. return this._alphaTest;
  6036. };
  6037. // Textures
  6038. Engine.prototype.wipeCaches = function () {
  6039. this._activeTexturesCache = [];
  6040. this._currentEffect = null;
  6041. this._depthCullingState.reset();
  6042. this._alphaState.reset();
  6043. this._cachedVertexBuffers = null;
  6044. this._cachedIndexBuffer = null;
  6045. this._cachedEffectForVertexBuffers = null;
  6046. };
  6047. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6048. var gl = this._gl;
  6049. gl.bindTexture(gl.TEXTURE_2D, texture);
  6050. var magFilter = gl.NEAREST;
  6051. var minFilter = gl.NEAREST;
  6052. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6053. magFilter = gl.LINEAR;
  6054. minFilter = gl.LINEAR;
  6055. }
  6056. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6057. magFilter = gl.LINEAR;
  6058. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6059. }
  6060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6062. gl.bindTexture(gl.TEXTURE_2D, null);
  6063. texture.samplingMode = samplingMode;
  6064. };
  6065. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6066. var _this = this;
  6067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6068. if (onLoad === void 0) { onLoad = null; }
  6069. if (onError === void 0) { onError = null; }
  6070. if (buffer === void 0) { buffer = null; }
  6071. var texture = this._gl.createTexture();
  6072. var extension;
  6073. var fromData = false;
  6074. if (url.substr(0, 5) === "data:") {
  6075. fromData = true;
  6076. }
  6077. if (!fromData)
  6078. extension = url.substr(url.length - 4, 4).toLowerCase();
  6079. else {
  6080. var oldUrl = url;
  6081. fromData = oldUrl.split(':');
  6082. url = oldUrl;
  6083. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6084. }
  6085. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6086. var isTGA = (extension === ".tga");
  6087. scene._addPendingData(texture);
  6088. texture.url = url;
  6089. texture.noMipmap = noMipmap;
  6090. texture.references = 1;
  6091. texture.samplingMode = samplingMode;
  6092. this._loadedTexturesCache.push(texture);
  6093. var onerror = function () {
  6094. scene._removePendingData(texture);
  6095. if (onError) {
  6096. onError();
  6097. }
  6098. };
  6099. if (isTGA) {
  6100. var callback = function (arrayBuffer) {
  6101. var data = new Uint8Array(arrayBuffer);
  6102. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6103. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6104. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6105. if (onLoad) {
  6106. onLoad();
  6107. }
  6108. }, samplingMode);
  6109. };
  6110. if (!(fromData instanceof Array))
  6111. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6112. callback(arrayBuffer);
  6113. }, onerror, scene.database, true);
  6114. else
  6115. callback(buffer);
  6116. }
  6117. else if (isDDS) {
  6118. callback = function (data) {
  6119. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6120. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6121. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6122. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6123. if (onLoad) {
  6124. onLoad();
  6125. }
  6126. }, samplingMode);
  6127. };
  6128. if (!(fromData instanceof Array))
  6129. BABYLON.Tools.LoadFile(url, function (data) {
  6130. callback(data);
  6131. }, onerror, scene.database, true);
  6132. else
  6133. callback(buffer);
  6134. }
  6135. else {
  6136. var onload = function (img) {
  6137. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6138. var isPot = (img.width === potWidth && img.height === potHeight);
  6139. if (!isPot) {
  6140. _this._prepareWorkingCanvas();
  6141. _this._workingCanvas.width = potWidth;
  6142. _this._workingCanvas.height = potHeight;
  6143. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6144. _this._workingContext.imageSmoothingEnabled = false;
  6145. _this._workingContext.mozImageSmoothingEnabled = false;
  6146. _this._workingContext.oImageSmoothingEnabled = false;
  6147. _this._workingContext.webkitImageSmoothingEnabled = false;
  6148. _this._workingContext.msImageSmoothingEnabled = false;
  6149. }
  6150. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6151. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6152. _this._workingContext.imageSmoothingEnabled = true;
  6153. _this._workingContext.mozImageSmoothingEnabled = true;
  6154. _this._workingContext.oImageSmoothingEnabled = true;
  6155. _this._workingContext.webkitImageSmoothingEnabled = true;
  6156. _this._workingContext.msImageSmoothingEnabled = true;
  6157. }
  6158. }
  6159. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6160. if (onLoad) {
  6161. onLoad();
  6162. }
  6163. }, samplingMode);
  6164. };
  6165. if (!(fromData instanceof Array))
  6166. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6167. else
  6168. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6169. }
  6170. return texture;
  6171. };
  6172. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6173. var texture = this._gl.createTexture();
  6174. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6175. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6176. // Format
  6177. var internalFormat = this._gl.RGBA;
  6178. switch (format) {
  6179. case Engine.TEXTUREFORMAT_ALPHA:
  6180. internalFormat = this._gl.ALPHA;
  6181. break;
  6182. case Engine.TEXTUREFORMAT_LUMINANCE:
  6183. internalFormat = this._gl.LUMINANCE;
  6184. break;
  6185. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6186. internalFormat = this._gl.LUMINANCE_ALPHA;
  6187. break;
  6188. case Engine.TEXTUREFORMAT_RGB:
  6189. internalFormat = this._gl.RGB;
  6190. break;
  6191. case Engine.TEXTUREFORMAT_RGBA:
  6192. internalFormat = this._gl.RGBA;
  6193. break;
  6194. }
  6195. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6196. if (generateMipMaps) {
  6197. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6198. }
  6199. // Filters
  6200. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6201. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6202. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6203. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6204. this._activeTexturesCache = [];
  6205. texture._baseWidth = width;
  6206. texture._baseHeight = height;
  6207. texture._width = width;
  6208. texture._height = height;
  6209. texture.isReady = true;
  6210. texture.references = 1;
  6211. texture.samplingMode = samplingMode;
  6212. this._loadedTexturesCache.push(texture);
  6213. return texture;
  6214. };
  6215. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6216. var texture = this._gl.createTexture();
  6217. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6218. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6219. this._activeTexturesCache = [];
  6220. texture._baseWidth = width;
  6221. texture._baseHeight = height;
  6222. texture._width = width;
  6223. texture._height = height;
  6224. texture.isReady = false;
  6225. texture.generateMipMaps = generateMipMaps;
  6226. texture.references = 1;
  6227. texture.samplingMode = samplingMode;
  6228. this.updateTextureSamplingMode(samplingMode, texture);
  6229. this._loadedTexturesCache.push(texture);
  6230. return texture;
  6231. };
  6232. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6233. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6234. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6236. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6237. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6238. };
  6239. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6240. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6241. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6242. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6243. if (texture.generateMipMaps) {
  6244. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6245. }
  6246. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6247. this._activeTexturesCache = [];
  6248. texture.isReady = true;
  6249. };
  6250. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6251. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6252. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6253. // Scale the video if it is a NPOT using the current working canvas
  6254. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6255. if (!texture._workingCanvas) {
  6256. texture._workingCanvas = document.createElement("canvas");
  6257. texture._workingContext = texture._workingCanvas.getContext("2d");
  6258. texture._workingCanvas.width = texture._width;
  6259. texture._workingCanvas.height = texture._height;
  6260. }
  6261. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6262. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6263. }
  6264. else {
  6265. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6266. }
  6267. if (texture.generateMipMaps) {
  6268. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6269. }
  6270. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6271. this._activeTexturesCache = [];
  6272. texture.isReady = true;
  6273. };
  6274. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6275. // old version had a "generateMipMaps" arg instead of options.
  6276. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6277. // in the same way, generateDepthBuffer is defaulted to true
  6278. var generateMipMaps = false;
  6279. var generateDepthBuffer = true;
  6280. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6281. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6282. if (options !== undefined) {
  6283. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6284. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6285. type = options.type === undefined ? type : options.type;
  6286. if (options.samplingMode !== undefined) {
  6287. samplingMode = options.samplingMode;
  6288. }
  6289. if (type === Engine.TEXTURETYPE_FLOAT) {
  6290. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6291. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6292. }
  6293. }
  6294. var gl = this._gl;
  6295. var texture = gl.createTexture();
  6296. gl.bindTexture(gl.TEXTURE_2D, texture);
  6297. var width = size.width || size;
  6298. var height = size.height || size;
  6299. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6300. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6301. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6302. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6303. }
  6304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6305. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6306. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6308. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6309. var depthBuffer;
  6310. // Create the depth buffer
  6311. if (generateDepthBuffer) {
  6312. depthBuffer = gl.createRenderbuffer();
  6313. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6314. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6315. }
  6316. // Create the framebuffer
  6317. var framebuffer = gl.createFramebuffer();
  6318. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6319. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6320. if (generateDepthBuffer) {
  6321. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6322. }
  6323. // Unbind
  6324. gl.bindTexture(gl.TEXTURE_2D, null);
  6325. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6326. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6327. texture._framebuffer = framebuffer;
  6328. if (generateDepthBuffer) {
  6329. texture._depthBuffer = depthBuffer;
  6330. }
  6331. texture._width = width;
  6332. texture._height = height;
  6333. texture.isReady = true;
  6334. texture.generateMipMaps = generateMipMaps;
  6335. texture.references = 1;
  6336. texture.samplingMode = samplingMode;
  6337. this._activeTexturesCache = [];
  6338. this._loadedTexturesCache.push(texture);
  6339. return texture;
  6340. };
  6341. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6342. var _this = this;
  6343. var gl = this._gl;
  6344. var texture = gl.createTexture();
  6345. texture.isCube = true;
  6346. texture.url = rootUrl;
  6347. texture.references = 1;
  6348. this._loadedTexturesCache.push(texture);
  6349. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6350. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6351. if (isDDS) {
  6352. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6353. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6354. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6355. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6357. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6358. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6359. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6360. }
  6361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6365. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6366. _this._activeTexturesCache = [];
  6367. texture._width = info.width;
  6368. texture._height = info.height;
  6369. texture.isReady = true;
  6370. }, null, null, true);
  6371. }
  6372. else {
  6373. cascadeLoad(rootUrl, scene, function (imgs) {
  6374. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6375. var height = width;
  6376. _this._prepareWorkingCanvas();
  6377. _this._workingCanvas.width = width;
  6378. _this._workingCanvas.height = height;
  6379. var faces = [
  6380. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6381. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6382. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6383. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6384. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6385. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6386. ];
  6387. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6388. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6389. for (var index = 0; index < faces.length; index++) {
  6390. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6391. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6392. }
  6393. if (!noMipmap) {
  6394. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6395. }
  6396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6400. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6401. _this._activeTexturesCache = [];
  6402. texture._width = width;
  6403. texture._height = height;
  6404. texture.isReady = true;
  6405. }, extensions);
  6406. }
  6407. return texture;
  6408. };
  6409. Engine.prototype._releaseTexture = function (texture) {
  6410. var gl = this._gl;
  6411. if (texture._framebuffer) {
  6412. gl.deleteFramebuffer(texture._framebuffer);
  6413. }
  6414. if (texture._depthBuffer) {
  6415. gl.deleteRenderbuffer(texture._depthBuffer);
  6416. }
  6417. gl.deleteTexture(texture);
  6418. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6419. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6420. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6421. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6422. this._activeTexturesCache[channel] = null;
  6423. }
  6424. var index = this._loadedTexturesCache.indexOf(texture);
  6425. if (index !== -1) {
  6426. this._loadedTexturesCache.splice(index, 1);
  6427. }
  6428. };
  6429. Engine.prototype.bindSamplers = function (effect) {
  6430. this._gl.useProgram(effect.getProgram());
  6431. var samplers = effect.getSamplers();
  6432. for (var index = 0; index < samplers.length; index++) {
  6433. var uniform = effect.getUniform(samplers[index]);
  6434. this._gl.uniform1i(uniform, index);
  6435. }
  6436. this._currentEffect = null;
  6437. };
  6438. Engine.prototype._bindTexture = function (channel, texture) {
  6439. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6440. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6441. this._activeTexturesCache[channel] = null;
  6442. };
  6443. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6444. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6445. };
  6446. Engine.prototype.setTexture = function (channel, texture) {
  6447. if (channel < 0) {
  6448. return;
  6449. }
  6450. // Not ready?
  6451. if (!texture || !texture.isReady()) {
  6452. if (this._activeTexturesCache[channel] != null) {
  6453. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6454. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6455. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6456. this._activeTexturesCache[channel] = null;
  6457. }
  6458. return;
  6459. }
  6460. // Video
  6461. if (texture instanceof BABYLON.VideoTexture) {
  6462. if (texture.update()) {
  6463. this._activeTexturesCache[channel] = null;
  6464. }
  6465. }
  6466. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6467. texture.delayLoad();
  6468. return;
  6469. }
  6470. if (this._activeTexturesCache[channel] === texture) {
  6471. return;
  6472. }
  6473. this._activeTexturesCache[channel] = texture;
  6474. var internalTexture = texture.getInternalTexture();
  6475. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6476. if (internalTexture.isCube) {
  6477. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6478. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6479. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6480. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6481. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6482. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6483. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6484. }
  6485. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6486. }
  6487. else {
  6488. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6489. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6490. internalTexture._cachedWrapU = texture.wrapU;
  6491. switch (texture.wrapU) {
  6492. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6493. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6494. break;
  6495. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6496. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6497. break;
  6498. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6499. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6500. break;
  6501. }
  6502. }
  6503. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6504. internalTexture._cachedWrapV = texture.wrapV;
  6505. switch (texture.wrapV) {
  6506. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6507. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6508. break;
  6509. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6510. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6511. break;
  6512. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6513. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6514. break;
  6515. }
  6516. }
  6517. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6518. }
  6519. };
  6520. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6521. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6522. var value = texture.anisotropicFilteringLevel;
  6523. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6524. value = 1;
  6525. }
  6526. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6527. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6528. texture._cachedAnisotropicFilteringLevel = value;
  6529. }
  6530. };
  6531. Engine.prototype.readPixels = function (x, y, width, height) {
  6532. var data = new Uint8Array(height * width * 4);
  6533. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6534. return data;
  6535. };
  6536. // Dispose
  6537. Engine.prototype.dispose = function () {
  6538. this.hideLoadingUI();
  6539. this.stopRenderLoop();
  6540. while (this.scenes.length) {
  6541. this.scenes[0].dispose();
  6542. }
  6543. // Release audio engine
  6544. Engine.audioEngine.dispose();
  6545. for (var name in this._compiledEffects) {
  6546. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6547. }
  6548. for (var i in this._vertexAttribArrays) {
  6549. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6550. continue;
  6551. }
  6552. this._gl.disableVertexAttribArray(i);
  6553. }
  6554. // Events
  6555. window.removeEventListener("blur", this._onBlur);
  6556. window.removeEventListener("focus", this._onFocus);
  6557. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6558. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6559. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6560. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6561. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6562. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6563. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6564. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6565. };
  6566. // Loading screen
  6567. Engine.prototype.displayLoadingUI = function () {
  6568. var _this = this;
  6569. this._loadingDiv = document.createElement("div");
  6570. this._loadingDiv.style.opacity = "0";
  6571. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6572. // Loading text
  6573. this._loadingTextDiv = document.createElement("div");
  6574. this._loadingTextDiv.style.position = "absolute";
  6575. this._loadingTextDiv.style.left = "0";
  6576. this._loadingTextDiv.style.top = "50%";
  6577. this._loadingTextDiv.style.marginTop = "80px";
  6578. this._loadingTextDiv.style.width = "100%";
  6579. this._loadingTextDiv.style.height = "20px";
  6580. this._loadingTextDiv.style.fontFamily = "Arial";
  6581. this._loadingTextDiv.style.fontSize = "14px";
  6582. this._loadingTextDiv.style.color = "white";
  6583. this._loadingTextDiv.style.textAlign = "center";
  6584. this._loadingTextDiv.innerHTML = "Loading";
  6585. this._loadingDiv.appendChild(this._loadingTextDiv);
  6586. // Loading img
  6587. var imgBack = new Image();
  6588. 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==";
  6589. imgBack.style.position = "absolute";
  6590. imgBack.style.left = "50%";
  6591. imgBack.style.top = "50%";
  6592. imgBack.style.marginLeft = "-50px";
  6593. imgBack.style.marginTop = "-50px";
  6594. imgBack.style.transition = "transform 1.0s ease";
  6595. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6596. var deg = 360;
  6597. var onTransitionEnd = function () {
  6598. deg += 360;
  6599. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6600. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6601. };
  6602. imgBack.addEventListener("transitionend", onTransitionEnd);
  6603. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6604. this._loadingDiv.appendChild(imgBack);
  6605. // front image
  6606. var imgFront = new Image();
  6607. 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=";
  6608. imgFront.style.position = "absolute";
  6609. imgFront.style.left = "50%";
  6610. imgFront.style.top = "50%";
  6611. imgFront.style.marginLeft = "-50px";
  6612. imgFront.style.marginTop = "-50px";
  6613. this._loadingDiv.appendChild(imgFront);
  6614. // Resize
  6615. this._resizeLoadingUI = function () {
  6616. var canvasRect = _this.getRenderingCanvasClientRect();
  6617. _this._loadingDiv.style.position = "absolute";
  6618. _this._loadingDiv.style.left = canvasRect.left + "px";
  6619. _this._loadingDiv.style.top = canvasRect.top + "px";
  6620. _this._loadingDiv.style.width = canvasRect.width + "px";
  6621. _this._loadingDiv.style.height = canvasRect.height + "px";
  6622. };
  6623. this._resizeLoadingUI();
  6624. window.addEventListener("resize", this._resizeLoadingUI);
  6625. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6626. document.body.appendChild(this._loadingDiv);
  6627. setTimeout(function () {
  6628. _this._loadingDiv.style.opacity = "1";
  6629. imgBack.style.transform = "rotateZ(360deg)";
  6630. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6631. }, 0);
  6632. };
  6633. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6634. set: function (text) {
  6635. if (!this._loadingDiv) {
  6636. return;
  6637. }
  6638. this._loadingTextDiv.innerHTML = text;
  6639. },
  6640. enumerable: true,
  6641. configurable: true
  6642. });
  6643. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6644. get: function () {
  6645. return this._loadingDivBackgroundColor;
  6646. },
  6647. set: function (color) {
  6648. this._loadingDivBackgroundColor = color;
  6649. if (!this._loadingDiv) {
  6650. return;
  6651. }
  6652. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6653. },
  6654. enumerable: true,
  6655. configurable: true
  6656. });
  6657. Engine.prototype.hideLoadingUI = function () {
  6658. var _this = this;
  6659. if (!this._loadingDiv) {
  6660. return;
  6661. }
  6662. var onTransitionEnd = function () {
  6663. if (!_this._loadingDiv) {
  6664. return;
  6665. }
  6666. document.body.removeChild(_this._loadingDiv);
  6667. window.removeEventListener("resize", _this._resizeLoadingUI);
  6668. _this._loadingDiv = null;
  6669. };
  6670. this._loadingDiv.style.opacity = "0";
  6671. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6672. };
  6673. // FPS
  6674. Engine.prototype.getFps = function () {
  6675. return this.fps;
  6676. };
  6677. Engine.prototype.getDeltaTime = function () {
  6678. return this.deltaTime;
  6679. };
  6680. Engine.prototype._measureFps = function () {
  6681. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6682. var length = this.previousFramesDuration.length;
  6683. if (length >= 2) {
  6684. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6685. }
  6686. if (length >= this.fpsRange) {
  6687. if (length > this.fpsRange) {
  6688. this.previousFramesDuration.splice(0, 1);
  6689. length = this.previousFramesDuration.length;
  6690. }
  6691. var sum = 0;
  6692. for (var id = 0; id < length - 1; id++) {
  6693. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6694. }
  6695. this.fps = 1000.0 / (sum / (length - 1));
  6696. }
  6697. };
  6698. // Statics
  6699. Engine.isSupported = function () {
  6700. try {
  6701. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6702. if (navigator.isCocoonJS) {
  6703. return true;
  6704. }
  6705. var tempcanvas = document.createElement("canvas");
  6706. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6707. return gl != null && !!window.WebGLRenderingContext;
  6708. }
  6709. catch (e) {
  6710. return false;
  6711. }
  6712. };
  6713. // Const statics
  6714. Engine._ALPHA_DISABLE = 0;
  6715. Engine._ALPHA_ADD = 1;
  6716. Engine._ALPHA_COMBINE = 2;
  6717. Engine._DELAYLOADSTATE_NONE = 0;
  6718. Engine._DELAYLOADSTATE_LOADED = 1;
  6719. Engine._DELAYLOADSTATE_LOADING = 2;
  6720. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6721. Engine._TEXTUREFORMAT_ALPHA = 0;
  6722. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6723. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6724. Engine._TEXTUREFORMAT_RGB = 4;
  6725. Engine._TEXTUREFORMAT_RGBA = 4;
  6726. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6727. Engine._TEXTURETYPE_FLOAT = 1;
  6728. // Updatable statics so stick with vars here
  6729. Engine.Epsilon = 0.001;
  6730. Engine.CollisionsEpsilon = 0.001;
  6731. Engine.CodeRepository = "Babylon/";
  6732. Engine.ShadersRepository = "Babylon/Shaders/";
  6733. return Engine;
  6734. })();
  6735. BABYLON.Engine = Engine;
  6736. })(BABYLON || (BABYLON = {}));
  6737. //# sourceMappingURL=babylon.engine.js.map
  6738. var BABYLON;
  6739. (function (BABYLON) {
  6740. /**
  6741. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6742. */
  6743. var Node = (function () {
  6744. /**
  6745. * @constructor
  6746. * @param {string} name - the name and id to be given to this node
  6747. * @param {BABYLON.Scene} the scene this node will be added to
  6748. */
  6749. function Node(name, scene) {
  6750. this.state = "";
  6751. this.animations = new Array();
  6752. this._childrenFlag = -1;
  6753. this._isEnabled = true;
  6754. this._isReady = true;
  6755. this._currentRenderId = -1;
  6756. this._parentRenderId = -1;
  6757. this.name = name;
  6758. this.id = name;
  6759. this._scene = scene;
  6760. this._initCache();
  6761. }
  6762. Node.prototype.getScene = function () {
  6763. return this._scene;
  6764. };
  6765. Node.prototype.getEngine = function () {
  6766. return this._scene.getEngine();
  6767. };
  6768. // override it in derived class
  6769. Node.prototype.getWorldMatrix = function () {
  6770. return BABYLON.Matrix.Identity();
  6771. };
  6772. // override it in derived class if you add new variables to the cache
  6773. // and call the parent class method
  6774. Node.prototype._initCache = function () {
  6775. this._cache = {};
  6776. this._cache.parent = undefined;
  6777. };
  6778. Node.prototype.updateCache = function (force) {
  6779. if (!force && this.isSynchronized())
  6780. return;
  6781. this._cache.parent = this.parent;
  6782. this._updateCache();
  6783. };
  6784. // override it in derived class if you add new variables to the cache
  6785. // and call the parent class method if !ignoreParentClass
  6786. Node.prototype._updateCache = function (ignoreParentClass) {
  6787. };
  6788. // override it in derived class if you add new variables to the cache
  6789. Node.prototype._isSynchronized = function () {
  6790. return true;
  6791. };
  6792. Node.prototype._markSyncedWithParent = function () {
  6793. this._parentRenderId = this.parent._currentRenderId;
  6794. };
  6795. Node.prototype.isSynchronizedWithParent = function () {
  6796. if (!this.parent) {
  6797. return true;
  6798. }
  6799. if (this._parentRenderId !== this.parent._currentRenderId) {
  6800. return false;
  6801. }
  6802. return this.parent.isSynchronized();
  6803. };
  6804. Node.prototype.isSynchronized = function (updateCache) {
  6805. var check = this.hasNewParent();
  6806. check = check || !this.isSynchronizedWithParent();
  6807. check = check || !this._isSynchronized();
  6808. if (updateCache)
  6809. this.updateCache(true);
  6810. return !check;
  6811. };
  6812. Node.prototype.hasNewParent = function (update) {
  6813. if (this._cache.parent === this.parent)
  6814. return false;
  6815. if (update)
  6816. this._cache.parent = this.parent;
  6817. return true;
  6818. };
  6819. /**
  6820. * Is this node ready to be used/rendered
  6821. * @return {boolean} is it ready
  6822. */
  6823. Node.prototype.isReady = function () {
  6824. return this._isReady;
  6825. };
  6826. /**
  6827. * Is this node enabled.
  6828. * If the node has a parent and is enabled, the parent will be inspected as well.
  6829. * @return {boolean} whether this node (and its parent) is enabled.
  6830. * @see setEnabled
  6831. */
  6832. Node.prototype.isEnabled = function () {
  6833. if (!this._isEnabled) {
  6834. return false;
  6835. }
  6836. if (this.parent) {
  6837. return this.parent.isEnabled();
  6838. }
  6839. return true;
  6840. };
  6841. /**
  6842. * Set the enabled state of this node.
  6843. * @param {boolean} value - the new enabled state
  6844. * @see isEnabled
  6845. */
  6846. Node.prototype.setEnabled = function (value) {
  6847. this._isEnabled = value;
  6848. };
  6849. /**
  6850. * Is this node a descendant of the given node.
  6851. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6852. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6853. * @see parent
  6854. */
  6855. Node.prototype.isDescendantOf = function (ancestor) {
  6856. if (this.parent) {
  6857. if (this.parent === ancestor) {
  6858. return true;
  6859. }
  6860. return this.parent.isDescendantOf(ancestor);
  6861. }
  6862. return false;
  6863. };
  6864. Node.prototype._getDescendants = function (list, results) {
  6865. for (var index = 0; index < list.length; index++) {
  6866. var item = list[index];
  6867. if (item.isDescendantOf(this)) {
  6868. results.push(item);
  6869. }
  6870. }
  6871. };
  6872. /**
  6873. * Will return all nodes that have this node as parent.
  6874. * @return {BABYLON.Node[]} all children nodes of all types.
  6875. */
  6876. Node.prototype.getDescendants = function () {
  6877. var results = [];
  6878. this._getDescendants(this._scene.meshes, results);
  6879. this._getDescendants(this._scene.lights, results);
  6880. this._getDescendants(this._scene.cameras, results);
  6881. return results;
  6882. };
  6883. Node.prototype._setReady = function (state) {
  6884. if (state == this._isReady) {
  6885. return;
  6886. }
  6887. if (!state) {
  6888. this._isReady = false;
  6889. return;
  6890. }
  6891. this._isReady = true;
  6892. if (this.onReady) {
  6893. this.onReady(this);
  6894. }
  6895. };
  6896. return Node;
  6897. })();
  6898. BABYLON.Node = Node;
  6899. })(BABYLON || (BABYLON = {}));
  6900. //# sourceMappingURL=babylon.node.js.map
  6901. var BABYLON;
  6902. (function (BABYLON) {
  6903. var FilesInput = (function () {
  6904. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6905. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6906. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6907. this._engine = p_engine;
  6908. this._canvas = p_canvas;
  6909. this._currentScene = p_scene;
  6910. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6911. this._progressCallback = p_progressCallback;
  6912. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6913. this._textureLoadingCallback = p_textureLoadingCallback;
  6914. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6915. }
  6916. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6917. var _this = this;
  6918. if (p_elementToMonitor) {
  6919. this._elementToMonitor = p_elementToMonitor;
  6920. this._elementToMonitor.addEventListener("dragenter", function (e) {
  6921. _this.drag(e);
  6922. }, false);
  6923. this._elementToMonitor.addEventListener("dragover", function (e) {
  6924. _this.drag(e);
  6925. }, false);
  6926. this._elementToMonitor.addEventListener("drop", function (e) {
  6927. _this.drop(e);
  6928. }, false);
  6929. }
  6930. };
  6931. FilesInput.prototype.renderFunction = function () {
  6932. if (this._additionnalRenderLoopLogicCallback) {
  6933. this._additionnalRenderLoopLogicCallback();
  6934. }
  6935. if (this._currentScene) {
  6936. if (this._textureLoadingCallback) {
  6937. var remaining = this._currentScene.getWaitingItemsCount();
  6938. if (remaining > 0) {
  6939. this._textureLoadingCallback(remaining);
  6940. }
  6941. }
  6942. this._currentScene.render();
  6943. }
  6944. };
  6945. FilesInput.prototype.drag = function (e) {
  6946. e.stopPropagation();
  6947. e.preventDefault();
  6948. };
  6949. FilesInput.prototype.drop = function (eventDrop) {
  6950. eventDrop.stopPropagation();
  6951. eventDrop.preventDefault();
  6952. this.loadFiles(eventDrop);
  6953. };
  6954. FilesInput.prototype.loadFiles = function (event) {
  6955. if (this._startingProcessingFilesCallback)
  6956. this._startingProcessingFilesCallback();
  6957. // Handling data transfer via drag'n'drop
  6958. if (event && event.dataTransfer && event.dataTransfer.files) {
  6959. this._filesToLoad = event.dataTransfer.files;
  6960. }
  6961. // Handling files from input files
  6962. if (event && event.target && event.target.files) {
  6963. this._filesToLoad = event.target.files;
  6964. }
  6965. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6966. for (var i = 0; i < this._filesToLoad.length; i++) {
  6967. switch (this._filesToLoad[i].type) {
  6968. case "image/jpeg":
  6969. case "image/png":
  6970. case "image/bmp":
  6971. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6972. break;
  6973. case "image/targa":
  6974. case "image/vnd.ms-dds":
  6975. case "audio/wav":
  6976. case "audio/x-wav":
  6977. case "audio/mp3":
  6978. case "audio/mpeg":
  6979. case "audio/mpeg3":
  6980. case "audio/x-mpeg-3":
  6981. case "audio/ogg":
  6982. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6983. break;
  6984. default:
  6985. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  6986. this._sceneFileToLoad = this._filesToLoad[i];
  6987. }
  6988. break;
  6989. }
  6990. }
  6991. this.reload();
  6992. }
  6993. };
  6994. FilesInput.prototype.reload = function () {
  6995. var _this = this;
  6996. var that = this;
  6997. // If a ".babylon" file has been provided
  6998. if (this._sceneFileToLoad) {
  6999. if (this._currentScene) {
  7000. this._engine.stopRenderLoop();
  7001. this._currentScene.dispose();
  7002. }
  7003. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7004. that._currentScene = newScene;
  7005. // Wait for textures and shaders to be ready
  7006. that._currentScene.executeWhenReady(function () {
  7007. // Attach camera to canvas inputs
  7008. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7009. that._currentScene.createDefaultCameraOrLight();
  7010. }
  7011. that._currentScene.activeCamera.attachControl(that._canvas);
  7012. if (that._sceneLoadedCallback) {
  7013. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7014. }
  7015. that._engine.runRenderLoop(function () {
  7016. that.renderFunction();
  7017. });
  7018. });
  7019. }, function (progress) {
  7020. if (_this._progressCallback) {
  7021. _this._progressCallback(progress);
  7022. }
  7023. });
  7024. }
  7025. else {
  7026. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7027. }
  7028. };
  7029. FilesInput.FilesTextures = new Array();
  7030. FilesInput.FilesToLoad = new Array();
  7031. return FilesInput;
  7032. })();
  7033. BABYLON.FilesInput = FilesInput;
  7034. })(BABYLON || (BABYLON = {}));
  7035. //# sourceMappingURL=babylon.filesInput.js.map
  7036. var BABYLON;
  7037. (function (BABYLON) {
  7038. var IntersectionInfo = (function () {
  7039. function IntersectionInfo(bu, bv, distance) {
  7040. this.bu = bu;
  7041. this.bv = bv;
  7042. this.distance = distance;
  7043. this.faceId = 0;
  7044. this.subMeshId = 0;
  7045. }
  7046. return IntersectionInfo;
  7047. })();
  7048. BABYLON.IntersectionInfo = IntersectionInfo;
  7049. var PickingInfo = (function () {
  7050. function PickingInfo() {
  7051. this.hit = false;
  7052. this.distance = 0;
  7053. this.pickedPoint = null;
  7054. this.pickedMesh = null;
  7055. this.bu = 0;
  7056. this.bv = 0;
  7057. this.faceId = -1;
  7058. this.subMeshId = 0;
  7059. }
  7060. // Methods
  7061. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7062. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7063. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7064. return null;
  7065. }
  7066. var indices = this.pickedMesh.getIndices();
  7067. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7068. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7069. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7070. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7071. normal0 = normal0.scale(this.bu);
  7072. normal1 = normal1.scale(this.bv);
  7073. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7074. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7075. if (useWorldCoordinates) {
  7076. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7077. }
  7078. return result;
  7079. };
  7080. PickingInfo.prototype.getTextureCoordinates = function () {
  7081. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7082. return null;
  7083. }
  7084. var indices = this.pickedMesh.getIndices();
  7085. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7086. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7087. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7088. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7089. uv0 = uv0.scale(this.bu);
  7090. uv1 = uv1.scale(this.bv);
  7091. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7092. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7093. };
  7094. return PickingInfo;
  7095. })();
  7096. BABYLON.PickingInfo = PickingInfo;
  7097. })(BABYLON || (BABYLON = {}));
  7098. //# sourceMappingURL=babylon.pickingInfo.js.map
  7099. var BABYLON;
  7100. (function (BABYLON) {
  7101. var BoundingSphere = (function () {
  7102. function BoundingSphere(minimum, maximum) {
  7103. this.minimum = minimum;
  7104. this.maximum = maximum;
  7105. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7106. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7107. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7108. this.radius = distance * 0.5;
  7109. this.centerWorld = BABYLON.Vector3.Zero();
  7110. this._update(BABYLON.Matrix.Identity());
  7111. }
  7112. // Methods
  7113. BoundingSphere.prototype._update = function (world) {
  7114. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7115. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7116. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7117. };
  7118. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7119. for (var i = 0; i < 6; i++) {
  7120. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7121. return false;
  7122. }
  7123. return true;
  7124. };
  7125. BoundingSphere.prototype.intersectsPoint = function (point) {
  7126. var x = this.centerWorld.x - point.x;
  7127. var y = this.centerWorld.y - point.y;
  7128. var z = this.centerWorld.z - point.z;
  7129. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7130. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7131. return false;
  7132. return true;
  7133. };
  7134. // Statics
  7135. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7136. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7137. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7138. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7139. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7140. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7141. return false;
  7142. return true;
  7143. };
  7144. return BoundingSphere;
  7145. })();
  7146. BABYLON.BoundingSphere = BoundingSphere;
  7147. })(BABYLON || (BABYLON = {}));
  7148. //# sourceMappingURL=babylon.boundingSphere.js.map
  7149. var BABYLON;
  7150. (function (BABYLON) {
  7151. var BoundingBox = (function () {
  7152. function BoundingBox(minimum, maximum) {
  7153. this.minimum = minimum;
  7154. this.maximum = maximum;
  7155. this.vectors = new Array();
  7156. this.vectorsWorld = new Array();
  7157. // Bounding vectors
  7158. this.vectors.push(this.minimum.clone());
  7159. this.vectors.push(this.maximum.clone());
  7160. this.vectors.push(this.minimum.clone());
  7161. this.vectors[2].x = this.maximum.x;
  7162. this.vectors.push(this.minimum.clone());
  7163. this.vectors[3].y = this.maximum.y;
  7164. this.vectors.push(this.minimum.clone());
  7165. this.vectors[4].z = this.maximum.z;
  7166. this.vectors.push(this.maximum.clone());
  7167. this.vectors[5].z = this.minimum.z;
  7168. this.vectors.push(this.maximum.clone());
  7169. this.vectors[6].x = this.minimum.x;
  7170. this.vectors.push(this.maximum.clone());
  7171. this.vectors[7].y = this.minimum.y;
  7172. // OBB
  7173. this.center = this.maximum.add(this.minimum).scale(0.5);
  7174. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7175. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7176. for (var index = 0; index < this.vectors.length; index++) {
  7177. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7178. }
  7179. this.minimumWorld = BABYLON.Vector3.Zero();
  7180. this.maximumWorld = BABYLON.Vector3.Zero();
  7181. this._update(BABYLON.Matrix.Identity());
  7182. }
  7183. // Methods
  7184. BoundingBox.prototype.getWorldMatrix = function () {
  7185. return this._worldMatrix;
  7186. };
  7187. BoundingBox.prototype._update = function (world) {
  7188. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7189. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7190. for (var index = 0; index < this.vectors.length; index++) {
  7191. var v = this.vectorsWorld[index];
  7192. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7193. if (v.x < this.minimumWorld.x)
  7194. this.minimumWorld.x = v.x;
  7195. if (v.y < this.minimumWorld.y)
  7196. this.minimumWorld.y = v.y;
  7197. if (v.z < this.minimumWorld.z)
  7198. this.minimumWorld.z = v.z;
  7199. if (v.x > this.maximumWorld.x)
  7200. this.maximumWorld.x = v.x;
  7201. if (v.y > this.maximumWorld.y)
  7202. this.maximumWorld.y = v.y;
  7203. if (v.z > this.maximumWorld.z)
  7204. this.maximumWorld.z = v.z;
  7205. }
  7206. // OBB
  7207. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7208. this.center.scaleInPlace(0.5);
  7209. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7210. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7211. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7212. this._worldMatrix = world;
  7213. };
  7214. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7215. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7216. };
  7217. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7218. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7219. };
  7220. BoundingBox.prototype.intersectsPoint = function (point) {
  7221. var delta = -BABYLON.Engine.Epsilon;
  7222. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7223. return false;
  7224. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7225. return false;
  7226. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7227. return false;
  7228. return true;
  7229. };
  7230. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7231. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7232. };
  7233. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7234. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7235. return false;
  7236. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7237. return false;
  7238. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7239. return false;
  7240. return true;
  7241. };
  7242. // Statics
  7243. BoundingBox.Intersects = function (box0, box1) {
  7244. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7245. return false;
  7246. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7247. return false;
  7248. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7249. return false;
  7250. return true;
  7251. };
  7252. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7253. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7254. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7255. return (num <= (sphereRadius * sphereRadius));
  7256. };
  7257. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7258. for (var p = 0; p < 6; p++) {
  7259. for (var i = 0; i < 8; i++) {
  7260. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7261. return false;
  7262. }
  7263. }
  7264. }
  7265. return true;
  7266. };
  7267. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7268. for (var p = 0; p < 6; p++) {
  7269. var inCount = 8;
  7270. for (var i = 0; i < 8; i++) {
  7271. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7272. --inCount;
  7273. }
  7274. else {
  7275. break;
  7276. }
  7277. }
  7278. if (inCount === 0)
  7279. return false;
  7280. }
  7281. return true;
  7282. };
  7283. return BoundingBox;
  7284. })();
  7285. BABYLON.BoundingBox = BoundingBox;
  7286. })(BABYLON || (BABYLON = {}));
  7287. //# sourceMappingURL=babylon.boundingBox.js.map
  7288. var BABYLON;
  7289. (function (BABYLON) {
  7290. var computeBoxExtents = function (axis, box) {
  7291. var p = BABYLON.Vector3.Dot(box.center, axis);
  7292. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7293. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7294. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7295. var r = r0 + r1 + r2;
  7296. return {
  7297. min: p - r,
  7298. max: p + r
  7299. };
  7300. };
  7301. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7302. var axisOverlap = function (axis, box0, box1) {
  7303. var result0 = computeBoxExtents(axis, box0);
  7304. var result1 = computeBoxExtents(axis, box1);
  7305. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7306. };
  7307. var BoundingInfo = (function () {
  7308. function BoundingInfo(minimum, maximum) {
  7309. this.minimum = minimum;
  7310. this.maximum = maximum;
  7311. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7312. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7313. }
  7314. // Methods
  7315. BoundingInfo.prototype._update = function (world) {
  7316. this.boundingBox._update(world);
  7317. this.boundingSphere._update(world);
  7318. };
  7319. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7320. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7321. return false;
  7322. return this.boundingBox.isInFrustum(frustumPlanes);
  7323. };
  7324. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7325. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7326. };
  7327. BoundingInfo.prototype._checkCollision = function (collider) {
  7328. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7329. };
  7330. BoundingInfo.prototype.intersectsPoint = function (point) {
  7331. if (!this.boundingSphere.centerWorld) {
  7332. return false;
  7333. }
  7334. if (!this.boundingSphere.intersectsPoint(point)) {
  7335. return false;
  7336. }
  7337. if (!this.boundingBox.intersectsPoint(point)) {
  7338. return false;
  7339. }
  7340. return true;
  7341. };
  7342. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7343. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7344. return false;
  7345. }
  7346. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7347. return false;
  7348. }
  7349. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7350. return false;
  7351. }
  7352. if (!precise) {
  7353. return true;
  7354. }
  7355. var box0 = this.boundingBox;
  7356. var box1 = boundingInfo.boundingBox;
  7357. if (!axisOverlap(box0.directions[0], box0, box1))
  7358. return false;
  7359. if (!axisOverlap(box0.directions[1], box0, box1))
  7360. return false;
  7361. if (!axisOverlap(box0.directions[2], box0, box1))
  7362. return false;
  7363. if (!axisOverlap(box1.directions[0], box0, box1))
  7364. return false;
  7365. if (!axisOverlap(box1.directions[1], box0, box1))
  7366. return false;
  7367. if (!axisOverlap(box1.directions[2], box0, box1))
  7368. return false;
  7369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7370. return false;
  7371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7372. return false;
  7373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7374. return false;
  7375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7376. return false;
  7377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7378. return false;
  7379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7380. return false;
  7381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7382. return false;
  7383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7384. return false;
  7385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7386. return false;
  7387. return true;
  7388. };
  7389. return BoundingInfo;
  7390. })();
  7391. BABYLON.BoundingInfo = BoundingInfo;
  7392. })(BABYLON || (BABYLON = {}));
  7393. //# sourceMappingURL=babylon.boundingInfo.js.map
  7394. var __extends = this.__extends || function (d, b) {
  7395. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7396. function __() { this.constructor = d; }
  7397. __.prototype = b.prototype;
  7398. d.prototype = new __();
  7399. };
  7400. var BABYLON;
  7401. (function (BABYLON) {
  7402. var AbstractMesh = (function (_super) {
  7403. __extends(AbstractMesh, _super);
  7404. function AbstractMesh(name, scene) {
  7405. var _this = this;
  7406. _super.call(this, name, scene);
  7407. // Properties
  7408. this.definedFacingForward = true; // orientation for POV movement & rotation
  7409. this.position = new BABYLON.Vector3(0, 0, 0);
  7410. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7411. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7412. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7413. this.visibility = 1.0;
  7414. this.alphaIndex = Number.MAX_VALUE;
  7415. this.infiniteDistance = false;
  7416. this.isVisible = true;
  7417. this.isPickable = true;
  7418. this.showBoundingBox = false;
  7419. this.showSubMeshesBoundingBox = false;
  7420. this.onDispose = null;
  7421. this.checkCollisions = false;
  7422. this.isBlocker = false;
  7423. this.renderingGroupId = 0;
  7424. this.receiveShadows = false;
  7425. this.renderOutline = false;
  7426. this.outlineColor = BABYLON.Color3.Red();
  7427. this.outlineWidth = 0.02;
  7428. this.renderOverlay = false;
  7429. this.overlayColor = BABYLON.Color3.Red();
  7430. this.overlayAlpha = 0.5;
  7431. this.hasVertexAlpha = false;
  7432. this.useVertexColors = true;
  7433. this.applyFog = true;
  7434. this.useOctreeForRenderingSelection = true;
  7435. this.useOctreeForPicking = true;
  7436. this.useOctreeForCollisions = true;
  7437. this.layerMask = 0x0FFFFFFF;
  7438. this.alwaysSelectAsActiveMesh = false;
  7439. // Physics
  7440. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7441. // Collisions
  7442. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7443. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7444. this._collider = new BABYLON.Collider();
  7445. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7446. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7447. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7448. // Cache
  7449. this._localScaling = BABYLON.Matrix.Zero();
  7450. this._localRotation = BABYLON.Matrix.Zero();
  7451. this._localTranslation = BABYLON.Matrix.Zero();
  7452. this._localBillboard = BABYLON.Matrix.Zero();
  7453. this._localPivotScaling = BABYLON.Matrix.Zero();
  7454. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7455. this._localWorld = BABYLON.Matrix.Zero();
  7456. this._worldMatrix = BABYLON.Matrix.Zero();
  7457. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7458. this._absolutePosition = BABYLON.Vector3.Zero();
  7459. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7460. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7461. this._isDirty = false;
  7462. this._pivotMatrix = BABYLON.Matrix.Identity();
  7463. this._isDisposed = false;
  7464. this._renderId = 0;
  7465. this._intersectionsInProgress = new Array();
  7466. this._onAfterWorldMatrixUpdate = new Array();
  7467. this._isWorldMatrixFrozen = false;
  7468. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7469. if (collidedMesh === void 0) { collidedMesh = null; }
  7470. //TODO move this to the collision coordinator!
  7471. if (collisionId != null || collisionId != undefined)
  7472. newPosition.multiplyInPlace(_this._collider.radius);
  7473. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7474. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7475. _this.position.addInPlace(_this._diffPositionForCollisions);
  7476. }
  7477. };
  7478. scene.addMesh(this);
  7479. }
  7480. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7481. get: function () {
  7482. return AbstractMesh._BILLBOARDMODE_NONE;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7488. get: function () {
  7489. return AbstractMesh._BILLBOARDMODE_X;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7495. get: function () {
  7496. return AbstractMesh._BILLBOARDMODE_Y;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7502. get: function () {
  7503. return AbstractMesh._BILLBOARDMODE_Z;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7509. get: function () {
  7510. return AbstractMesh._BILLBOARDMODE_ALL;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7516. // Methods
  7517. get: function () {
  7518. return false;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. AbstractMesh.prototype.getLOD = function (camera) {
  7524. return this;
  7525. };
  7526. AbstractMesh.prototype.getTotalVertices = function () {
  7527. return 0;
  7528. };
  7529. AbstractMesh.prototype.getIndices = function () {
  7530. return null;
  7531. };
  7532. AbstractMesh.prototype.getVerticesData = function (kind) {
  7533. return null;
  7534. };
  7535. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7536. return false;
  7537. };
  7538. AbstractMesh.prototype.getBoundingInfo = function () {
  7539. if (this._masterMesh) {
  7540. return this._masterMesh.getBoundingInfo();
  7541. }
  7542. if (!this._boundingInfo) {
  7543. this._updateBoundingInfo();
  7544. }
  7545. return this._boundingInfo;
  7546. };
  7547. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7548. get: function () {
  7549. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. AbstractMesh.prototype._preActivate = function () {
  7555. };
  7556. AbstractMesh.prototype._activate = function (renderId) {
  7557. this._renderId = renderId;
  7558. };
  7559. AbstractMesh.prototype.getWorldMatrix = function () {
  7560. if (this._masterMesh) {
  7561. return this._masterMesh.getWorldMatrix();
  7562. }
  7563. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7564. this.computeWorldMatrix();
  7565. }
  7566. return this._worldMatrix;
  7567. };
  7568. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7569. get: function () {
  7570. return this._worldMatrix;
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7576. get: function () {
  7577. return this._absolutePosition;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7583. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7584. this.computeWorldMatrix(true);
  7585. this._isWorldMatrixFrozen = true;
  7586. };
  7587. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7588. this._isWorldMatrixFrozen = false;
  7589. this.computeWorldMatrix(true);
  7590. };
  7591. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7592. get: function () {
  7593. return this._isWorldMatrixFrozen;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7599. if (!this.rotationQuaternion) {
  7600. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7601. this.rotation = BABYLON.Vector3.Zero();
  7602. }
  7603. if (!space || space === 0 /* LOCAL */) {
  7604. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7605. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7606. }
  7607. else {
  7608. if (this.parent) {
  7609. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7610. invertParentWorldMatrix.invert();
  7611. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7612. }
  7613. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7614. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7615. }
  7616. };
  7617. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7618. var displacementVector = axis.scale(distance);
  7619. if (!space || space === 0 /* LOCAL */) {
  7620. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7621. this.setPositionWithLocalVector(tempV3);
  7622. }
  7623. else {
  7624. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7625. }
  7626. };
  7627. AbstractMesh.prototype.getAbsolutePosition = function () {
  7628. this.computeWorldMatrix();
  7629. return this._absolutePosition;
  7630. };
  7631. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7632. if (!absolutePosition) {
  7633. return;
  7634. }
  7635. var absolutePositionX;
  7636. var absolutePositionY;
  7637. var absolutePositionZ;
  7638. if (absolutePosition.x === undefined) {
  7639. if (arguments.length < 3) {
  7640. return;
  7641. }
  7642. absolutePositionX = arguments[0];
  7643. absolutePositionY = arguments[1];
  7644. absolutePositionZ = arguments[2];
  7645. }
  7646. else {
  7647. absolutePositionX = absolutePosition.x;
  7648. absolutePositionY = absolutePosition.y;
  7649. absolutePositionZ = absolutePosition.z;
  7650. }
  7651. if (this.parent) {
  7652. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7653. invertParentWorldMatrix.invert();
  7654. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7655. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7656. }
  7657. else {
  7658. this.position.x = absolutePositionX;
  7659. this.position.y = absolutePositionY;
  7660. this.position.z = absolutePositionZ;
  7661. }
  7662. };
  7663. // ================================== Point of View Movement =================================
  7664. /**
  7665. * Perform relative position change from the point of view of behind the front of the mesh.
  7666. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7667. * Supports definition of mesh facing forward or backward.
  7668. * @param {number} amountRight
  7669. * @param {number} amountUp
  7670. * @param {number} amountForward
  7671. */
  7672. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7673. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7674. };
  7675. /**
  7676. * Calculate relative position change from the point of view of behind the front of the mesh.
  7677. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7678. * Supports definition of mesh facing forward or backward.
  7679. * @param {number} amountRight
  7680. * @param {number} amountUp
  7681. * @param {number} amountForward
  7682. */
  7683. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7684. var rotMatrix = new BABYLON.Matrix();
  7685. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7686. rotQuaternion.toRotationMatrix(rotMatrix);
  7687. var translationDelta = BABYLON.Vector3.Zero();
  7688. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7690. return translationDelta;
  7691. };
  7692. // ================================== Point of View Rotation =================================
  7693. /**
  7694. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7695. * Supports definition of mesh facing forward or backward.
  7696. * @param {number} flipBack
  7697. * @param {number} twirlClockwise
  7698. * @param {number} tiltRight
  7699. */
  7700. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7701. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7702. };
  7703. /**
  7704. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7705. * Supports definition of mesh facing forward or backward.
  7706. * @param {number} flipBack
  7707. * @param {number} twirlClockwise
  7708. * @param {number} tiltRight
  7709. */
  7710. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7711. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7712. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7713. };
  7714. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7715. this._pivotMatrix = matrix;
  7716. this._cache.pivotMatrixUpdated = true;
  7717. };
  7718. AbstractMesh.prototype.getPivotMatrix = function () {
  7719. return this._pivotMatrix;
  7720. };
  7721. AbstractMesh.prototype._isSynchronized = function () {
  7722. if (this._isDirty) {
  7723. return false;
  7724. }
  7725. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7726. return false;
  7727. if (this._cache.pivotMatrixUpdated) {
  7728. return false;
  7729. }
  7730. if (this.infiniteDistance) {
  7731. return false;
  7732. }
  7733. if (!this._cache.position.equals(this.position))
  7734. return false;
  7735. if (this.rotationQuaternion) {
  7736. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7737. return false;
  7738. }
  7739. else {
  7740. if (!this._cache.rotation.equals(this.rotation))
  7741. return false;
  7742. }
  7743. if (!this._cache.scaling.equals(this.scaling))
  7744. return false;
  7745. return true;
  7746. };
  7747. AbstractMesh.prototype._initCache = function () {
  7748. _super.prototype._initCache.call(this);
  7749. this._cache.localMatrixUpdated = false;
  7750. this._cache.position = BABYLON.Vector3.Zero();
  7751. this._cache.scaling = BABYLON.Vector3.Zero();
  7752. this._cache.rotation = BABYLON.Vector3.Zero();
  7753. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7754. };
  7755. AbstractMesh.prototype.markAsDirty = function (property) {
  7756. if (property === "rotation") {
  7757. this.rotationQuaternion = null;
  7758. }
  7759. this._currentRenderId = Number.MAX_VALUE;
  7760. this._isDirty = true;
  7761. };
  7762. AbstractMesh.prototype._updateBoundingInfo = function () {
  7763. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7764. this._boundingInfo._update(this.worldMatrixFromCache);
  7765. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7766. };
  7767. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7768. if (!this.subMeshes) {
  7769. return;
  7770. }
  7771. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7772. var subMesh = this.subMeshes[subIndex];
  7773. subMesh.updateBoundingInfo(matrix);
  7774. }
  7775. };
  7776. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7777. if (this._isWorldMatrixFrozen) {
  7778. return this._worldMatrix;
  7779. }
  7780. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7781. return this._worldMatrix;
  7782. }
  7783. this._cache.position.copyFrom(this.position);
  7784. this._cache.scaling.copyFrom(this.scaling);
  7785. this._cache.pivotMatrixUpdated = false;
  7786. this._currentRenderId = this.getScene().getRenderId();
  7787. this._isDirty = false;
  7788. // Scaling
  7789. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7790. // Rotation
  7791. if (this.rotationQuaternion) {
  7792. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7793. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7794. }
  7795. else {
  7796. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7797. this._cache.rotation.copyFrom(this.rotation);
  7798. }
  7799. // Translation
  7800. if (this.infiniteDistance && !this.parent) {
  7801. var camera = this.getScene().activeCamera;
  7802. var cameraWorldMatrix = camera.getWorldMatrix();
  7803. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7804. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7805. }
  7806. else {
  7807. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7808. }
  7809. // Composing transformations
  7810. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7811. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7812. // Billboarding
  7813. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7814. var localPosition = this.position.clone();
  7815. var zero = this.getScene().activeCamera.globalPosition.clone();
  7816. if (this.parent && this.parent.position) {
  7817. localPosition.addInPlace(this.parent.position);
  7818. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7819. }
  7820. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7821. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7822. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7823. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7824. zero.y = localPosition.y + 0.001;
  7825. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7826. zero.z = localPosition.z + 0.001;
  7827. }
  7828. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7829. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7830. this._localBillboard.invert();
  7831. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7832. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7833. }
  7834. // Local world
  7835. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7836. // Parent
  7837. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7838. this._markSyncedWithParent();
  7839. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7840. }
  7841. else {
  7842. this._worldMatrix.copyFrom(this._localWorld);
  7843. }
  7844. // Bounding info
  7845. this._updateBoundingInfo();
  7846. // Absolute position
  7847. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7848. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7849. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7850. }
  7851. return this._worldMatrix;
  7852. };
  7853. /**
  7854. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7855. * @param func: callback function to add
  7856. */
  7857. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7858. this._onAfterWorldMatrixUpdate.push(func);
  7859. };
  7860. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7861. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7862. if (index > -1) {
  7863. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7864. }
  7865. };
  7866. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7867. this.computeWorldMatrix();
  7868. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7869. };
  7870. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7871. this.computeWorldMatrix();
  7872. var invLocalWorldMatrix = this._localWorld.clone();
  7873. invLocalWorldMatrix.invert();
  7874. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7875. };
  7876. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7877. this.computeWorldMatrix();
  7878. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7879. };
  7880. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7881. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7882. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7883. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7884. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7885. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7886. /// <returns>Mesh oriented towards targetMesh</returns>
  7887. yawCor = yawCor || 0; // default to zero if undefined
  7888. pitchCor = pitchCor || 0;
  7889. rollCor = rollCor || 0;
  7890. var dv = targetPoint.subtract(this.position);
  7891. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7892. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7893. var pitch = Math.atan2(dv.y, len);
  7894. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7895. };
  7896. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7897. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7898. return false;
  7899. }
  7900. return true;
  7901. };
  7902. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7903. if (!camera) {
  7904. camera = this.getScene().activeCamera;
  7905. }
  7906. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7907. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7908. return false;
  7909. }
  7910. return true;
  7911. };
  7912. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7913. if (!this._boundingInfo || !mesh._boundingInfo) {
  7914. return false;
  7915. }
  7916. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7917. };
  7918. AbstractMesh.prototype.intersectsPoint = function (point) {
  7919. if (!this._boundingInfo) {
  7920. return false;
  7921. }
  7922. return this._boundingInfo.intersectsPoint(point);
  7923. };
  7924. // Physics
  7925. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7926. var physicsEngine = this.getScene().getPhysicsEngine();
  7927. if (!physicsEngine) {
  7928. return;
  7929. }
  7930. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7931. if (impostor.impostor) {
  7932. // Old API
  7933. options = impostor;
  7934. impostor = impostor.impostor;
  7935. }
  7936. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7937. physicsEngine._unregisterMesh(this);
  7938. return;
  7939. }
  7940. if (!options) {
  7941. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7942. }
  7943. else {
  7944. if (!options.mass && options.mass !== 0)
  7945. options.mass = 0;
  7946. if (!options.friction && options.friction !== 0)
  7947. options.friction = 0.2;
  7948. if (!options.restitution && options.restitution !== 0)
  7949. options.restitution = 0.2;
  7950. }
  7951. this._physicImpostor = impostor;
  7952. this._physicsMass = options.mass;
  7953. this._physicsFriction = options.friction;
  7954. this._physicRestitution = options.restitution;
  7955. return physicsEngine._registerMesh(this, impostor, options);
  7956. };
  7957. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7958. if (!this._physicImpostor) {
  7959. return BABYLON.PhysicsEngine.NoImpostor;
  7960. }
  7961. return this._physicImpostor;
  7962. };
  7963. AbstractMesh.prototype.getPhysicsMass = function () {
  7964. if (!this._physicsMass) {
  7965. return 0;
  7966. }
  7967. return this._physicsMass;
  7968. };
  7969. AbstractMesh.prototype.getPhysicsFriction = function () {
  7970. if (!this._physicsFriction) {
  7971. return 0;
  7972. }
  7973. return this._physicsFriction;
  7974. };
  7975. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7976. if (!this._physicRestitution) {
  7977. return 0;
  7978. }
  7979. return this._physicRestitution;
  7980. };
  7981. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7982. if (!camera) {
  7983. camera = this.getScene().activeCamera;
  7984. }
  7985. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7986. };
  7987. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7988. if (!camera) {
  7989. camera = this.getScene().activeCamera;
  7990. }
  7991. return this.absolutePosition.subtract(camera.position).length();
  7992. };
  7993. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7994. if (!this._physicImpostor) {
  7995. return;
  7996. }
  7997. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7998. };
  7999. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8000. if (!this._physicImpostor) {
  8001. return;
  8002. }
  8003. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8004. };
  8005. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8006. if (!this._physicImpostor) {
  8007. return;
  8008. }
  8009. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8010. };
  8011. // Collisions
  8012. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8013. var globalPosition = this.getAbsolutePosition();
  8014. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8015. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8016. this._collider.radius = this.ellipsoid;
  8017. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8018. };
  8019. // Submeshes octree
  8020. /**
  8021. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8022. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8023. */
  8024. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8025. if (maxCapacity === void 0) { maxCapacity = 64; }
  8026. if (maxDepth === void 0) { maxDepth = 2; }
  8027. if (!this._submeshesOctree) {
  8028. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8029. }
  8030. this.computeWorldMatrix(true);
  8031. // Update octree
  8032. var bbox = this.getBoundingInfo().boundingBox;
  8033. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8034. return this._submeshesOctree;
  8035. };
  8036. // Collisions
  8037. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8038. this._generatePointsArray();
  8039. // Transformation
  8040. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8041. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8042. subMesh._lastColliderWorldVertices = [];
  8043. subMesh._trianglePlanes = [];
  8044. var start = subMesh.verticesStart;
  8045. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8046. for (var i = start; i < end; i++) {
  8047. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8048. }
  8049. }
  8050. // Collide
  8051. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8052. if (collider.collisionFound) {
  8053. collider.collidedMesh = this;
  8054. }
  8055. };
  8056. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8057. var subMeshes;
  8058. var len;
  8059. // Octrees
  8060. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8061. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8062. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8063. len = intersections.length;
  8064. subMeshes = intersections.data;
  8065. }
  8066. else {
  8067. subMeshes = this.subMeshes;
  8068. len = subMeshes.length;
  8069. }
  8070. for (var index = 0; index < len; index++) {
  8071. var subMesh = subMeshes[index];
  8072. // Bounding test
  8073. if (len > 1 && !subMesh._checkCollision(collider))
  8074. continue;
  8075. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8076. }
  8077. };
  8078. AbstractMesh.prototype._checkCollision = function (collider) {
  8079. // Bounding box test
  8080. if (!this._boundingInfo._checkCollision(collider))
  8081. return;
  8082. // Transformation matrix
  8083. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8084. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8085. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8086. };
  8087. // Picking
  8088. AbstractMesh.prototype._generatePointsArray = function () {
  8089. return false;
  8090. };
  8091. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8092. var pickingInfo = new BABYLON.PickingInfo();
  8093. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8094. return pickingInfo;
  8095. }
  8096. if (!this._generatePointsArray()) {
  8097. return pickingInfo;
  8098. }
  8099. var intersectInfo = null;
  8100. // Octrees
  8101. var subMeshes;
  8102. var len;
  8103. if (this._submeshesOctree && this.useOctreeForPicking) {
  8104. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8105. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8106. len = intersections.length;
  8107. subMeshes = intersections.data;
  8108. }
  8109. else {
  8110. subMeshes = this.subMeshes;
  8111. len = subMeshes.length;
  8112. }
  8113. for (var index = 0; index < len; index++) {
  8114. var subMesh = subMeshes[index];
  8115. // Bounding test
  8116. if (len > 1 && !subMesh.canIntersects(ray))
  8117. continue;
  8118. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8119. if (currentIntersectInfo) {
  8120. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8121. intersectInfo = currentIntersectInfo;
  8122. intersectInfo.subMeshId = index;
  8123. if (fastCheck) {
  8124. break;
  8125. }
  8126. }
  8127. }
  8128. }
  8129. if (intersectInfo) {
  8130. // Get picked point
  8131. var world = this.getWorldMatrix();
  8132. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8133. var direction = ray.direction.clone();
  8134. direction = direction.scale(intersectInfo.distance);
  8135. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8136. var pickedPoint = worldOrigin.add(worldDirection);
  8137. // Return result
  8138. pickingInfo.hit = true;
  8139. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8140. pickingInfo.pickedPoint = pickedPoint;
  8141. pickingInfo.pickedMesh = this;
  8142. pickingInfo.bu = intersectInfo.bu;
  8143. pickingInfo.bv = intersectInfo.bv;
  8144. pickingInfo.faceId = intersectInfo.faceId;
  8145. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8146. return pickingInfo;
  8147. }
  8148. return pickingInfo;
  8149. };
  8150. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8151. return null;
  8152. };
  8153. AbstractMesh.prototype.releaseSubMeshes = function () {
  8154. if (this.subMeshes) {
  8155. while (this.subMeshes.length) {
  8156. this.subMeshes[0].dispose();
  8157. }
  8158. }
  8159. else {
  8160. this.subMeshes = new Array();
  8161. }
  8162. };
  8163. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8164. var index;
  8165. // Physics
  8166. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8167. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8168. }
  8169. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8170. var other = this._intersectionsInProgress[index];
  8171. var pos = other._intersectionsInProgress.indexOf(this);
  8172. other._intersectionsInProgress.splice(pos, 1);
  8173. }
  8174. this._intersectionsInProgress = [];
  8175. // SubMeshes
  8176. this.releaseSubMeshes();
  8177. // Remove from scene
  8178. this.getScene().removeMesh(this);
  8179. if (!doNotRecurse) {
  8180. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8181. if (this.getScene().particleSystems[index].emitter === this) {
  8182. this.getScene().particleSystems[index].dispose();
  8183. index--;
  8184. }
  8185. }
  8186. // Children
  8187. var objects = this.getScene().meshes.slice(0);
  8188. for (index = 0; index < objects.length; index++) {
  8189. if (objects[index].parent === this) {
  8190. objects[index].dispose();
  8191. }
  8192. }
  8193. }
  8194. else {
  8195. for (index = 0; index < this.getScene().meshes.length; index++) {
  8196. var obj = this.getScene().meshes[index];
  8197. if (obj.parent === this) {
  8198. obj.parent = null;
  8199. obj.computeWorldMatrix(true);
  8200. }
  8201. }
  8202. }
  8203. this._onAfterWorldMatrixUpdate = [];
  8204. this._isDisposed = true;
  8205. // Callback
  8206. if (this.onDispose) {
  8207. this.onDispose();
  8208. }
  8209. };
  8210. // Statics
  8211. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8212. AbstractMesh._BILLBOARDMODE_X = 1;
  8213. AbstractMesh._BILLBOARDMODE_Y = 2;
  8214. AbstractMesh._BILLBOARDMODE_Z = 4;
  8215. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8216. return AbstractMesh;
  8217. })(BABYLON.Node);
  8218. BABYLON.AbstractMesh = AbstractMesh;
  8219. })(BABYLON || (BABYLON = {}));
  8220. //# sourceMappingURL=babylon.abstractMesh.js.map
  8221. var __extends = this.__extends || function (d, b) {
  8222. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8223. function __() { this.constructor = d; }
  8224. __.prototype = b.prototype;
  8225. d.prototype = new __();
  8226. };
  8227. var BABYLON;
  8228. (function (BABYLON) {
  8229. var Light = (function (_super) {
  8230. __extends(Light, _super);
  8231. function Light(name, scene) {
  8232. _super.call(this, name, scene);
  8233. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8234. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8235. this.intensity = 1.0;
  8236. this.range = Number.MAX_VALUE;
  8237. this.includeOnlyWithLayerMask = 0;
  8238. this.includedOnlyMeshes = new Array();
  8239. this.excludedMeshes = new Array();
  8240. this.excludeWithLayerMask = 0;
  8241. this._excludedMeshesIds = new Array();
  8242. this._includedOnlyMeshesIds = new Array();
  8243. scene.addLight(this);
  8244. }
  8245. Light.prototype.getShadowGenerator = function () {
  8246. return this._shadowGenerator;
  8247. };
  8248. Light.prototype.getAbsolutePosition = function () {
  8249. return BABYLON.Vector3.Zero();
  8250. };
  8251. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8252. };
  8253. Light.prototype._getWorldMatrix = function () {
  8254. return BABYLON.Matrix.Identity();
  8255. };
  8256. Light.prototype.canAffectMesh = function (mesh) {
  8257. if (!mesh) {
  8258. return true;
  8259. }
  8260. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8261. return false;
  8262. }
  8263. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8264. return false;
  8265. }
  8266. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8267. return false;
  8268. }
  8269. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8270. return false;
  8271. }
  8272. return true;
  8273. };
  8274. Light.prototype.getWorldMatrix = function () {
  8275. this._currentRenderId = this.getScene().getRenderId();
  8276. var worldMatrix = this._getWorldMatrix();
  8277. if (this.parent && this.parent.getWorldMatrix) {
  8278. if (!this._parentedWorldMatrix) {
  8279. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8280. }
  8281. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8282. this._markSyncedWithParent();
  8283. return this._parentedWorldMatrix;
  8284. }
  8285. return worldMatrix;
  8286. };
  8287. Light.prototype.dispose = function () {
  8288. if (this._shadowGenerator) {
  8289. this._shadowGenerator.dispose();
  8290. this._shadowGenerator = null;
  8291. }
  8292. // Remove from scene
  8293. this.getScene().removeLight(this);
  8294. };
  8295. return Light;
  8296. })(BABYLON.Node);
  8297. BABYLON.Light = Light;
  8298. })(BABYLON || (BABYLON = {}));
  8299. //# sourceMappingURL=babylon.light.js.map
  8300. var __extends = this.__extends || function (d, b) {
  8301. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8302. function __() { this.constructor = d; }
  8303. __.prototype = b.prototype;
  8304. d.prototype = new __();
  8305. };
  8306. var BABYLON;
  8307. (function (BABYLON) {
  8308. var PointLight = (function (_super) {
  8309. __extends(PointLight, _super);
  8310. function PointLight(name, position, scene) {
  8311. _super.call(this, name, scene);
  8312. this.position = position;
  8313. }
  8314. PointLight.prototype.getAbsolutePosition = function () {
  8315. return this._transformedPosition ? this._transformedPosition : this.position;
  8316. };
  8317. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8318. if (this.parent && this.parent.getWorldMatrix) {
  8319. if (!this._transformedPosition) {
  8320. this._transformedPosition = BABYLON.Vector3.Zero();
  8321. }
  8322. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8323. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8324. return;
  8325. }
  8326. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8327. };
  8328. PointLight.prototype.getShadowGenerator = function () {
  8329. return null;
  8330. };
  8331. PointLight.prototype._getWorldMatrix = function () {
  8332. if (!this._worldMatrix) {
  8333. this._worldMatrix = BABYLON.Matrix.Identity();
  8334. }
  8335. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8336. return this._worldMatrix;
  8337. };
  8338. return PointLight;
  8339. })(BABYLON.Light);
  8340. BABYLON.PointLight = PointLight;
  8341. })(BABYLON || (BABYLON = {}));
  8342. //# sourceMappingURL=babylon.pointLight.js.map
  8343. var __extends = this.__extends || function (d, b) {
  8344. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8345. function __() { this.constructor = d; }
  8346. __.prototype = b.prototype;
  8347. d.prototype = new __();
  8348. };
  8349. var BABYLON;
  8350. (function (BABYLON) {
  8351. var SpotLight = (function (_super) {
  8352. __extends(SpotLight, _super);
  8353. function SpotLight(name, position, direction, angle, exponent, scene) {
  8354. _super.call(this, name, scene);
  8355. this.position = position;
  8356. this.direction = direction;
  8357. this.angle = angle;
  8358. this.exponent = exponent;
  8359. }
  8360. SpotLight.prototype.getAbsolutePosition = function () {
  8361. return this.transformedPosition ? this.transformedPosition : this.position;
  8362. };
  8363. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8364. var activeCamera = this.getScene().activeCamera;
  8365. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8366. };
  8367. SpotLight.prototype.supportsVSM = function () {
  8368. return true;
  8369. };
  8370. SpotLight.prototype.needRefreshPerFrame = function () {
  8371. return false;
  8372. };
  8373. SpotLight.prototype.setDirectionToTarget = function (target) {
  8374. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8375. return this.direction;
  8376. };
  8377. SpotLight.prototype.computeTransformedPosition = function () {
  8378. if (this.parent && this.parent.getWorldMatrix) {
  8379. if (!this.transformedPosition) {
  8380. this.transformedPosition = BABYLON.Vector3.Zero();
  8381. }
  8382. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8383. return true;
  8384. }
  8385. return false;
  8386. };
  8387. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8388. var normalizeDirection;
  8389. if (this.parent && this.parent.getWorldMatrix) {
  8390. if (!this._transformedDirection) {
  8391. this._transformedDirection = BABYLON.Vector3.Zero();
  8392. }
  8393. this.computeTransformedPosition();
  8394. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8395. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8396. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8397. }
  8398. else {
  8399. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8400. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8401. }
  8402. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8403. };
  8404. SpotLight.prototype._getWorldMatrix = function () {
  8405. if (!this._worldMatrix) {
  8406. this._worldMatrix = BABYLON.Matrix.Identity();
  8407. }
  8408. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8409. return this._worldMatrix;
  8410. };
  8411. return SpotLight;
  8412. })(BABYLON.Light);
  8413. BABYLON.SpotLight = SpotLight;
  8414. })(BABYLON || (BABYLON = {}));
  8415. //# sourceMappingURL=babylon.spotLight.js.map
  8416. var __extends = this.__extends || function (d, b) {
  8417. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8418. function __() { this.constructor = d; }
  8419. __.prototype = b.prototype;
  8420. d.prototype = new __();
  8421. };
  8422. var BABYLON;
  8423. (function (BABYLON) {
  8424. var HemisphericLight = (function (_super) {
  8425. __extends(HemisphericLight, _super);
  8426. function HemisphericLight(name, direction, scene) {
  8427. _super.call(this, name, scene);
  8428. this.direction = direction;
  8429. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8430. }
  8431. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8432. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8433. return this.direction;
  8434. };
  8435. HemisphericLight.prototype.getShadowGenerator = function () {
  8436. return null;
  8437. };
  8438. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8439. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8440. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8441. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8442. };
  8443. HemisphericLight.prototype._getWorldMatrix = function () {
  8444. if (!this._worldMatrix) {
  8445. this._worldMatrix = BABYLON.Matrix.Identity();
  8446. }
  8447. return this._worldMatrix;
  8448. };
  8449. return HemisphericLight;
  8450. })(BABYLON.Light);
  8451. BABYLON.HemisphericLight = HemisphericLight;
  8452. })(BABYLON || (BABYLON = {}));
  8453. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8454. var __extends = this.__extends || function (d, b) {
  8455. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8456. function __() { this.constructor = d; }
  8457. __.prototype = b.prototype;
  8458. d.prototype = new __();
  8459. };
  8460. var BABYLON;
  8461. (function (BABYLON) {
  8462. var DirectionalLight = (function (_super) {
  8463. __extends(DirectionalLight, _super);
  8464. function DirectionalLight(name, direction, scene) {
  8465. _super.call(this, name, scene);
  8466. this.direction = direction;
  8467. this.shadowOrthoScale = 0.5;
  8468. this.position = direction.scale(-1);
  8469. }
  8470. DirectionalLight.prototype.getAbsolutePosition = function () {
  8471. return this.transformedPosition ? this.transformedPosition : this.position;
  8472. };
  8473. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8474. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8475. return this.direction;
  8476. };
  8477. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8478. var orthoLeft = Number.MAX_VALUE;
  8479. var orthoRight = Number.MIN_VALUE;
  8480. var orthoTop = Number.MIN_VALUE;
  8481. var orthoBottom = Number.MAX_VALUE;
  8482. var tempVector3 = BABYLON.Vector3.Zero();
  8483. var activeCamera = this.getScene().activeCamera;
  8484. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8485. var mesh = renderList[meshIndex];
  8486. if (!mesh) {
  8487. continue;
  8488. }
  8489. var boundingInfo = mesh.getBoundingInfo();
  8490. if (!boundingInfo) {
  8491. continue;
  8492. }
  8493. var boundingBox = boundingInfo.boundingBox;
  8494. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8495. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8496. if (tempVector3.x < orthoLeft)
  8497. orthoLeft = tempVector3.x;
  8498. if (tempVector3.y < orthoBottom)
  8499. orthoBottom = tempVector3.y;
  8500. if (tempVector3.x > orthoRight)
  8501. orthoRight = tempVector3.x;
  8502. if (tempVector3.y > orthoTop)
  8503. orthoTop = tempVector3.y;
  8504. }
  8505. }
  8506. var xOffset = orthoRight - orthoLeft;
  8507. var yOffset = orthoTop - orthoBottom;
  8508. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8509. };
  8510. DirectionalLight.prototype.supportsVSM = function () {
  8511. return true;
  8512. };
  8513. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8514. return true;
  8515. };
  8516. DirectionalLight.prototype.computeTransformedPosition = function () {
  8517. if (this.parent && this.parent.getWorldMatrix) {
  8518. if (!this.transformedPosition) {
  8519. this.transformedPosition = BABYLON.Vector3.Zero();
  8520. }
  8521. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8522. return true;
  8523. }
  8524. return false;
  8525. };
  8526. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8527. if (this.parent && this.parent.getWorldMatrix) {
  8528. if (!this._transformedDirection) {
  8529. this._transformedDirection = BABYLON.Vector3.Zero();
  8530. }
  8531. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8532. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8533. return;
  8534. }
  8535. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8536. };
  8537. DirectionalLight.prototype._getWorldMatrix = function () {
  8538. if (!this._worldMatrix) {
  8539. this._worldMatrix = BABYLON.Matrix.Identity();
  8540. }
  8541. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8542. return this._worldMatrix;
  8543. };
  8544. return DirectionalLight;
  8545. })(BABYLON.Light);
  8546. BABYLON.DirectionalLight = DirectionalLight;
  8547. })(BABYLON || (BABYLON = {}));
  8548. //# sourceMappingURL=babylon.directionalLight.js.map
  8549. var BABYLON;
  8550. (function (BABYLON) {
  8551. var ShadowGenerator = (function () {
  8552. function ShadowGenerator(mapSize, light) {
  8553. var _this = this;
  8554. // Members
  8555. this._filter = ShadowGenerator.FILTER_NONE;
  8556. this.blurScale = 2;
  8557. this._blurBoxOffset = 0;
  8558. this._bias = 0.00005;
  8559. this._darkness = 0;
  8560. this._transparencyShadow = false;
  8561. this._viewMatrix = BABYLON.Matrix.Zero();
  8562. this._projectionMatrix = BABYLON.Matrix.Zero();
  8563. this._transformMatrix = BABYLON.Matrix.Zero();
  8564. this._worldViewProjection = BABYLON.Matrix.Zero();
  8565. this._light = light;
  8566. this._scene = light.getScene();
  8567. this._mapSize = mapSize;
  8568. light._shadowGenerator = this;
  8569. // Render target
  8570. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8571. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8572. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8573. this._shadowMap.anisotropicFilteringLevel = 1;
  8574. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8575. this._shadowMap.renderParticles = false;
  8576. this._shadowMap.onAfterUnbind = function () {
  8577. if (!_this.useBlurVarianceShadowMap) {
  8578. return;
  8579. }
  8580. if (!_this._shadowMap2) {
  8581. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8582. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8583. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8584. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8585. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8586. _this._downSamplePostprocess.onApply = function (effect) {
  8587. effect.setTexture("textureSampler", _this._shadowMap);
  8588. };
  8589. _this.blurBoxOffset = 1;
  8590. }
  8591. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8592. };
  8593. // Custom render function
  8594. var renderSubMesh = function (subMesh) {
  8595. var mesh = subMesh.getRenderingMesh();
  8596. var scene = _this._scene;
  8597. var engine = scene.getEngine();
  8598. // Culling
  8599. engine.setState(subMesh.getMaterial().backFaceCulling);
  8600. // Managing instances
  8601. var batch = mesh._getInstancesRenderList(subMesh._id);
  8602. if (batch.mustReturn) {
  8603. return;
  8604. }
  8605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8606. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8607. engine.enableEffect(_this._effect);
  8608. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8609. var material = subMesh.getMaterial();
  8610. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8611. // Alpha test
  8612. if (material && material.needAlphaTesting()) {
  8613. var alphaTexture = material.getAlphaTestTexture();
  8614. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8615. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8616. }
  8617. // Bones
  8618. if (mesh.useBones) {
  8619. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8620. }
  8621. // Draw
  8622. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8623. }
  8624. else {
  8625. // Need to reset refresh rate of the shadowMap
  8626. _this._shadowMap.resetRefreshCounter();
  8627. }
  8628. };
  8629. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8630. var index;
  8631. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8632. renderSubMesh(opaqueSubMeshes.data[index]);
  8633. }
  8634. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8635. renderSubMesh(alphaTestSubMeshes.data[index]);
  8636. }
  8637. if (_this._transparencyShadow) {
  8638. for (index = 0; index < transparentSubMeshes.length; index++) {
  8639. renderSubMesh(transparentSubMeshes.data[index]);
  8640. }
  8641. }
  8642. };
  8643. this._shadowMap.onClear = function (engine) {
  8644. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8645. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8646. }
  8647. else {
  8648. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8649. }
  8650. };
  8651. }
  8652. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8653. // Static
  8654. get: function () {
  8655. return ShadowGenerator._FILTER_NONE;
  8656. },
  8657. enumerable: true,
  8658. configurable: true
  8659. });
  8660. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8661. get: function () {
  8662. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8663. },
  8664. enumerable: true,
  8665. configurable: true
  8666. });
  8667. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8668. get: function () {
  8669. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8675. get: function () {
  8676. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8682. get: function () {
  8683. return this._bias;
  8684. },
  8685. set: function (bias) {
  8686. this._bias = bias;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8692. get: function () {
  8693. return this._blurBoxOffset;
  8694. },
  8695. set: function (value) {
  8696. var _this = this;
  8697. if (this._blurBoxOffset === value) {
  8698. return;
  8699. }
  8700. this._blurBoxOffset = value;
  8701. if (this._boxBlurPostprocess) {
  8702. this._boxBlurPostprocess.dispose();
  8703. }
  8704. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  8705. this._boxBlurPostprocess.onApply = function (effect) {
  8706. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8707. };
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8713. get: function () {
  8714. return this._filter;
  8715. },
  8716. set: function (value) {
  8717. if (this._filter === value) {
  8718. return;
  8719. }
  8720. this._filter = value;
  8721. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8722. this._shadowMap.anisotropicFilteringLevel = 16;
  8723. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8724. }
  8725. else {
  8726. this._shadowMap.anisotropicFilteringLevel = 1;
  8727. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8728. }
  8729. },
  8730. enumerable: true,
  8731. configurable: true
  8732. });
  8733. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8734. get: function () {
  8735. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8736. },
  8737. set: function (value) {
  8738. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8739. },
  8740. enumerable: true,
  8741. configurable: true
  8742. });
  8743. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8744. get: function () {
  8745. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8746. },
  8747. set: function (value) {
  8748. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8749. },
  8750. enumerable: true,
  8751. configurable: true
  8752. });
  8753. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8754. get: function () {
  8755. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8756. },
  8757. set: function (value) {
  8758. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8759. },
  8760. enumerable: true,
  8761. configurable: true
  8762. });
  8763. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8764. var defines = [];
  8765. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8766. defines.push("#define VSM");
  8767. }
  8768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8769. var mesh = subMesh.getMesh();
  8770. var material = subMesh.getMaterial();
  8771. // Alpha test
  8772. if (material && material.needAlphaTesting()) {
  8773. defines.push("#define ALPHATEST");
  8774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8775. attribs.push(BABYLON.VertexBuffer.UVKind);
  8776. defines.push("#define UV1");
  8777. }
  8778. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8779. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8780. defines.push("#define UV2");
  8781. }
  8782. }
  8783. // Bones
  8784. if (mesh.useBones) {
  8785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8787. defines.push("#define BONES");
  8788. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8789. }
  8790. // Instances
  8791. if (useInstances) {
  8792. defines.push("#define INSTANCES");
  8793. attribs.push("world0");
  8794. attribs.push("world1");
  8795. attribs.push("world2");
  8796. attribs.push("world3");
  8797. }
  8798. // Get correct effect
  8799. var join = defines.join("\n");
  8800. if (this._cachedDefines !== join) {
  8801. this._cachedDefines = join;
  8802. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8803. }
  8804. return this._effect.isReady();
  8805. };
  8806. ShadowGenerator.prototype.getShadowMap = function () {
  8807. return this._shadowMap;
  8808. };
  8809. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8810. if (this._shadowMap2) {
  8811. return this._shadowMap2;
  8812. }
  8813. return this._shadowMap;
  8814. };
  8815. ShadowGenerator.prototype.getLight = function () {
  8816. return this._light;
  8817. };
  8818. // Methods
  8819. ShadowGenerator.prototype.getTransformMatrix = function () {
  8820. var scene = this._scene;
  8821. if (this._currentRenderID === scene.getRenderId()) {
  8822. return this._transformMatrix;
  8823. }
  8824. this._currentRenderID = scene.getRenderId();
  8825. var lightPosition = this._light.position;
  8826. var lightDirection = this._light.direction;
  8827. if (this._light.computeTransformedPosition()) {
  8828. lightPosition = this._light.transformedPosition;
  8829. }
  8830. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8831. this._cachedPosition = lightPosition.clone();
  8832. this._cachedDirection = lightDirection.clone();
  8833. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8834. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8835. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8836. }
  8837. return this._transformMatrix;
  8838. };
  8839. ShadowGenerator.prototype.getDarkness = function () {
  8840. return this._darkness;
  8841. };
  8842. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8843. if (darkness >= 1.0)
  8844. this._darkness = 1.0;
  8845. else if (darkness <= 0.0)
  8846. this._darkness = 0.0;
  8847. else
  8848. this._darkness = darkness;
  8849. };
  8850. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8851. this._transparencyShadow = hasShadow;
  8852. };
  8853. ShadowGenerator.prototype._packHalf = function (depth) {
  8854. var scale = depth * 255.0;
  8855. var fract = scale - Math.floor(scale);
  8856. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8857. };
  8858. ShadowGenerator.prototype.dispose = function () {
  8859. this._shadowMap.dispose();
  8860. if (this._shadowMap2) {
  8861. this._shadowMap2.dispose();
  8862. }
  8863. if (this._downSamplePostprocess) {
  8864. this._downSamplePostprocess.dispose();
  8865. }
  8866. if (this._boxBlurPostprocess) {
  8867. this._boxBlurPostprocess.dispose();
  8868. }
  8869. };
  8870. ShadowGenerator._FILTER_NONE = 0;
  8871. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8872. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8873. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8874. return ShadowGenerator;
  8875. })();
  8876. BABYLON.ShadowGenerator = ShadowGenerator;
  8877. })(BABYLON || (BABYLON = {}));
  8878. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8879. var BABYLON;
  8880. (function (BABYLON) {
  8881. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8882. if (boxMin.x > sphereCenter.x + sphereRadius)
  8883. return false;
  8884. if (sphereCenter.x - sphereRadius > boxMax.x)
  8885. return false;
  8886. if (boxMin.y > sphereCenter.y + sphereRadius)
  8887. return false;
  8888. if (sphereCenter.y - sphereRadius > boxMax.y)
  8889. return false;
  8890. if (boxMin.z > sphereCenter.z + sphereRadius)
  8891. return false;
  8892. if (sphereCenter.z - sphereRadius > boxMax.z)
  8893. return false;
  8894. return true;
  8895. };
  8896. var getLowestRoot = function (a, b, c, maxR) {
  8897. var determinant = b * b - 4.0 * a * c;
  8898. var result = { root: 0, found: false };
  8899. if (determinant < 0)
  8900. return result;
  8901. var sqrtD = Math.sqrt(determinant);
  8902. var r1 = (-b - sqrtD) / (2.0 * a);
  8903. var r2 = (-b + sqrtD) / (2.0 * a);
  8904. if (r1 > r2) {
  8905. var temp = r2;
  8906. r2 = r1;
  8907. r1 = temp;
  8908. }
  8909. if (r1 > 0 && r1 < maxR) {
  8910. result.root = r1;
  8911. result.found = true;
  8912. return result;
  8913. }
  8914. if (r2 > 0 && r2 < maxR) {
  8915. result.root = r2;
  8916. result.found = true;
  8917. return result;
  8918. }
  8919. return result;
  8920. };
  8921. var Collider = (function () {
  8922. function Collider() {
  8923. this.radius = new BABYLON.Vector3(1, 1, 1);
  8924. this.retry = 0;
  8925. this.basePointWorld = BABYLON.Vector3.Zero();
  8926. this.velocityWorld = BABYLON.Vector3.Zero();
  8927. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8928. this._collisionPoint = BABYLON.Vector3.Zero();
  8929. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8930. this._tempVector = BABYLON.Vector3.Zero();
  8931. this._tempVector2 = BABYLON.Vector3.Zero();
  8932. this._tempVector3 = BABYLON.Vector3.Zero();
  8933. this._tempVector4 = BABYLON.Vector3.Zero();
  8934. this._edge = BABYLON.Vector3.Zero();
  8935. this._baseToVertex = BABYLON.Vector3.Zero();
  8936. this._destinationPoint = BABYLON.Vector3.Zero();
  8937. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8938. this._displacementVector = BABYLON.Vector3.Zero();
  8939. }
  8940. // Methods
  8941. Collider.prototype._initialize = function (source, dir, e) {
  8942. this.velocity = dir;
  8943. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8944. this.basePoint = source;
  8945. source.multiplyToRef(this.radius, this.basePointWorld);
  8946. dir.multiplyToRef(this.radius, this.velocityWorld);
  8947. this.velocityWorldLength = this.velocityWorld.length();
  8948. this.epsilon = e;
  8949. this.collisionFound = false;
  8950. };
  8951. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8952. pa.subtractToRef(point, this._tempVector);
  8953. pb.subtractToRef(point, this._tempVector2);
  8954. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8955. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8956. if (d < 0)
  8957. return false;
  8958. pc.subtractToRef(point, this._tempVector3);
  8959. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8960. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8961. if (d < 0)
  8962. return false;
  8963. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8964. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8965. return d >= 0;
  8966. };
  8967. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8968. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8969. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8970. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8971. return false;
  8972. }
  8973. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8974. return false;
  8975. return true;
  8976. };
  8977. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8978. var t0;
  8979. var embeddedInPlane = false;
  8980. //defensive programming, actually not needed.
  8981. if (!trianglePlaneArray) {
  8982. trianglePlaneArray = [];
  8983. }
  8984. if (!trianglePlaneArray[faceIndex]) {
  8985. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  8986. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  8987. }
  8988. var trianglePlane = trianglePlaneArray[faceIndex];
  8989. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  8990. return;
  8991. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  8992. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  8993. if (normalDotVelocity == 0) {
  8994. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  8995. return;
  8996. embeddedInPlane = true;
  8997. t0 = 0;
  8998. }
  8999. else {
  9000. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9001. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9002. if (t0 > t1) {
  9003. var temp = t1;
  9004. t1 = t0;
  9005. t0 = temp;
  9006. }
  9007. if (t0 > 1.0 || t1 < 0.0)
  9008. return;
  9009. if (t0 < 0)
  9010. t0 = 0;
  9011. if (t0 > 1.0)
  9012. t0 = 1.0;
  9013. }
  9014. this._collisionPoint.copyFromFloats(0, 0, 0);
  9015. var found = false;
  9016. var t = 1.0;
  9017. if (!embeddedInPlane) {
  9018. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9019. this.velocity.scaleToRef(t0, this._tempVector);
  9020. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9021. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9022. found = true;
  9023. t = t0;
  9024. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9025. }
  9026. }
  9027. if (!found) {
  9028. var velocitySquaredLength = this.velocity.lengthSquared();
  9029. var a = velocitySquaredLength;
  9030. this.basePoint.subtractToRef(p1, this._tempVector);
  9031. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9032. var c = this._tempVector.lengthSquared() - 1.0;
  9033. var lowestRoot = getLowestRoot(a, b, c, t);
  9034. if (lowestRoot.found) {
  9035. t = lowestRoot.root;
  9036. found = true;
  9037. this._collisionPoint.copyFrom(p1);
  9038. }
  9039. this.basePoint.subtractToRef(p2, this._tempVector);
  9040. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9041. c = this._tempVector.lengthSquared() - 1.0;
  9042. lowestRoot = getLowestRoot(a, b, c, t);
  9043. if (lowestRoot.found) {
  9044. t = lowestRoot.root;
  9045. found = true;
  9046. this._collisionPoint.copyFrom(p2);
  9047. }
  9048. this.basePoint.subtractToRef(p3, this._tempVector);
  9049. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9050. c = this._tempVector.lengthSquared() - 1.0;
  9051. lowestRoot = getLowestRoot(a, b, c, t);
  9052. if (lowestRoot.found) {
  9053. t = lowestRoot.root;
  9054. found = true;
  9055. this._collisionPoint.copyFrom(p3);
  9056. }
  9057. p2.subtractToRef(p1, this._edge);
  9058. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9059. var edgeSquaredLength = this._edge.lengthSquared();
  9060. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9061. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9062. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9063. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9064. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9065. lowestRoot = getLowestRoot(a, b, c, t);
  9066. if (lowestRoot.found) {
  9067. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9068. if (f >= 0.0 && f <= 1.0) {
  9069. t = lowestRoot.root;
  9070. found = true;
  9071. this._edge.scaleInPlace(f);
  9072. p1.addToRef(this._edge, this._collisionPoint);
  9073. }
  9074. }
  9075. p3.subtractToRef(p2, this._edge);
  9076. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9077. edgeSquaredLength = this._edge.lengthSquared();
  9078. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9079. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9080. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9081. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9082. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9083. lowestRoot = getLowestRoot(a, b, c, t);
  9084. if (lowestRoot.found) {
  9085. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9086. if (f >= 0.0 && f <= 1.0) {
  9087. t = lowestRoot.root;
  9088. found = true;
  9089. this._edge.scaleInPlace(f);
  9090. p2.addToRef(this._edge, this._collisionPoint);
  9091. }
  9092. }
  9093. p1.subtractToRef(p3, this._edge);
  9094. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9095. edgeSquaredLength = this._edge.lengthSquared();
  9096. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9097. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9098. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9099. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9100. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9101. lowestRoot = getLowestRoot(a, b, c, t);
  9102. if (lowestRoot.found) {
  9103. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9104. if (f >= 0.0 && f <= 1.0) {
  9105. t = lowestRoot.root;
  9106. found = true;
  9107. this._edge.scaleInPlace(f);
  9108. p3.addToRef(this._edge, this._collisionPoint);
  9109. }
  9110. }
  9111. }
  9112. if (found) {
  9113. var distToCollision = t * this.velocity.length();
  9114. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9115. if (!this.intersectionPoint) {
  9116. this.intersectionPoint = this._collisionPoint.clone();
  9117. }
  9118. else {
  9119. this.intersectionPoint.copyFrom(this._collisionPoint);
  9120. }
  9121. this.nearestDistance = distToCollision;
  9122. this.collisionFound = true;
  9123. }
  9124. }
  9125. };
  9126. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9127. for (var i = indexStart; i < indexEnd; i += 3) {
  9128. var p1 = pts[indices[i] - decal];
  9129. var p2 = pts[indices[i + 1] - decal];
  9130. var p3 = pts[indices[i + 2] - decal];
  9131. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9132. }
  9133. };
  9134. Collider.prototype._getResponse = function (pos, vel) {
  9135. pos.addToRef(vel, this._destinationPoint);
  9136. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9137. this.basePoint.addToRef(vel, pos);
  9138. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9139. this._slidePlaneNormal.normalize();
  9140. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9141. pos.addInPlace(this._displacementVector);
  9142. this.intersectionPoint.addInPlace(this._displacementVector);
  9143. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9144. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9145. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9146. };
  9147. return Collider;
  9148. })();
  9149. BABYLON.Collider = Collider;
  9150. })(BABYLON || (BABYLON = {}));
  9151. //# sourceMappingURL=babylon.collider.js.map
  9152. var BABYLON;
  9153. (function (BABYLON) {
  9154. //WebWorker code will be inserted to this variable.
  9155. BABYLON.CollisionWorker = "";
  9156. (function (WorkerTaskType) {
  9157. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9158. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9159. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9160. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9161. var WorkerTaskType = BABYLON.WorkerTaskType;
  9162. (function (WorkerReplyType) {
  9163. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9164. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9165. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9166. var WorkerReplyType = BABYLON.WorkerReplyType;
  9167. var CollisionCoordinatorWorker = (function () {
  9168. function CollisionCoordinatorWorker() {
  9169. var _this = this;
  9170. this._scaledPosition = BABYLON.Vector3.Zero();
  9171. this._scaledVelocity = BABYLON.Vector3.Zero();
  9172. this.onMeshUpdated = function (mesh) {
  9173. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9174. };
  9175. this.onGeometryUpdated = function (geometry) {
  9176. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9177. };
  9178. this._afterRender = function () {
  9179. if (!_this._init)
  9180. return;
  9181. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9182. return;
  9183. }
  9184. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9185. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9186. if (_this._runningUpdated > 4) {
  9187. return;
  9188. }
  9189. ++_this._runningUpdated;
  9190. var payload = {
  9191. updatedMeshes: _this._addUpdateMeshesList,
  9192. updatedGeometries: _this._addUpdateGeometriesList,
  9193. removedGeometries: _this._toRemoveGeometryArray,
  9194. removedMeshes: _this._toRemoveMeshesArray
  9195. };
  9196. var message = {
  9197. payload: payload,
  9198. taskType: 1 /* UPDATE */
  9199. };
  9200. var serializable = [];
  9201. for (var id in payload.updatedGeometries) {
  9202. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9203. //prepare transferables
  9204. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9205. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9206. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9207. }
  9208. }
  9209. _this._worker.postMessage(message, serializable);
  9210. _this._addUpdateMeshesList = {};
  9211. _this._addUpdateGeometriesList = {};
  9212. _this._toRemoveGeometryArray = [];
  9213. _this._toRemoveMeshesArray = [];
  9214. };
  9215. this._onMessageFromWorker = function (e) {
  9216. var returnData = e.data;
  9217. if (returnData.error != 0 /* SUCCESS */) {
  9218. //TODO what errors can be returned from the worker?
  9219. BABYLON.Tools.Warn("error returned from worker!");
  9220. return;
  9221. }
  9222. switch (returnData.taskType) {
  9223. case 0 /* INIT */:
  9224. _this._init = true;
  9225. //Update the worked with ALL of the scene's current state
  9226. _this._scene.meshes.forEach(function (mesh) {
  9227. _this.onMeshAdded(mesh);
  9228. });
  9229. _this._scene.getGeometries().forEach(function (geometry) {
  9230. _this.onGeometryAdded(geometry);
  9231. });
  9232. break;
  9233. case 1 /* UPDATE */:
  9234. _this._runningUpdated--;
  9235. break;
  9236. case 2 /* COLLIDE */:
  9237. _this._runningCollisionTask = false;
  9238. var returnPayload = returnData.payload;
  9239. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9240. return;
  9241. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9242. //cleanup
  9243. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9244. break;
  9245. }
  9246. };
  9247. this._collisionsCallbackArray = [];
  9248. this._init = false;
  9249. this._runningUpdated = 0;
  9250. this._runningCollisionTask = false;
  9251. this._addUpdateMeshesList = {};
  9252. this._addUpdateGeometriesList = {};
  9253. this._toRemoveGeometryArray = [];
  9254. this._toRemoveMeshesArray = [];
  9255. }
  9256. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9257. if (!this._init)
  9258. return;
  9259. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9260. return;
  9261. position.divideToRef(collider.radius, this._scaledPosition);
  9262. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9263. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9264. var payload = {
  9265. collider: {
  9266. position: this._scaledPosition.asArray(),
  9267. velocity: this._scaledVelocity.asArray(),
  9268. radius: collider.radius.asArray()
  9269. },
  9270. collisionId: collisionIndex,
  9271. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9272. maximumRetry: maximumRetry
  9273. };
  9274. var message = {
  9275. payload: payload,
  9276. taskType: 2 /* COLLIDE */
  9277. };
  9278. this._worker.postMessage(message);
  9279. };
  9280. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9281. this._scene = scene;
  9282. this._scene.registerAfterRender(this._afterRender);
  9283. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9284. this._worker = new Worker(workerUrl);
  9285. this._worker.onmessage = this._onMessageFromWorker;
  9286. var message = {
  9287. payload: {},
  9288. taskType: 0 /* INIT */
  9289. };
  9290. this._worker.postMessage(message);
  9291. };
  9292. CollisionCoordinatorWorker.prototype.destroy = function () {
  9293. this._scene.unregisterAfterRender(this._afterRender);
  9294. this._worker.terminate();
  9295. };
  9296. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9297. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9298. this.onMeshUpdated(mesh);
  9299. };
  9300. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9301. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9302. };
  9303. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9304. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9305. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9306. this.onGeometryUpdated(geometry);
  9307. };
  9308. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9309. this._toRemoveGeometryArray.push(geometry.id);
  9310. };
  9311. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9312. var submeshes = [];
  9313. if (mesh.subMeshes) {
  9314. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9315. return {
  9316. position: idx,
  9317. verticesStart: sm.verticesStart,
  9318. verticesCount: sm.verticesCount,
  9319. indexStart: sm.indexStart,
  9320. indexCount: sm.indexCount,
  9321. hasMaterial: !!sm.getMaterial(),
  9322. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9323. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9324. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9325. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9326. };
  9327. });
  9328. }
  9329. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9330. return {
  9331. uniqueId: mesh.uniqueId,
  9332. id: mesh.id,
  9333. name: mesh.name,
  9334. geometryId: geometryId,
  9335. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9336. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9337. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9338. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9339. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9340. subMeshes: submeshes,
  9341. checkCollisions: mesh.checkCollisions
  9342. };
  9343. };
  9344. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9345. return {
  9346. id: geometry.id,
  9347. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9348. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9349. indices: new Int32Array(geometry.getIndices() || []),
  9350. };
  9351. };
  9352. return CollisionCoordinatorWorker;
  9353. })();
  9354. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9355. var CollisionCoordinatorLegacy = (function () {
  9356. function CollisionCoordinatorLegacy() {
  9357. this._scaledPosition = BABYLON.Vector3.Zero();
  9358. this._scaledVelocity = BABYLON.Vector3.Zero();
  9359. this._finalPosition = BABYLON.Vector3.Zero();
  9360. }
  9361. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9362. position.divideToRef(collider.radius, this._scaledPosition);
  9363. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9364. collider.retry = 0;
  9365. collider.initialVelocity = this._scaledVelocity;
  9366. collider.initialPosition = this._scaledPosition;
  9367. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9368. this._finalPosition.multiplyInPlace(collider.radius);
  9369. //run the callback
  9370. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9371. };
  9372. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9373. this._scene = scene;
  9374. };
  9375. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9376. //Legacy need no destruction method.
  9377. };
  9378. //No update in legacy mode
  9379. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9380. };
  9381. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9382. };
  9383. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9384. };
  9385. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9386. };
  9387. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9388. };
  9389. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9390. };
  9391. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9392. if (excludedMesh === void 0) { excludedMesh = null; }
  9393. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9394. if (collider.retry >= maximumRetry) {
  9395. finalPosition.copyFrom(position);
  9396. return;
  9397. }
  9398. collider._initialize(position, velocity, closeDistance);
  9399. for (var index = 0; index < this._scene.meshes.length; index++) {
  9400. var mesh = this._scene.meshes[index];
  9401. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9402. mesh._checkCollision(collider);
  9403. }
  9404. }
  9405. if (!collider.collisionFound) {
  9406. position.addToRef(velocity, finalPosition);
  9407. return;
  9408. }
  9409. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9410. collider._getResponse(position, velocity);
  9411. }
  9412. if (velocity.length() <= closeDistance) {
  9413. finalPosition.copyFrom(position);
  9414. return;
  9415. }
  9416. collider.retry++;
  9417. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9418. };
  9419. return CollisionCoordinatorLegacy;
  9420. })();
  9421. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9422. })(BABYLON || (BABYLON = {}));
  9423. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9424. var __extends = this.__extends || function (d, b) {
  9425. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9426. function __() { this.constructor = d; }
  9427. __.prototype = b.prototype;
  9428. d.prototype = new __();
  9429. };
  9430. var BABYLON;
  9431. (function (BABYLON) {
  9432. var Camera = (function (_super) {
  9433. __extends(Camera, _super);
  9434. function Camera(name, position, scene) {
  9435. _super.call(this, name, scene);
  9436. this.position = position;
  9437. // Members
  9438. this.upVector = BABYLON.Vector3.Up();
  9439. this.orthoLeft = null;
  9440. this.orthoRight = null;
  9441. this.orthoBottom = null;
  9442. this.orthoTop = null;
  9443. this.fov = 0.8;
  9444. this.minZ = 1.0;
  9445. this.maxZ = 10000.0;
  9446. this.inertia = 0.9;
  9447. this.mode = Camera.PERSPECTIVE_CAMERA;
  9448. this.isIntermediate = false;
  9449. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9450. this.subCameras = [];
  9451. this.layerMask = 0xFFFFFFFF;
  9452. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9453. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9454. this._projectionMatrix = new BABYLON.Matrix();
  9455. this._postProcesses = new Array();
  9456. this._postProcessesTakenIndices = [];
  9457. this._activeMeshes = new BABYLON.SmartArray(256);
  9458. this._globalPosition = BABYLON.Vector3.Zero();
  9459. scene.addCamera(this);
  9460. if (!scene.activeCamera) {
  9461. scene.activeCamera = this;
  9462. }
  9463. }
  9464. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9465. get: function () {
  9466. return Camera._PERSPECTIVE_CAMERA;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9472. get: function () {
  9473. return Camera._ORTHOGRAPHIC_CAMERA;
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9479. get: function () {
  9480. return Camera._FOVMODE_VERTICAL_FIXED;
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9486. get: function () {
  9487. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(Camera.prototype, "globalPosition", {
  9493. get: function () {
  9494. return this._globalPosition;
  9495. },
  9496. enumerable: true,
  9497. configurable: true
  9498. });
  9499. Camera.prototype.getActiveMeshes = function () {
  9500. return this._activeMeshes;
  9501. };
  9502. Camera.prototype.isActiveMesh = function (mesh) {
  9503. return (this._activeMeshes.indexOf(mesh) !== -1);
  9504. };
  9505. //Cache
  9506. Camera.prototype._initCache = function () {
  9507. _super.prototype._initCache.call(this);
  9508. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9509. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9510. this._cache.mode = undefined;
  9511. this._cache.minZ = undefined;
  9512. this._cache.maxZ = undefined;
  9513. this._cache.fov = undefined;
  9514. this._cache.aspectRatio = undefined;
  9515. this._cache.orthoLeft = undefined;
  9516. this._cache.orthoRight = undefined;
  9517. this._cache.orthoBottom = undefined;
  9518. this._cache.orthoTop = undefined;
  9519. this._cache.renderWidth = undefined;
  9520. this._cache.renderHeight = undefined;
  9521. };
  9522. Camera.prototype._updateCache = function (ignoreParentClass) {
  9523. if (!ignoreParentClass) {
  9524. _super.prototype._updateCache.call(this);
  9525. }
  9526. var engine = this.getEngine();
  9527. this._cache.position.copyFrom(this.position);
  9528. this._cache.upVector.copyFrom(this.upVector);
  9529. this._cache.mode = this.mode;
  9530. this._cache.minZ = this.minZ;
  9531. this._cache.maxZ = this.maxZ;
  9532. this._cache.fov = this.fov;
  9533. this._cache.aspectRatio = engine.getAspectRatio(this);
  9534. this._cache.orthoLeft = this.orthoLeft;
  9535. this._cache.orthoRight = this.orthoRight;
  9536. this._cache.orthoBottom = this.orthoBottom;
  9537. this._cache.orthoTop = this.orthoTop;
  9538. this._cache.renderWidth = engine.getRenderWidth();
  9539. this._cache.renderHeight = engine.getRenderHeight();
  9540. };
  9541. Camera.prototype._updateFromScene = function () {
  9542. this.updateCache();
  9543. this._update();
  9544. };
  9545. // Synchronized
  9546. Camera.prototype._isSynchronized = function () {
  9547. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9548. };
  9549. Camera.prototype._isSynchronizedViewMatrix = function () {
  9550. if (!_super.prototype._isSynchronized.call(this))
  9551. return false;
  9552. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9553. };
  9554. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9555. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9556. if (!check) {
  9557. return false;
  9558. }
  9559. var engine = this.getEngine();
  9560. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9561. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9562. }
  9563. else {
  9564. 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();
  9565. }
  9566. return check;
  9567. };
  9568. // Controls
  9569. Camera.prototype.attachControl = function (element) {
  9570. };
  9571. Camera.prototype.detachControl = function (element) {
  9572. };
  9573. Camera.prototype._update = function () {
  9574. };
  9575. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9576. if (insertAt === void 0) { insertAt = null; }
  9577. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9578. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9579. return 0;
  9580. }
  9581. if (insertAt == null || insertAt < 0) {
  9582. this._postProcesses.push(postProcess);
  9583. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9584. return this._postProcesses.length - 1;
  9585. }
  9586. var add = 0;
  9587. if (this._postProcesses[insertAt]) {
  9588. var start = this._postProcesses.length - 1;
  9589. for (var i = start; i >= insertAt + 1; --i) {
  9590. this._postProcesses[i + 1] = this._postProcesses[i];
  9591. }
  9592. add = 1;
  9593. }
  9594. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9595. if (this._postProcessesTakenIndices[i] < insertAt) {
  9596. continue;
  9597. }
  9598. start = this._postProcessesTakenIndices.length - 1;
  9599. for (var j = start; j >= i; --j) {
  9600. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9601. }
  9602. this._postProcessesTakenIndices[i] = insertAt;
  9603. break;
  9604. }
  9605. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9606. this._postProcessesTakenIndices.push(insertAt);
  9607. }
  9608. var result = insertAt + add;
  9609. this._postProcesses[result] = postProcess;
  9610. return result;
  9611. };
  9612. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9613. if (atIndices === void 0) { atIndices = null; }
  9614. var result = [];
  9615. if (!atIndices) {
  9616. var length = this._postProcesses.length;
  9617. for (var i = 0; i < length; i++) {
  9618. if (this._postProcesses[i] !== postProcess) {
  9619. continue;
  9620. }
  9621. delete this._postProcesses[i];
  9622. var index = this._postProcessesTakenIndices.indexOf(i);
  9623. this._postProcessesTakenIndices.splice(index, 1);
  9624. }
  9625. }
  9626. else {
  9627. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9628. for (i = 0; i < atIndices.length; i++) {
  9629. var foundPostProcess = this._postProcesses[atIndices[i]];
  9630. if (foundPostProcess !== postProcess) {
  9631. result.push(i);
  9632. continue;
  9633. }
  9634. delete this._postProcesses[atIndices[i]];
  9635. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9636. this._postProcessesTakenIndices.splice(index, 1);
  9637. }
  9638. }
  9639. return result;
  9640. };
  9641. Camera.prototype.getWorldMatrix = function () {
  9642. if (!this._worldMatrix) {
  9643. this._worldMatrix = BABYLON.Matrix.Identity();
  9644. }
  9645. var viewMatrix = this.getViewMatrix();
  9646. viewMatrix.invertToRef(this._worldMatrix);
  9647. return this._worldMatrix;
  9648. };
  9649. Camera.prototype._getViewMatrix = function () {
  9650. return BABYLON.Matrix.Identity();
  9651. };
  9652. Camera.prototype.getViewMatrix = function (force) {
  9653. this._computedViewMatrix = this._computeViewMatrix(force);
  9654. if (!force && this._isSynchronizedViewMatrix()) {
  9655. return this._computedViewMatrix;
  9656. }
  9657. if (!this.parent || !this.parent.getWorldMatrix) {
  9658. this._globalPosition.copyFrom(this.position);
  9659. }
  9660. else {
  9661. if (!this._worldMatrix) {
  9662. this._worldMatrix = BABYLON.Matrix.Identity();
  9663. }
  9664. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9665. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9666. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9667. this._computedViewMatrix.invert();
  9668. this._markSyncedWithParent();
  9669. }
  9670. this._currentRenderId = this.getScene().getRenderId();
  9671. return this._computedViewMatrix;
  9672. };
  9673. Camera.prototype._computeViewMatrix = function (force) {
  9674. if (!force && this._isSynchronizedViewMatrix()) {
  9675. return this._computedViewMatrix;
  9676. }
  9677. this._computedViewMatrix = this._getViewMatrix();
  9678. this._currentRenderId = this.getScene().getRenderId();
  9679. return this._computedViewMatrix;
  9680. };
  9681. Camera.prototype.getProjectionMatrix = function (force) {
  9682. if (!force && this._isSynchronizedProjectionMatrix()) {
  9683. return this._projectionMatrix;
  9684. }
  9685. var engine = this.getEngine();
  9686. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9687. if (this.minZ <= 0) {
  9688. this.minZ = 0.1;
  9689. }
  9690. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9691. return this._projectionMatrix;
  9692. }
  9693. var halfWidth = engine.getRenderWidth() / 2.0;
  9694. var halfHeight = engine.getRenderHeight() / 2.0;
  9695. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9696. return this._projectionMatrix;
  9697. };
  9698. Camera.prototype.dispose = function () {
  9699. // Remove from scene
  9700. this.getScene().removeCamera(this);
  9701. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9702. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9703. }
  9704. };
  9705. // Statics
  9706. Camera._PERSPECTIVE_CAMERA = 0;
  9707. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9708. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9709. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9710. return Camera;
  9711. })(BABYLON.Node);
  9712. BABYLON.Camera = Camera;
  9713. })(BABYLON || (BABYLON = {}));
  9714. //# sourceMappingURL=babylon.camera.js.map
  9715. var __extends = this.__extends || function (d, b) {
  9716. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9717. function __() { this.constructor = d; }
  9718. __.prototype = b.prototype;
  9719. d.prototype = new __();
  9720. };
  9721. var BABYLON;
  9722. (function (BABYLON) {
  9723. var TargetCamera = (function (_super) {
  9724. __extends(TargetCamera, _super);
  9725. function TargetCamera(name, position, scene) {
  9726. _super.call(this, name, position, scene);
  9727. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9728. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9729. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9730. this.speed = 2.0;
  9731. this.noRotationConstraint = false;
  9732. this.lockedTarget = null;
  9733. this._currentTarget = BABYLON.Vector3.Zero();
  9734. this._viewMatrix = BABYLON.Matrix.Zero();
  9735. this._camMatrix = BABYLON.Matrix.Zero();
  9736. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9737. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9738. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9739. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9740. this._lookAtTemp = BABYLON.Matrix.Zero();
  9741. this._tempMatrix = BABYLON.Matrix.Zero();
  9742. }
  9743. TargetCamera.prototype._getLockedTargetPosition = function () {
  9744. if (!this.lockedTarget) {
  9745. return null;
  9746. }
  9747. return this.lockedTarget.position || this.lockedTarget;
  9748. };
  9749. // Cache
  9750. TargetCamera.prototype._initCache = function () {
  9751. _super.prototype._initCache.call(this);
  9752. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9753. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9754. };
  9755. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9756. if (!ignoreParentClass) {
  9757. _super.prototype._updateCache.call(this);
  9758. }
  9759. var lockedTargetPosition = this._getLockedTargetPosition();
  9760. if (!lockedTargetPosition) {
  9761. this._cache.lockedTarget = null;
  9762. }
  9763. else {
  9764. if (!this._cache.lockedTarget) {
  9765. this._cache.lockedTarget = lockedTargetPosition.clone();
  9766. }
  9767. else {
  9768. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  9769. }
  9770. }
  9771. this._cache.rotation.copyFrom(this.rotation);
  9772. };
  9773. // Synchronized
  9774. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  9775. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  9776. return false;
  9777. }
  9778. var lockedTargetPosition = this._getLockedTargetPosition();
  9779. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  9780. };
  9781. // Methods
  9782. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  9783. var engine = this.getEngine();
  9784. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  9785. };
  9786. // Target
  9787. TargetCamera.prototype.setTarget = function (target) {
  9788. this.upVector.normalize();
  9789. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  9790. this._camMatrix.invert();
  9791. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  9792. var vDir = target.subtract(this.position);
  9793. if (vDir.x >= 0.0) {
  9794. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  9795. }
  9796. else {
  9797. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  9798. }
  9799. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  9800. if (isNaN(this.rotation.x)) {
  9801. this.rotation.x = 0;
  9802. }
  9803. if (isNaN(this.rotation.y)) {
  9804. this.rotation.y = 0;
  9805. }
  9806. if (isNaN(this.rotation.z)) {
  9807. this.rotation.z = 0;
  9808. }
  9809. };
  9810. TargetCamera.prototype.getTarget = function () {
  9811. return this._currentTarget;
  9812. };
  9813. TargetCamera.prototype._decideIfNeedsToMove = function () {
  9814. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  9815. };
  9816. TargetCamera.prototype._updatePosition = function () {
  9817. this.position.addInPlace(this.cameraDirection);
  9818. };
  9819. TargetCamera.prototype._update = function () {
  9820. var needToMove = this._decideIfNeedsToMove();
  9821. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  9822. // Move
  9823. if (needToMove) {
  9824. this._updatePosition();
  9825. }
  9826. // Rotate
  9827. if (needToRotate) {
  9828. this.rotation.x += this.cameraRotation.x;
  9829. this.rotation.y += this.cameraRotation.y;
  9830. if (!this.noRotationConstraint) {
  9831. var limit = (Math.PI / 2) * 0.95;
  9832. if (this.rotation.x > limit)
  9833. this.rotation.x = limit;
  9834. if (this.rotation.x < -limit)
  9835. this.rotation.x = -limit;
  9836. }
  9837. }
  9838. // Inertia
  9839. if (needToMove) {
  9840. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  9841. this.cameraDirection.x = 0;
  9842. }
  9843. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  9844. this.cameraDirection.y = 0;
  9845. }
  9846. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  9847. this.cameraDirection.z = 0;
  9848. }
  9849. this.cameraDirection.scaleInPlace(this.inertia);
  9850. }
  9851. if (needToRotate) {
  9852. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  9853. this.cameraRotation.x = 0;
  9854. }
  9855. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  9856. this.cameraRotation.y = 0;
  9857. }
  9858. this.cameraRotation.scaleInPlace(this.inertia);
  9859. }
  9860. };
  9861. TargetCamera.prototype._getViewMatrix = function () {
  9862. if (!this.lockedTarget) {
  9863. // Compute
  9864. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  9865. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  9866. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9867. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  9868. this._lookAtTemp.invert();
  9869. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  9870. }
  9871. else {
  9872. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9873. }
  9874. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  9875. // Computing target and final matrix
  9876. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  9877. }
  9878. else {
  9879. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  9880. }
  9881. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  9882. return this._viewMatrix;
  9883. };
  9884. return TargetCamera;
  9885. })(BABYLON.Camera);
  9886. BABYLON.TargetCamera = TargetCamera;
  9887. })(BABYLON || (BABYLON = {}));
  9888. //# sourceMappingURL=babylon.targetCamera.js.map
  9889. var __extends = this.__extends || function (d, b) {
  9890. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9891. function __() { this.constructor = d; }
  9892. __.prototype = b.prototype;
  9893. d.prototype = new __();
  9894. };
  9895. var BABYLON;
  9896. (function (BABYLON) {
  9897. var FreeCamera = (function (_super) {
  9898. __extends(FreeCamera, _super);
  9899. function FreeCamera(name, position, scene) {
  9900. var _this = this;
  9901. _super.call(this, name, position, scene);
  9902. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9903. this.keysUp = [38];
  9904. this.keysDown = [40];
  9905. this.keysLeft = [37];
  9906. this.keysRight = [39];
  9907. this.checkCollisions = false;
  9908. this.applyGravity = false;
  9909. this.angularSensibility = 2000.0;
  9910. this._keys = [];
  9911. this._collider = new BABYLON.Collider();
  9912. this._needMoveForGravity = false;
  9913. this._oldPosition = BABYLON.Vector3.Zero();
  9914. this._diffPosition = BABYLON.Vector3.Zero();
  9915. this._newPosition = BABYLON.Vector3.Zero();
  9916. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9917. if (collidedMesh === void 0) { collidedMesh = null; }
  9918. //TODO move this to the collision coordinator!
  9919. if (_this.getScene().workerCollisions)
  9920. newPosition.multiplyInPlace(_this._collider.radius);
  9921. var updatePosition = function (newPos) {
  9922. _this._newPosition.copyFrom(newPos);
  9923. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  9924. var oldPosition = _this.position.clone();
  9925. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  9926. _this.position.addInPlace(_this._diffPosition);
  9927. if (_this.onCollide && collidedMesh) {
  9928. _this.onCollide(collidedMesh);
  9929. }
  9930. }
  9931. };
  9932. updatePosition(newPosition);
  9933. };
  9934. }
  9935. // Controls
  9936. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  9937. var _this = this;
  9938. var previousPosition;
  9939. var engine = this.getEngine();
  9940. if (this._attachedElement) {
  9941. return;
  9942. }
  9943. this._attachedElement = element;
  9944. if (this._onMouseDown === undefined) {
  9945. this._onMouseDown = function (evt) {
  9946. previousPosition = {
  9947. x: evt.clientX,
  9948. y: evt.clientY
  9949. };
  9950. if (!noPreventDefault) {
  9951. evt.preventDefault();
  9952. }
  9953. };
  9954. this._onMouseUp = function (evt) {
  9955. previousPosition = null;
  9956. if (!noPreventDefault) {
  9957. evt.preventDefault();
  9958. }
  9959. };
  9960. this._onMouseOut = function (evt) {
  9961. previousPosition = null;
  9962. _this._keys = [];
  9963. if (!noPreventDefault) {
  9964. evt.preventDefault();
  9965. }
  9966. };
  9967. this._onMouseMove = function (evt) {
  9968. if (!previousPosition && !engine.isPointerLock) {
  9969. return;
  9970. }
  9971. var offsetX;
  9972. var offsetY;
  9973. if (!engine.isPointerLock) {
  9974. offsetX = evt.clientX - previousPosition.x;
  9975. offsetY = evt.clientY - previousPosition.y;
  9976. }
  9977. else {
  9978. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  9979. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  9980. }
  9981. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  9982. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  9983. previousPosition = {
  9984. x: evt.clientX,
  9985. y: evt.clientY
  9986. };
  9987. if (!noPreventDefault) {
  9988. evt.preventDefault();
  9989. }
  9990. };
  9991. this._onKeyDown = function (evt) {
  9992. 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) {
  9993. var index = _this._keys.indexOf(evt.keyCode);
  9994. if (index === -1) {
  9995. _this._keys.push(evt.keyCode);
  9996. }
  9997. if (!noPreventDefault) {
  9998. evt.preventDefault();
  9999. }
  10000. }
  10001. };
  10002. this._onKeyUp = function (evt) {
  10003. 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) {
  10004. var index = _this._keys.indexOf(evt.keyCode);
  10005. if (index >= 0) {
  10006. _this._keys.splice(index, 1);
  10007. }
  10008. if (!noPreventDefault) {
  10009. evt.preventDefault();
  10010. }
  10011. }
  10012. };
  10013. this._onLostFocus = function () {
  10014. _this._keys = [];
  10015. };
  10016. this._reset = function () {
  10017. _this._keys = [];
  10018. previousPosition = null;
  10019. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10020. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10021. };
  10022. }
  10023. element.addEventListener("mousedown", this._onMouseDown, false);
  10024. element.addEventListener("mouseup", this._onMouseUp, false);
  10025. element.addEventListener("mouseout", this._onMouseOut, false);
  10026. element.addEventListener("mousemove", this._onMouseMove, false);
  10027. BABYLON.Tools.RegisterTopRootEvents([
  10028. { name: "keydown", handler: this._onKeyDown },
  10029. { name: "keyup", handler: this._onKeyUp },
  10030. { name: "blur", handler: this._onLostFocus }
  10031. ]);
  10032. };
  10033. FreeCamera.prototype.detachControl = function (element) {
  10034. if (this._attachedElement != element) {
  10035. return;
  10036. }
  10037. element.removeEventListener("mousedown", this._onMouseDown);
  10038. element.removeEventListener("mouseup", this._onMouseUp);
  10039. element.removeEventListener("mouseout", this._onMouseOut);
  10040. element.removeEventListener("mousemove", this._onMouseMove);
  10041. BABYLON.Tools.UnregisterTopRootEvents([
  10042. { name: "keydown", handler: this._onKeyDown },
  10043. { name: "keyup", handler: this._onKeyUp },
  10044. { name: "blur", handler: this._onLostFocus }
  10045. ]);
  10046. this._attachedElement = null;
  10047. if (this._reset) {
  10048. this._reset();
  10049. }
  10050. };
  10051. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10052. var globalPosition;
  10053. if (this.parent) {
  10054. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10055. }
  10056. else {
  10057. globalPosition = this.position;
  10058. }
  10059. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10060. this._collider.radius = this.ellipsoid;
  10061. //add gravity to the velocity to prevent the dual-collision checking
  10062. if (this.applyGravity) {
  10063. velocity.addInPlace(this.getScene().gravity);
  10064. }
  10065. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10066. };
  10067. FreeCamera.prototype._checkInputs = function () {
  10068. if (!this._localDirection) {
  10069. this._localDirection = BABYLON.Vector3.Zero();
  10070. this._transformedDirection = BABYLON.Vector3.Zero();
  10071. }
  10072. for (var index = 0; index < this._keys.length; index++) {
  10073. var keyCode = this._keys[index];
  10074. var speed = this._computeLocalCameraSpeed();
  10075. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10076. this._localDirection.copyFromFloats(-speed, 0, 0);
  10077. }
  10078. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10079. this._localDirection.copyFromFloats(0, 0, speed);
  10080. }
  10081. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10082. this._localDirection.copyFromFloats(speed, 0, 0);
  10083. }
  10084. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10085. this._localDirection.copyFromFloats(0, 0, -speed);
  10086. }
  10087. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10088. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10089. this.cameraDirection.addInPlace(this._transformedDirection);
  10090. }
  10091. };
  10092. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10093. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10094. };
  10095. FreeCamera.prototype._updatePosition = function () {
  10096. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10097. this._collideWithWorld(this.cameraDirection);
  10098. }
  10099. else {
  10100. this.position.addInPlace(this.cameraDirection);
  10101. }
  10102. };
  10103. FreeCamera.prototype._update = function () {
  10104. this._checkInputs();
  10105. _super.prototype._update.call(this);
  10106. };
  10107. return FreeCamera;
  10108. })(BABYLON.TargetCamera);
  10109. BABYLON.FreeCamera = FreeCamera;
  10110. })(BABYLON || (BABYLON = {}));
  10111. //# sourceMappingURL=babylon.freeCamera.js.map
  10112. var __extends = this.__extends || function (d, b) {
  10113. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10114. function __() { this.constructor = d; }
  10115. __.prototype = b.prototype;
  10116. d.prototype = new __();
  10117. };
  10118. var BABYLON;
  10119. (function (BABYLON) {
  10120. var FollowCamera = (function (_super) {
  10121. __extends(FollowCamera, _super);
  10122. function FollowCamera(name, position, scene) {
  10123. _super.call(this, name, position, scene);
  10124. this.radius = 12;
  10125. this.rotationOffset = 0;
  10126. this.heightOffset = 4;
  10127. this.cameraAcceleration = 0.05;
  10128. this.maxCameraSpeed = 20;
  10129. }
  10130. FollowCamera.prototype.getRadians = function (degrees) {
  10131. return degrees * Math.PI / 180;
  10132. };
  10133. FollowCamera.prototype.follow = function (cameraTarget) {
  10134. if (!cameraTarget)
  10135. return;
  10136. var yRotation;
  10137. if (cameraTarget.rotationQuaternion) {
  10138. var rotMatrix = new BABYLON.Matrix();
  10139. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10140. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10141. }
  10142. else {
  10143. yRotation = cameraTarget.rotation.y;
  10144. }
  10145. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10146. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10147. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10148. var dx = targetX - this.position.x;
  10149. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10150. var dz = (targetZ) - this.position.z;
  10151. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10152. var vy = dy * this.cameraAcceleration;
  10153. var vz = dz * this.cameraAcceleration * 2;
  10154. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10155. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10156. }
  10157. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10158. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10159. }
  10160. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10161. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10162. }
  10163. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10164. this.setTarget(cameraTarget.position);
  10165. };
  10166. FollowCamera.prototype._update = function () {
  10167. _super.prototype._update.call(this);
  10168. this.follow(this.target);
  10169. };
  10170. return FollowCamera;
  10171. })(BABYLON.TargetCamera);
  10172. BABYLON.FollowCamera = FollowCamera;
  10173. })(BABYLON || (BABYLON = {}));
  10174. //# sourceMappingURL=babylon.followCamera.js.map
  10175. var __extends = this.__extends || function (d, b) {
  10176. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10177. function __() { this.constructor = d; }
  10178. __.prototype = b.prototype;
  10179. d.prototype = new __();
  10180. };
  10181. var BABYLON;
  10182. (function (BABYLON) {
  10183. // We're mainly based on the logic defined into the FreeCamera code
  10184. var TouchCamera = (function (_super) {
  10185. __extends(TouchCamera, _super);
  10186. function TouchCamera(name, position, scene) {
  10187. _super.call(this, name, position, scene);
  10188. this._offsetX = null;
  10189. this._offsetY = null;
  10190. this._pointerCount = 0;
  10191. this._pointerPressed = [];
  10192. this.angularSensibility = 200000.0;
  10193. this.moveSensibility = 500.0;
  10194. }
  10195. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10196. var _this = this;
  10197. var previousPosition;
  10198. if (this._attachedCanvas) {
  10199. return;
  10200. }
  10201. this._attachedCanvas = canvas;
  10202. if (this._onPointerDown === undefined) {
  10203. this._onPointerDown = function (evt) {
  10204. if (!noPreventDefault) {
  10205. evt.preventDefault();
  10206. }
  10207. _this._pointerPressed.push(evt.pointerId);
  10208. if (_this._pointerPressed.length !== 1) {
  10209. return;
  10210. }
  10211. previousPosition = {
  10212. x: evt.clientX,
  10213. y: evt.clientY
  10214. };
  10215. };
  10216. this._onPointerUp = function (evt) {
  10217. if (!noPreventDefault) {
  10218. evt.preventDefault();
  10219. }
  10220. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10221. if (index === -1) {
  10222. return;
  10223. }
  10224. _this._pointerPressed.splice(index, 1);
  10225. if (index != 0) {
  10226. return;
  10227. }
  10228. previousPosition = null;
  10229. _this._offsetX = null;
  10230. _this._offsetY = null;
  10231. };
  10232. this._onPointerMove = function (evt) {
  10233. if (!noPreventDefault) {
  10234. evt.preventDefault();
  10235. }
  10236. if (!previousPosition) {
  10237. return;
  10238. }
  10239. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10240. if (index != 0) {
  10241. return;
  10242. }
  10243. _this._offsetX = evt.clientX - previousPosition.x;
  10244. _this._offsetY = -(evt.clientY - previousPosition.y);
  10245. };
  10246. this._onLostFocus = function () {
  10247. _this._offsetX = null;
  10248. _this._offsetY = null;
  10249. };
  10250. }
  10251. canvas.addEventListener("pointerdown", this._onPointerDown);
  10252. canvas.addEventListener("pointerup", this._onPointerUp);
  10253. canvas.addEventListener("pointerout", this._onPointerUp);
  10254. canvas.addEventListener("pointermove", this._onPointerMove);
  10255. BABYLON.Tools.RegisterTopRootEvents([
  10256. { name: "blur", handler: this._onLostFocus }
  10257. ]);
  10258. };
  10259. TouchCamera.prototype.detachControl = function (canvas) {
  10260. if (this._attachedCanvas != canvas) {
  10261. return;
  10262. }
  10263. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10264. canvas.removeEventListener("pointerup", this._onPointerUp);
  10265. canvas.removeEventListener("pointerout", this._onPointerUp);
  10266. canvas.removeEventListener("pointermove", this._onPointerMove);
  10267. BABYLON.Tools.UnregisterTopRootEvents([
  10268. { name: "blur", handler: this._onLostFocus }
  10269. ]);
  10270. this._attachedCanvas = null;
  10271. };
  10272. TouchCamera.prototype._checkInputs = function () {
  10273. if (!this._offsetX) {
  10274. return;
  10275. }
  10276. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10277. if (this._pointerPressed.length > 1) {
  10278. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10279. }
  10280. else {
  10281. var speed = this._computeLocalCameraSpeed();
  10282. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10283. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10284. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10285. }
  10286. };
  10287. return TouchCamera;
  10288. })(BABYLON.FreeCamera);
  10289. BABYLON.TouchCamera = TouchCamera;
  10290. })(BABYLON || (BABYLON = {}));
  10291. //# sourceMappingURL=babylon.touchCamera.js.map
  10292. var __extends = this.__extends || function (d, b) {
  10293. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10294. function __() { this.constructor = d; }
  10295. __.prototype = b.prototype;
  10296. d.prototype = new __();
  10297. };
  10298. var BABYLON;
  10299. (function (BABYLON) {
  10300. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10301. var ArcRotateCamera = (function (_super) {
  10302. __extends(ArcRotateCamera, _super);
  10303. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10304. var _this = this;
  10305. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10306. this.alpha = alpha;
  10307. this.beta = beta;
  10308. this.radius = radius;
  10309. this.target = target;
  10310. this.inertialAlphaOffset = 0;
  10311. this.inertialBetaOffset = 0;
  10312. this.inertialRadiusOffset = 0;
  10313. this.lowerAlphaLimit = null;
  10314. this.upperAlphaLimit = null;
  10315. this.lowerBetaLimit = 0.01;
  10316. this.upperBetaLimit = Math.PI;
  10317. this.lowerRadiusLimit = null;
  10318. this.upperRadiusLimit = null;
  10319. this.angularSensibility = 1000.0;
  10320. this.wheelPrecision = 3.0;
  10321. this.pinchPrecision = 2.0;
  10322. this.keysUp = [38];
  10323. this.keysDown = [40];
  10324. this.keysLeft = [37];
  10325. this.keysRight = [39];
  10326. this.zoomOnFactor = 1;
  10327. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10328. this.pinchInwards = true;
  10329. this._keys = [];
  10330. this._viewMatrix = new BABYLON.Matrix();
  10331. this.checkCollisions = false;
  10332. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10333. this._collider = new BABYLON.Collider();
  10334. this._previousPosition = BABYLON.Vector3.Zero();
  10335. this._collisionVelocity = BABYLON.Vector3.Zero();
  10336. this._newPosition = BABYLON.Vector3.Zero();
  10337. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10338. if (collidedMesh === void 0) { collidedMesh = null; }
  10339. if (collisionId != null || collisionId != undefined)
  10340. newPosition.multiplyInPlace(_this._collider.radius);
  10341. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10342. _this.position.copyFrom(_this._previousPosition);
  10343. _this.alpha = _this._previousAlpha;
  10344. _this.beta = _this._previousBeta;
  10345. _this.radius = _this._previousRadius;
  10346. if (_this.onCollide && collidedMesh) {
  10347. _this.onCollide(collidedMesh);
  10348. }
  10349. }
  10350. _this._collisionTriggered = false;
  10351. };
  10352. if (!this.target) {
  10353. this.target = BABYLON.Vector3.Zero();
  10354. }
  10355. this.getViewMatrix();
  10356. }
  10357. ArcRotateCamera.prototype._getTargetPosition = function () {
  10358. return this.target.position || this.target;
  10359. };
  10360. // Cache
  10361. ArcRotateCamera.prototype._initCache = function () {
  10362. _super.prototype._initCache.call(this);
  10363. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10364. this._cache.alpha = undefined;
  10365. this._cache.beta = undefined;
  10366. this._cache.radius = undefined;
  10367. this._cache.targetScreenOffset = undefined;
  10368. };
  10369. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10370. if (!ignoreParentClass) {
  10371. _super.prototype._updateCache.call(this);
  10372. }
  10373. this._cache.target.copyFrom(this._getTargetPosition());
  10374. this._cache.alpha = this.alpha;
  10375. this._cache.beta = this.beta;
  10376. this._cache.radius = this.radius;
  10377. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10378. };
  10379. // Synchronized
  10380. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10381. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10382. return false;
  10383. 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);
  10384. };
  10385. // Methods
  10386. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10387. var _this = this;
  10388. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10389. var previousPinchDistance = 0;
  10390. var pointers = new BABYLON.SmartCollection();
  10391. if (this._attachedElement) {
  10392. return;
  10393. }
  10394. this._attachedElement = element;
  10395. var engine = this.getEngine();
  10396. if (this._onPointerDown === undefined) {
  10397. this._onPointerDown = function (evt) {
  10398. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10399. cacheSoloPointer = pointers.item(evt.pointerId);
  10400. if (!noPreventDefault) {
  10401. evt.preventDefault();
  10402. }
  10403. };
  10404. this._onPointerUp = function (evt) {
  10405. cacheSoloPointer = null;
  10406. previousPinchDistance = 0;
  10407. pointers.remove(evt.pointerId);
  10408. if (!noPreventDefault) {
  10409. evt.preventDefault();
  10410. }
  10411. };
  10412. this._onPointerMove = function (evt) {
  10413. if (!noPreventDefault) {
  10414. evt.preventDefault();
  10415. }
  10416. switch (pointers.count) {
  10417. case 1:
  10418. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10419. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10420. var offsetX = evt.clientX - cacheSoloPointer.x;
  10421. var offsetY = evt.clientY - cacheSoloPointer.y;
  10422. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10423. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10424. //pointers.item(evt.pointerId).x = evt.clientX;
  10425. //pointers.item(evt.pointerId).y = evt.clientY;
  10426. cacheSoloPointer.x = evt.clientX;
  10427. cacheSoloPointer.y = evt.clientY;
  10428. break;
  10429. case 2:
  10430. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10431. pointers.item(evt.pointerId).x = evt.clientX;
  10432. pointers.item(evt.pointerId).y = evt.clientY;
  10433. var direction = _this.pinchInwards ? 1 : -1;
  10434. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10435. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10436. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10437. if (previousPinchDistance === 0) {
  10438. previousPinchDistance = pinchSquaredDistance;
  10439. return;
  10440. }
  10441. if (pinchSquaredDistance !== previousPinchDistance) {
  10442. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10443. previousPinchDistance = pinchSquaredDistance;
  10444. }
  10445. break;
  10446. default:
  10447. if (pointers.item(evt.pointerId)) {
  10448. pointers.item(evt.pointerId).x = evt.clientX;
  10449. pointers.item(evt.pointerId).y = evt.clientY;
  10450. }
  10451. }
  10452. };
  10453. this._onMouseMove = function (evt) {
  10454. if (!engine.isPointerLock) {
  10455. return;
  10456. }
  10457. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10458. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10459. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10460. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10461. if (!noPreventDefault) {
  10462. evt.preventDefault();
  10463. }
  10464. };
  10465. this._wheel = function (event) {
  10466. var delta = 0;
  10467. if (event.wheelDelta) {
  10468. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10469. }
  10470. else if (event.detail) {
  10471. delta = -event.detail / _this.wheelPrecision;
  10472. }
  10473. if (delta)
  10474. _this.inertialRadiusOffset += delta;
  10475. if (event.preventDefault) {
  10476. if (!noPreventDefault) {
  10477. event.preventDefault();
  10478. }
  10479. }
  10480. };
  10481. this._onKeyDown = function (evt) {
  10482. 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) {
  10483. var index = _this._keys.indexOf(evt.keyCode);
  10484. if (index === -1) {
  10485. _this._keys.push(evt.keyCode);
  10486. }
  10487. if (evt.preventDefault) {
  10488. if (!noPreventDefault) {
  10489. evt.preventDefault();
  10490. }
  10491. }
  10492. }
  10493. };
  10494. this._onKeyUp = function (evt) {
  10495. 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) {
  10496. var index = _this._keys.indexOf(evt.keyCode);
  10497. if (index >= 0) {
  10498. _this._keys.splice(index, 1);
  10499. }
  10500. if (evt.preventDefault) {
  10501. if (!noPreventDefault) {
  10502. evt.preventDefault();
  10503. }
  10504. }
  10505. }
  10506. };
  10507. this._onLostFocus = function () {
  10508. _this._keys = [];
  10509. pointers.empty();
  10510. previousPinchDistance = 0;
  10511. cacheSoloPointer = null;
  10512. };
  10513. this._onGestureStart = function (e) {
  10514. if (window.MSGesture === undefined) {
  10515. return;
  10516. }
  10517. if (!_this._MSGestureHandler) {
  10518. _this._MSGestureHandler = new MSGesture();
  10519. _this._MSGestureHandler.target = element;
  10520. }
  10521. _this._MSGestureHandler.addPointer(e.pointerId);
  10522. };
  10523. this._onGesture = function (e) {
  10524. _this.radius *= e.scale;
  10525. if (e.preventDefault) {
  10526. if (!noPreventDefault) {
  10527. e.stopPropagation();
  10528. e.preventDefault();
  10529. }
  10530. }
  10531. };
  10532. this._reset = function () {
  10533. _this._keys = [];
  10534. _this.inertialAlphaOffset = 0;
  10535. _this.inertialBetaOffset = 0;
  10536. _this.inertialRadiusOffset = 0;
  10537. pointers.empty();
  10538. previousPinchDistance = 0;
  10539. cacheSoloPointer = null;
  10540. };
  10541. }
  10542. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10543. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10544. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10545. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10546. element.addEventListener("mousemove", this._onMouseMove, false);
  10547. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10548. element.addEventListener("MSGestureChange", this._onGesture, false);
  10549. element.addEventListener('mousewheel', this._wheel, false);
  10550. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10551. BABYLON.Tools.RegisterTopRootEvents([
  10552. { name: "keydown", handler: this._onKeyDown },
  10553. { name: "keyup", handler: this._onKeyUp },
  10554. { name: "blur", handler: this._onLostFocus }
  10555. ]);
  10556. };
  10557. ArcRotateCamera.prototype.detachControl = function (element) {
  10558. if (this._attachedElement !== element) {
  10559. return;
  10560. }
  10561. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10562. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10563. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10564. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10565. element.removeEventListener("mousemove", this._onMouseMove);
  10566. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10567. element.removeEventListener("MSGestureChange", this._onGesture);
  10568. element.removeEventListener('mousewheel', this._wheel);
  10569. element.removeEventListener('DOMMouseScroll', this._wheel);
  10570. BABYLON.Tools.UnregisterTopRootEvents([
  10571. { name: "keydown", handler: this._onKeyDown },
  10572. { name: "keyup", handler: this._onKeyUp },
  10573. { name: "blur", handler: this._onLostFocus }
  10574. ]);
  10575. this._MSGestureHandler = null;
  10576. this._attachedElement = null;
  10577. if (this._reset) {
  10578. this._reset();
  10579. }
  10580. };
  10581. ArcRotateCamera.prototype._update = function () {
  10582. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10583. if (this._collisionTriggered) {
  10584. return;
  10585. }
  10586. for (var index = 0; index < this._keys.length; index++) {
  10587. var keyCode = this._keys[index];
  10588. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10589. this.inertialAlphaOffset -= 0.01;
  10590. }
  10591. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10592. this.inertialBetaOffset -= 0.01;
  10593. }
  10594. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10595. this.inertialAlphaOffset += 0.01;
  10596. }
  10597. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10598. this.inertialBetaOffset += 0.01;
  10599. }
  10600. }
  10601. // Inertia
  10602. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10603. this.alpha += this.inertialAlphaOffset;
  10604. this.beta += this.inertialBetaOffset;
  10605. this.radius -= this.inertialRadiusOffset;
  10606. this.inertialAlphaOffset *= this.inertia;
  10607. this.inertialBetaOffset *= this.inertia;
  10608. this.inertialRadiusOffset *= this.inertia;
  10609. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10610. this.inertialAlphaOffset = 0;
  10611. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10612. this.inertialBetaOffset = 0;
  10613. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10614. this.inertialRadiusOffset = 0;
  10615. }
  10616. // Limits
  10617. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  10618. this.alpha = this.lowerAlphaLimit;
  10619. }
  10620. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  10621. this.alpha = this.upperAlphaLimit;
  10622. }
  10623. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  10624. this.beta = this.lowerBetaLimit;
  10625. }
  10626. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  10627. this.beta = this.upperBetaLimit;
  10628. }
  10629. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  10630. this.radius = this.lowerRadiusLimit;
  10631. }
  10632. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  10633. this.radius = this.upperRadiusLimit;
  10634. }
  10635. };
  10636. ArcRotateCamera.prototype.setPosition = function (position) {
  10637. var radiusv3 = position.subtract(this._getTargetPosition());
  10638. this.radius = radiusv3.length();
  10639. // Alpha
  10640. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  10641. if (radiusv3.z < 0) {
  10642. this.alpha = 2 * Math.PI - this.alpha;
  10643. }
  10644. // Beta
  10645. this.beta = Math.acos(radiusv3.y / this.radius);
  10646. };
  10647. ArcRotateCamera.prototype._getViewMatrix = function () {
  10648. // Compute
  10649. var cosa = Math.cos(this.alpha);
  10650. var sina = Math.sin(this.alpha);
  10651. var cosb = Math.cos(this.beta);
  10652. var sinb = Math.sin(this.beta);
  10653. var target = this._getTargetPosition();
  10654. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  10655. if (this.checkCollisions) {
  10656. this._collider.radius = this.collisionRadius;
  10657. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  10658. this._collisionTriggered = true;
  10659. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10660. }
  10661. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  10662. this._previousAlpha = this.alpha;
  10663. this._previousBeta = this.beta;
  10664. this._previousRadius = this.radius;
  10665. this._previousPosition.copyFrom(this.position);
  10666. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  10667. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  10668. return this._viewMatrix;
  10669. };
  10670. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  10671. meshes = meshes || this.getScene().meshes;
  10672. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  10673. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  10674. this.radius = distance * this.zoomOnFactor;
  10675. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  10676. };
  10677. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  10678. var meshesOrMinMaxVector;
  10679. var distance;
  10680. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  10681. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  10682. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10683. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  10684. }
  10685. else {
  10686. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  10687. distance = meshesOrMinMaxVectorAndDistance.distance;
  10688. }
  10689. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  10690. this.maxZ = distance * 2;
  10691. };
  10692. return ArcRotateCamera;
  10693. })(BABYLON.Camera);
  10694. BABYLON.ArcRotateCamera = ArcRotateCamera;
  10695. })(BABYLON || (BABYLON = {}));
  10696. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  10697. var __extends = this.__extends || function (d, b) {
  10698. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10699. function __() { this.constructor = d; }
  10700. __.prototype = b.prototype;
  10701. d.prototype = new __();
  10702. };
  10703. var BABYLON;
  10704. (function (BABYLON) {
  10705. // We're mainly based on the logic defined into the FreeCamera code
  10706. var DeviceOrientationCamera = (function (_super) {
  10707. __extends(DeviceOrientationCamera, _super);
  10708. function DeviceOrientationCamera(name, position, scene) {
  10709. var _this = this;
  10710. _super.call(this, name, position, scene);
  10711. this._offsetX = null;
  10712. this._offsetY = null;
  10713. this._orientationGamma = 0;
  10714. this._orientationBeta = 0;
  10715. this._initialOrientationGamma = 0;
  10716. this._initialOrientationBeta = 0;
  10717. this.angularSensibility = 10000.0;
  10718. this.moveSensibility = 50.0;
  10719. window.addEventListener("resize", function () {
  10720. _this._initialOrientationGamma = null;
  10721. }, false);
  10722. }
  10723. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10724. var _this = this;
  10725. if (this._attachedCanvas) {
  10726. return;
  10727. }
  10728. this._attachedCanvas = canvas;
  10729. if (!this._orientationChanged) {
  10730. this._orientationChanged = function (evt) {
  10731. if (!_this._initialOrientationGamma) {
  10732. _this._initialOrientationGamma = evt.gamma;
  10733. _this._initialOrientationBeta = evt.beta;
  10734. }
  10735. _this._orientationGamma = evt.gamma;
  10736. _this._orientationBeta = evt.beta;
  10737. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  10738. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  10739. };
  10740. }
  10741. window.addEventListener("deviceorientation", this._orientationChanged);
  10742. };
  10743. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  10744. if (this._attachedCanvas != canvas) {
  10745. return;
  10746. }
  10747. window.removeEventListener("deviceorientation", this._orientationChanged);
  10748. this._attachedCanvas = null;
  10749. this._orientationGamma = 0;
  10750. this._orientationBeta = 0;
  10751. this._initialOrientationGamma = 0;
  10752. this._initialOrientationBeta = 0;
  10753. };
  10754. DeviceOrientationCamera.prototype._checkInputs = function () {
  10755. if (!this._offsetX) {
  10756. return;
  10757. }
  10758. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  10759. var speed = this._computeLocalCameraSpeed();
  10760. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10761. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10762. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10763. };
  10764. return DeviceOrientationCamera;
  10765. })(BABYLON.FreeCamera);
  10766. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  10767. })(BABYLON || (BABYLON = {}));
  10768. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  10769. var BABYLON;
  10770. (function (BABYLON) {
  10771. var RenderingManager = (function () {
  10772. function RenderingManager(scene) {
  10773. this._renderingGroups = new Array();
  10774. this._scene = scene;
  10775. }
  10776. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10777. if (this._scene._activeParticleSystems.length === 0) {
  10778. return;
  10779. }
  10780. // Particles
  10781. var beforeParticlesDate = BABYLON.Tools.Now;
  10782. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10783. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10784. if (particleSystem.renderingGroupId !== index) {
  10785. continue;
  10786. }
  10787. this._clearDepthBuffer();
  10788. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10789. this._scene._activeParticles += particleSystem.render();
  10790. }
  10791. }
  10792. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10793. };
  10794. RenderingManager.prototype._renderSprites = function (index) {
  10795. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  10796. return;
  10797. }
  10798. // Sprites
  10799. var beforeSpritessDate = BABYLON.Tools.Now;
  10800. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10801. var spriteManager = this._scene.spriteManagers[id];
  10802. if (spriteManager.renderingGroupId === index) {
  10803. this._clearDepthBuffer();
  10804. spriteManager.render();
  10805. }
  10806. }
  10807. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10808. };
  10809. RenderingManager.prototype._clearDepthBuffer = function () {
  10810. if (this._depthBufferAlreadyCleaned) {
  10811. return;
  10812. }
  10813. this._scene.getEngine().clear(0, false, true);
  10814. this._depthBufferAlreadyCleaned = true;
  10815. };
  10816. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10817. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10818. this._depthBufferAlreadyCleaned = false;
  10819. var renderingGroup = this._renderingGroups[index];
  10820. var needToStepBack = false;
  10821. if (renderingGroup) {
  10822. this._clearDepthBuffer();
  10823. if (!renderingGroup.render(customRenderFunction)) {
  10824. this._renderingGroups.splice(index, 1);
  10825. needToStepBack = true;
  10826. }
  10827. }
  10828. if (renderSprites) {
  10829. this._renderSprites(index);
  10830. }
  10831. if (renderParticles) {
  10832. this._renderParticles(index, activeMeshes);
  10833. }
  10834. if (needToStepBack) {
  10835. index--;
  10836. }
  10837. }
  10838. };
  10839. RenderingManager.prototype.reset = function () {
  10840. for (var index in this._renderingGroups) {
  10841. var renderingGroup = this._renderingGroups[index];
  10842. renderingGroup.prepare();
  10843. }
  10844. };
  10845. RenderingManager.prototype.dispatch = function (subMesh) {
  10846. var mesh = subMesh.getMesh();
  10847. var renderingGroupId = mesh.renderingGroupId || 0;
  10848. if (!this._renderingGroups[renderingGroupId]) {
  10849. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10850. }
  10851. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10852. };
  10853. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10854. return RenderingManager;
  10855. })();
  10856. BABYLON.RenderingManager = RenderingManager;
  10857. })(BABYLON || (BABYLON = {}));
  10858. //# sourceMappingURL=babylon.renderingManager.js.map
  10859. var BABYLON;
  10860. (function (BABYLON) {
  10861. var RenderingGroup = (function () {
  10862. function RenderingGroup(index, scene) {
  10863. this.index = index;
  10864. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10865. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10866. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10867. this._scene = scene;
  10868. }
  10869. RenderingGroup.prototype.render = function (customRenderFunction) {
  10870. if (customRenderFunction) {
  10871. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10872. return true;
  10873. }
  10874. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10875. return false;
  10876. }
  10877. var engine = this._scene.getEngine();
  10878. // Opaque
  10879. var subIndex;
  10880. var submesh;
  10881. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10882. submesh = this._opaqueSubMeshes.data[subIndex];
  10883. submesh.render();
  10884. }
  10885. // Alpha test
  10886. engine.setAlphaTesting(true);
  10887. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10888. submesh = this._alphaTestSubMeshes.data[subIndex];
  10889. submesh.render();
  10890. }
  10891. engine.setAlphaTesting(false);
  10892. // Transparent
  10893. if (this._transparentSubMeshes.length) {
  10894. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10895. submesh = this._transparentSubMeshes.data[subIndex];
  10896. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10897. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10898. }
  10899. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10900. sortedArray.sort(function (a, b) {
  10901. // Alpha index first
  10902. if (a._alphaIndex > b._alphaIndex) {
  10903. return 1;
  10904. }
  10905. if (a._alphaIndex < b._alphaIndex) {
  10906. return -1;
  10907. }
  10908. // Then distance to camera
  10909. if (a._distanceToCamera < b._distanceToCamera) {
  10910. return 1;
  10911. }
  10912. if (a._distanceToCamera > b._distanceToCamera) {
  10913. return -1;
  10914. }
  10915. return 0;
  10916. });
  10917. // Rendering
  10918. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10919. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10920. submesh = sortedArray[subIndex];
  10921. submesh.render();
  10922. }
  10923. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10924. }
  10925. return true;
  10926. };
  10927. RenderingGroup.prototype.prepare = function () {
  10928. this._opaqueSubMeshes.reset();
  10929. this._transparentSubMeshes.reset();
  10930. this._alphaTestSubMeshes.reset();
  10931. };
  10932. RenderingGroup.prototype.dispatch = function (subMesh) {
  10933. var material = subMesh.getMaterial();
  10934. var mesh = subMesh.getMesh();
  10935. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10936. this._transparentSubMeshes.push(subMesh);
  10937. }
  10938. else if (material.needAlphaTesting()) {
  10939. this._alphaTestSubMeshes.push(subMesh);
  10940. }
  10941. else {
  10942. this._opaqueSubMeshes.push(subMesh); // Opaque
  10943. }
  10944. };
  10945. return RenderingGroup;
  10946. })();
  10947. BABYLON.RenderingGroup = RenderingGroup;
  10948. })(BABYLON || (BABYLON = {}));
  10949. //# sourceMappingURL=babylon.renderingGroup.js.map
  10950. var BABYLON;
  10951. (function (BABYLON) {
  10952. /**
  10953. * Represents a scene to be rendered by the engine.
  10954. * @see http://doc.babylonjs.com/page.php?p=21911
  10955. */
  10956. var Scene = (function () {
  10957. /**
  10958. * @constructor
  10959. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  10960. */
  10961. function Scene(engine) {
  10962. // Members
  10963. this.autoClear = true;
  10964. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10965. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10966. this.forceWireframe = false;
  10967. this.forcePointsCloud = false;
  10968. this.forceShowBoundingBoxes = false;
  10969. this.animationsEnabled = true;
  10970. 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
  10971. // Fog
  10972. /**
  10973. * is fog enabled on this scene.
  10974. * @type {boolean}
  10975. */
  10976. this.fogEnabled = true;
  10977. this.fogMode = Scene.FOGMODE_NONE;
  10978. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10979. this.fogDensity = 0.1;
  10980. this.fogStart = 0;
  10981. this.fogEnd = 1000.0;
  10982. // Lights
  10983. /**
  10984. * is shadow enabled on this scene.
  10985. * @type {boolean}
  10986. */
  10987. this.shadowsEnabled = true;
  10988. /**
  10989. * is light enabled on this scene.
  10990. * @type {boolean}
  10991. */
  10992. this.lightsEnabled = true;
  10993. /**
  10994. * All of the lights added to this scene.
  10995. * @see BABYLON.Light
  10996. * @type {BABYLON.Light[]}
  10997. */
  10998. this.lights = new Array();
  10999. // Cameras
  11000. /**
  11001. * All of the cameras added to this scene.
  11002. * @see BABYLON.Camera
  11003. * @type {BABYLON.Camera[]}
  11004. */
  11005. this.cameras = new Array();
  11006. this.activeCameras = new Array();
  11007. // Meshes
  11008. /**
  11009. * All of the (abstract) meshes added to this scene.
  11010. * @see BABYLON.AbstractMesh
  11011. * @type {BABYLON.AbstractMesh[]}
  11012. */
  11013. this.meshes = new Array();
  11014. // Geometries
  11015. this._geometries = new Array();
  11016. this.materials = new Array();
  11017. this.multiMaterials = new Array();
  11018. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11019. // Textures
  11020. this.texturesEnabled = true;
  11021. this.textures = new Array();
  11022. // Particles
  11023. this.particlesEnabled = true;
  11024. this.particleSystems = new Array();
  11025. // Sprites
  11026. this.spritesEnabled = true;
  11027. this.spriteManagers = new Array();
  11028. // Layers
  11029. this.layers = new Array();
  11030. // Skeletons
  11031. this.skeletonsEnabled = true;
  11032. this.skeletons = new Array();
  11033. // Lens flares
  11034. this.lensFlaresEnabled = true;
  11035. this.lensFlareSystems = new Array();
  11036. // Collisions
  11037. this.collisionsEnabled = true;
  11038. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  11039. // Postprocesses
  11040. this.postProcessesEnabled = true;
  11041. // Customs render targets
  11042. this.renderTargetsEnabled = true;
  11043. this.dumpNextRenderTargets = false;
  11044. this.customRenderTargets = new Array();
  11045. // Imported meshes
  11046. this.importedMeshesFiles = new Array();
  11047. this._actionManagers = new Array();
  11048. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11049. // Procedural textures
  11050. this.proceduralTexturesEnabled = true;
  11051. this._proceduralTextures = new Array();
  11052. this.soundTracks = new Array();
  11053. this._audioEnabled = true;
  11054. this._headphone = false;
  11055. this._totalVertices = 0;
  11056. this._activeIndices = 0;
  11057. this._activeParticles = 0;
  11058. this._lastFrameDuration = 0;
  11059. this._evaluateActiveMeshesDuration = 0;
  11060. this._renderTargetsDuration = 0;
  11061. this._particlesDuration = 0;
  11062. this._renderDuration = 0;
  11063. this._spritesDuration = 0;
  11064. this._animationRatio = 0;
  11065. this._renderId = 0;
  11066. this._executeWhenReadyTimeoutId = -1;
  11067. this._toBeDisposed = new BABYLON.SmartArray(256);
  11068. this._onReadyCallbacks = new Array();
  11069. this._pendingData = []; //ANY
  11070. this._onBeforeRenderCallbacks = new Array();
  11071. this._onAfterRenderCallbacks = new Array();
  11072. this._activeMeshes = new BABYLON.SmartArray(256);
  11073. this._processedMaterials = new BABYLON.SmartArray(256);
  11074. this._renderTargets = new BABYLON.SmartArray(256);
  11075. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11076. this._activeSkeletons = new BABYLON.SmartArray(32);
  11077. this._activeBones = 0;
  11078. this._activeAnimatables = new Array();
  11079. this._transformMatrix = BABYLON.Matrix.Zero();
  11080. this._uniqueIdCounter = 0;
  11081. this._engine = engine;
  11082. engine.scenes.push(this);
  11083. this._renderingManager = new BABYLON.RenderingManager(this);
  11084. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11085. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11086. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11087. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11088. this.attachControl();
  11089. this._debugLayer = new BABYLON.DebugLayer(this);
  11090. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11091. //simplification queue
  11092. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11093. //collision coordinator initialization. For now legacy per default.
  11094. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11095. }
  11096. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11097. get: function () {
  11098. return Scene._FOGMODE_NONE;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11104. get: function () {
  11105. return Scene._FOGMODE_EXP;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11111. get: function () {
  11112. return Scene._FOGMODE_EXP2;
  11113. },
  11114. enumerable: true,
  11115. configurable: true
  11116. });
  11117. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11118. get: function () {
  11119. return Scene._FOGMODE_LINEAR;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Scene.prototype, "debugLayer", {
  11125. // Properties
  11126. get: function () {
  11127. return this._debugLayer;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11133. get: function () {
  11134. return this._workerCollisions;
  11135. },
  11136. set: function (enabled) {
  11137. enabled = (enabled && !!Worker);
  11138. this._workerCollisions = enabled;
  11139. if (this.collisionCoordinator) {
  11140. this.collisionCoordinator.destroy();
  11141. }
  11142. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11143. this.collisionCoordinator.init(this);
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11149. /**
  11150. * The mesh that is currently under the pointer.
  11151. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11152. */
  11153. get: function () {
  11154. return this._meshUnderPointer;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(Scene.prototype, "pointerX", {
  11160. /**
  11161. * Current on-screen X position of the pointer
  11162. * @return {number} X position of the pointer
  11163. */
  11164. get: function () {
  11165. return this._pointerX;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Scene.prototype, "pointerY", {
  11171. /**
  11172. * Current on-screen Y position of the pointer
  11173. * @return {number} Y position of the pointer
  11174. */
  11175. get: function () {
  11176. return this._pointerY;
  11177. },
  11178. enumerable: true,
  11179. configurable: true
  11180. });
  11181. Scene.prototype.getCachedMaterial = function () {
  11182. return this._cachedMaterial;
  11183. };
  11184. Scene.prototype.getBoundingBoxRenderer = function () {
  11185. return this._boundingBoxRenderer;
  11186. };
  11187. Scene.prototype.getOutlineRenderer = function () {
  11188. return this._outlineRenderer;
  11189. };
  11190. Scene.prototype.getEngine = function () {
  11191. return this._engine;
  11192. };
  11193. Scene.prototype.getTotalVertices = function () {
  11194. return this._totalVertices;
  11195. };
  11196. Scene.prototype.getActiveIndices = function () {
  11197. return this._activeIndices;
  11198. };
  11199. Scene.prototype.getActiveParticles = function () {
  11200. return this._activeParticles;
  11201. };
  11202. Scene.prototype.getActiveBones = function () {
  11203. return this._activeBones;
  11204. };
  11205. // Stats
  11206. Scene.prototype.getLastFrameDuration = function () {
  11207. return this._lastFrameDuration;
  11208. };
  11209. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11210. return this._evaluateActiveMeshesDuration;
  11211. };
  11212. Scene.prototype.getActiveMeshes = function () {
  11213. return this._activeMeshes;
  11214. };
  11215. Scene.prototype.getRenderTargetsDuration = function () {
  11216. return this._renderTargetsDuration;
  11217. };
  11218. Scene.prototype.getRenderDuration = function () {
  11219. return this._renderDuration;
  11220. };
  11221. Scene.prototype.getParticlesDuration = function () {
  11222. return this._particlesDuration;
  11223. };
  11224. Scene.prototype.getSpritesDuration = function () {
  11225. return this._spritesDuration;
  11226. };
  11227. Scene.prototype.getAnimationRatio = function () {
  11228. return this._animationRatio;
  11229. };
  11230. Scene.prototype.getRenderId = function () {
  11231. return this._renderId;
  11232. };
  11233. Scene.prototype.incrementRenderId = function () {
  11234. this._renderId++;
  11235. };
  11236. Scene.prototype._updatePointerPosition = function (evt) {
  11237. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11238. this._pointerX = evt.clientX - canvasRect.left;
  11239. this._pointerY = evt.clientY - canvasRect.top;
  11240. if (this.cameraToUseForPointers) {
  11241. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11242. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11243. }
  11244. };
  11245. // Pointers handling
  11246. Scene.prototype.attachControl = function () {
  11247. var _this = this;
  11248. this._onPointerMove = function (evt) {
  11249. var canvas = _this._engine.getRenderingCanvas();
  11250. _this._updatePointerPosition(evt);
  11251. 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);
  11252. if (pickResult.hit) {
  11253. _this._meshUnderPointer = pickResult.pickedMesh;
  11254. _this.setPointerOverMesh(pickResult.pickedMesh);
  11255. canvas.style.cursor = "pointer";
  11256. }
  11257. else {
  11258. _this.setPointerOverMesh(null);
  11259. canvas.style.cursor = "";
  11260. _this._meshUnderPointer = null;
  11261. }
  11262. };
  11263. this._onPointerDown = function (evt) {
  11264. var predicate = null;
  11265. if (!_this.onPointerDown) {
  11266. predicate = function (mesh) {
  11267. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11268. };
  11269. }
  11270. _this._updatePointerPosition(evt);
  11271. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11272. if (pickResult.hit) {
  11273. if (pickResult.pickedMesh.actionManager) {
  11274. switch (evt.button) {
  11275. case 0:
  11276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11277. break;
  11278. case 1:
  11279. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11280. break;
  11281. case 2:
  11282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11283. break;
  11284. }
  11285. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11286. }
  11287. }
  11288. if (_this.onPointerDown) {
  11289. _this.onPointerDown(evt, pickResult);
  11290. }
  11291. };
  11292. this._onPointerUp = function (evt) {
  11293. var predicate = null;
  11294. if (!_this.onPointerUp) {
  11295. predicate = function (mesh) {
  11296. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11297. };
  11298. }
  11299. _this._updatePointerPosition(evt);
  11300. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11301. if (pickResult.hit) {
  11302. if (pickResult.pickedMesh.actionManager) {
  11303. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11304. }
  11305. }
  11306. if (_this.onPointerUp) {
  11307. _this.onPointerUp(evt, pickResult);
  11308. }
  11309. };
  11310. this._onKeyDown = function (evt) {
  11311. if (_this.actionManager) {
  11312. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11313. }
  11314. };
  11315. this._onKeyUp = function (evt) {
  11316. if (_this.actionManager) {
  11317. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11318. }
  11319. };
  11320. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11321. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11322. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11323. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11324. BABYLON.Tools.RegisterTopRootEvents([
  11325. { name: "keydown", handler: this._onKeyDown },
  11326. { name: "keyup", handler: this._onKeyUp }
  11327. ]);
  11328. };
  11329. Scene.prototype.detachControl = function () {
  11330. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11331. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11332. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11333. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11334. BABYLON.Tools.UnregisterTopRootEvents([
  11335. { name: "keydown", handler: this._onKeyDown },
  11336. { name: "keyup", handler: this._onKeyUp }
  11337. ]);
  11338. };
  11339. // Ready
  11340. Scene.prototype.isReady = function () {
  11341. if (this._pendingData.length > 0) {
  11342. return false;
  11343. }
  11344. for (var index = 0; index < this._geometries.length; index++) {
  11345. var geometry = this._geometries[index];
  11346. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11347. return false;
  11348. }
  11349. }
  11350. for (index = 0; index < this.meshes.length; index++) {
  11351. var mesh = this.meshes[index];
  11352. if (!mesh.isReady()) {
  11353. return false;
  11354. }
  11355. var mat = mesh.material;
  11356. if (mat) {
  11357. if (!mat.isReady(mesh)) {
  11358. return false;
  11359. }
  11360. }
  11361. }
  11362. return true;
  11363. };
  11364. Scene.prototype.resetCachedMaterial = function () {
  11365. this._cachedMaterial = null;
  11366. };
  11367. Scene.prototype.registerBeforeRender = function (func) {
  11368. this._onBeforeRenderCallbacks.push(func);
  11369. };
  11370. Scene.prototype.unregisterBeforeRender = function (func) {
  11371. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11372. if (index > -1) {
  11373. this._onBeforeRenderCallbacks.splice(index, 1);
  11374. }
  11375. };
  11376. Scene.prototype.registerAfterRender = function (func) {
  11377. this._onAfterRenderCallbacks.push(func);
  11378. };
  11379. Scene.prototype.unregisterAfterRender = function (func) {
  11380. var index = this._onAfterRenderCallbacks.indexOf(func);
  11381. if (index > -1) {
  11382. this._onAfterRenderCallbacks.splice(index, 1);
  11383. }
  11384. };
  11385. Scene.prototype._addPendingData = function (data) {
  11386. this._pendingData.push(data);
  11387. };
  11388. Scene.prototype._removePendingData = function (data) {
  11389. var index = this._pendingData.indexOf(data);
  11390. if (index !== -1) {
  11391. this._pendingData.splice(index, 1);
  11392. }
  11393. };
  11394. Scene.prototype.getWaitingItemsCount = function () {
  11395. return this._pendingData.length;
  11396. };
  11397. /**
  11398. * Registers a function to be executed when the scene is ready.
  11399. * @param {Function} func - the function to be executed.
  11400. */
  11401. Scene.prototype.executeWhenReady = function (func) {
  11402. var _this = this;
  11403. this._onReadyCallbacks.push(func);
  11404. if (this._executeWhenReadyTimeoutId !== -1) {
  11405. return;
  11406. }
  11407. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11408. _this._checkIsReady();
  11409. }, 150);
  11410. };
  11411. Scene.prototype._checkIsReady = function () {
  11412. var _this = this;
  11413. if (this.isReady()) {
  11414. this._onReadyCallbacks.forEach(function (func) {
  11415. func();
  11416. });
  11417. this._onReadyCallbacks = [];
  11418. this._executeWhenReadyTimeoutId = -1;
  11419. return;
  11420. }
  11421. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11422. _this._checkIsReady();
  11423. }, 150);
  11424. };
  11425. // Animations
  11426. /**
  11427. * Will start the animation sequence of a given target
  11428. * @param target - the target
  11429. * @param {number} from - from which frame should animation start
  11430. * @param {number} to - till which frame should animation run.
  11431. * @param {boolean} [loop] - should the animation loop
  11432. * @param {number} [speedRatio] - the speed in which to run the animation
  11433. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11434. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11435. * @return {BABYLON.Animatable} the animatable object created for this animation
  11436. * @see BABYLON.Animatable
  11437. * @see http://doc.babylonjs.com/page.php?p=22081
  11438. */
  11439. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11440. if (speedRatio === undefined) {
  11441. speedRatio = 1.0;
  11442. }
  11443. this.stopAnimation(target);
  11444. if (!animatable) {
  11445. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11446. }
  11447. // Local animations
  11448. if (target.animations) {
  11449. animatable.appendAnimations(target, target.animations);
  11450. }
  11451. // Children animations
  11452. if (target.getAnimatables) {
  11453. var animatables = target.getAnimatables();
  11454. for (var index = 0; index < animatables.length; index++) {
  11455. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11456. }
  11457. }
  11458. return animatable;
  11459. };
  11460. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11461. if (speedRatio === undefined) {
  11462. speedRatio = 1.0;
  11463. }
  11464. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11465. return animatable;
  11466. };
  11467. Scene.prototype.getAnimatableByTarget = function (target) {
  11468. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11469. if (this._activeAnimatables[index].target === target) {
  11470. return this._activeAnimatables[index];
  11471. }
  11472. }
  11473. return null;
  11474. };
  11475. /**
  11476. * Will stop the animation of the given target
  11477. * @param target - the target
  11478. * @see beginAnimation
  11479. */
  11480. Scene.prototype.stopAnimation = function (target) {
  11481. var animatable = this.getAnimatableByTarget(target);
  11482. if (animatable) {
  11483. animatable.stop();
  11484. }
  11485. };
  11486. Scene.prototype._animate = function () {
  11487. if (!this.animationsEnabled) {
  11488. return;
  11489. }
  11490. if (!this._animationStartDate) {
  11491. this._animationStartDate = BABYLON.Tools.Now;
  11492. }
  11493. // Getting time
  11494. var now = BABYLON.Tools.Now;
  11495. var delay = now - this._animationStartDate;
  11496. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11497. this._activeAnimatables[index]._animate(delay);
  11498. }
  11499. };
  11500. // Matrix
  11501. Scene.prototype.getViewMatrix = function () {
  11502. return this._viewMatrix;
  11503. };
  11504. Scene.prototype.getProjectionMatrix = function () {
  11505. return this._projectionMatrix;
  11506. };
  11507. Scene.prototype.getTransformMatrix = function () {
  11508. return this._transformMatrix;
  11509. };
  11510. Scene.prototype.setTransformMatrix = function (view, projection) {
  11511. this._viewMatrix = view;
  11512. this._projectionMatrix = projection;
  11513. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11514. };
  11515. // Methods
  11516. Scene.prototype.addMesh = function (newMesh) {
  11517. newMesh.uniqueId = this._uniqueIdCounter++;
  11518. var position = this.meshes.push(newMesh);
  11519. //notify the collision coordinator
  11520. this.collisionCoordinator.onMeshAdded(newMesh);
  11521. if (this.onNewMeshAdded) {
  11522. this.onNewMeshAdded(newMesh, position, this);
  11523. }
  11524. };
  11525. Scene.prototype.removeMesh = function (toRemove) {
  11526. var index = this.meshes.indexOf(toRemove);
  11527. if (index !== -1) {
  11528. // Remove from the scene if mesh found
  11529. this.meshes.splice(index, 1);
  11530. }
  11531. //notify the collision coordinator
  11532. this.collisionCoordinator.onMeshRemoved(toRemove);
  11533. if (this.onMeshRemoved) {
  11534. this.onMeshRemoved(toRemove);
  11535. }
  11536. return index;
  11537. };
  11538. Scene.prototype.removeLight = function (toRemove) {
  11539. var index = this.lights.indexOf(toRemove);
  11540. if (index !== -1) {
  11541. // Remove from the scene if mesh found
  11542. this.lights.splice(index, 1);
  11543. }
  11544. if (this.onLightRemoved) {
  11545. this.onLightRemoved(toRemove);
  11546. }
  11547. return index;
  11548. };
  11549. Scene.prototype.removeCamera = function (toRemove) {
  11550. var index = this.cameras.indexOf(toRemove);
  11551. if (index !== -1) {
  11552. // Remove from the scene if mesh found
  11553. this.cameras.splice(index, 1);
  11554. }
  11555. // Remove from activeCameras
  11556. var index2 = this.activeCameras.indexOf(toRemove);
  11557. if (index2 !== -1) {
  11558. // Remove from the scene if mesh found
  11559. this.activeCameras.splice(index2, 1);
  11560. }
  11561. // Reset the activeCamera
  11562. if (this.activeCamera === toRemove) {
  11563. if (this.cameras.length > 0) {
  11564. this.activeCamera = this.cameras[0];
  11565. }
  11566. else {
  11567. this.activeCamera = null;
  11568. }
  11569. }
  11570. if (this.onCameraRemoved) {
  11571. this.onCameraRemoved(toRemove);
  11572. }
  11573. return index;
  11574. };
  11575. Scene.prototype.addLight = function (newLight) {
  11576. newLight.uniqueId = this._uniqueIdCounter++;
  11577. var position = this.lights.push(newLight);
  11578. if (this.onNewLightAdded) {
  11579. this.onNewLightAdded(newLight, position, this);
  11580. }
  11581. };
  11582. Scene.prototype.addCamera = function (newCamera) {
  11583. newCamera.uniqueId = this._uniqueIdCounter++;
  11584. var position = this.cameras.push(newCamera);
  11585. if (this.onNewCameraAdded) {
  11586. this.onNewCameraAdded(newCamera, position, this);
  11587. }
  11588. };
  11589. /**
  11590. * sets the active camera of the scene using its ID
  11591. * @param {string} id - the camera's ID
  11592. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11593. * @see activeCamera
  11594. */
  11595. Scene.prototype.setActiveCameraByID = function (id) {
  11596. var camera = this.getCameraByID(id);
  11597. if (camera) {
  11598. this.activeCamera = camera;
  11599. return camera;
  11600. }
  11601. return null;
  11602. };
  11603. /**
  11604. * sets the active camera of the scene using its name
  11605. * @param {string} name - the camera's name
  11606. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11607. * @see activeCamera
  11608. */
  11609. Scene.prototype.setActiveCameraByName = function (name) {
  11610. var camera = this.getCameraByName(name);
  11611. if (camera) {
  11612. this.activeCamera = camera;
  11613. return camera;
  11614. }
  11615. return null;
  11616. };
  11617. /**
  11618. * get a material using its id
  11619. * @param {string} the material's ID
  11620. * @return {BABYLON.Material|null} the material or null if none found.
  11621. */
  11622. Scene.prototype.getMaterialByID = function (id) {
  11623. for (var index = 0; index < this.materials.length; index++) {
  11624. if (this.materials[index].id === id) {
  11625. return this.materials[index];
  11626. }
  11627. }
  11628. return null;
  11629. };
  11630. /**
  11631. * get a material using its name
  11632. * @param {string} the material's name
  11633. * @return {BABYLON.Material|null} the material or null if none found.
  11634. */
  11635. Scene.prototype.getMaterialByName = function (name) {
  11636. for (var index = 0; index < this.materials.length; index++) {
  11637. if (this.materials[index].name === name) {
  11638. return this.materials[index];
  11639. }
  11640. }
  11641. return null;
  11642. };
  11643. Scene.prototype.getCameraByID = function (id) {
  11644. for (var index = 0; index < this.cameras.length; index++) {
  11645. if (this.cameras[index].id === id) {
  11646. return this.cameras[index];
  11647. }
  11648. }
  11649. return null;
  11650. };
  11651. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  11652. for (var index = 0; index < this.cameras.length; index++) {
  11653. if (this.cameras[index].uniqueId === uniqueId) {
  11654. return this.cameras[index];
  11655. }
  11656. }
  11657. return null;
  11658. };
  11659. /**
  11660. * get a camera using its name
  11661. * @param {string} the camera's name
  11662. * @return {BABYLON.Camera|null} the camera or null if none found.
  11663. */
  11664. Scene.prototype.getCameraByName = function (name) {
  11665. for (var index = 0; index < this.cameras.length; index++) {
  11666. if (this.cameras[index].name === name) {
  11667. return this.cameras[index];
  11668. }
  11669. }
  11670. return null;
  11671. };
  11672. /**
  11673. * get a light node using its name
  11674. * @param {string} the light's name
  11675. * @return {BABYLON.Light|null} the light or null if none found.
  11676. */
  11677. Scene.prototype.getLightByName = function (name) {
  11678. for (var index = 0; index < this.lights.length; index++) {
  11679. if (this.lights[index].name === name) {
  11680. return this.lights[index];
  11681. }
  11682. }
  11683. return null;
  11684. };
  11685. /**
  11686. * get a light node using its ID
  11687. * @param {string} the light's id
  11688. * @return {BABYLON.Light|null} the light or null if none found.
  11689. */
  11690. Scene.prototype.getLightByID = function (id) {
  11691. for (var index = 0; index < this.lights.length; index++) {
  11692. if (this.lights[index].id === id) {
  11693. return this.lights[index];
  11694. }
  11695. }
  11696. return null;
  11697. };
  11698. /**
  11699. * get a light node using its scene-generated unique ID
  11700. * @param {number} the light's unique id
  11701. * @return {BABYLON.Light|null} the light or null if none found.
  11702. */
  11703. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  11704. for (var index = 0; index < this.lights.length; index++) {
  11705. if (this.lights[index].uniqueId === uniqueId) {
  11706. return this.lights[index];
  11707. }
  11708. }
  11709. return null;
  11710. };
  11711. /**
  11712. * get a geometry using its ID
  11713. * @param {string} the geometry's id
  11714. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  11715. */
  11716. Scene.prototype.getGeometryByID = function (id) {
  11717. for (var index = 0; index < this._geometries.length; index++) {
  11718. if (this._geometries[index].id === id) {
  11719. return this._geometries[index];
  11720. }
  11721. }
  11722. return null;
  11723. };
  11724. /**
  11725. * add a new geometry to this scene.
  11726. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  11727. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  11728. * @return {boolean} was the geometry added or not
  11729. */
  11730. Scene.prototype.pushGeometry = function (geometry, force) {
  11731. if (!force && this.getGeometryByID(geometry.id)) {
  11732. return false;
  11733. }
  11734. this._geometries.push(geometry);
  11735. //notify the collision coordinator
  11736. this.collisionCoordinator.onGeometryAdded(geometry);
  11737. if (this.onGeometryAdded) {
  11738. this.onGeometryAdded(geometry);
  11739. }
  11740. return true;
  11741. };
  11742. /**
  11743. * Removes an existing geometry
  11744. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  11745. * @return {boolean} was the geometry removed or not
  11746. */
  11747. Scene.prototype.removeGeometry = function (geometry) {
  11748. var index = this._geometries.indexOf(geometry);
  11749. if (index > -1) {
  11750. this._geometries.splice(index, 1);
  11751. //notify the collision coordinator
  11752. this.collisionCoordinator.onGeometryDeleted(geometry);
  11753. if (this.onGeometryRemoved) {
  11754. this.onGeometryRemoved(geometry);
  11755. }
  11756. return true;
  11757. }
  11758. return false;
  11759. };
  11760. Scene.prototype.getGeometries = function () {
  11761. return this._geometries;
  11762. };
  11763. /**
  11764. * Get the first added mesh found of a given ID
  11765. * @param {string} id - the id to search for
  11766. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11767. */
  11768. Scene.prototype.getMeshByID = function (id) {
  11769. for (var index = 0; index < this.meshes.length; index++) {
  11770. if (this.meshes[index].id === id) {
  11771. return this.meshes[index];
  11772. }
  11773. }
  11774. return null;
  11775. };
  11776. /**
  11777. * Get a mesh with its auto-generated unique id
  11778. * @param {number} uniqueId - the unique id to search for
  11779. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11780. */
  11781. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  11782. for (var index = 0; index < this.meshes.length; index++) {
  11783. if (this.meshes[index].uniqueId === uniqueId) {
  11784. return this.meshes[index];
  11785. }
  11786. }
  11787. return null;
  11788. };
  11789. /**
  11790. * Get a the last added mesh found of a given ID
  11791. * @param {string} id - the id to search for
  11792. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11793. */
  11794. Scene.prototype.getLastMeshByID = function (id) {
  11795. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11796. if (this.meshes[index].id === id) {
  11797. return this.meshes[index];
  11798. }
  11799. }
  11800. return null;
  11801. };
  11802. /**
  11803. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  11804. * @param {string} id - the id to search for
  11805. * @return {BABYLON.Node|null} the node found or null if not found at all.
  11806. */
  11807. Scene.prototype.getLastEntryByID = function (id) {
  11808. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11809. if (this.meshes[index].id === id) {
  11810. return this.meshes[index];
  11811. }
  11812. }
  11813. for (index = this.cameras.length - 1; index >= 0; index--) {
  11814. if (this.cameras[index].id === id) {
  11815. return this.cameras[index];
  11816. }
  11817. }
  11818. for (index = this.lights.length - 1; index >= 0; index--) {
  11819. if (this.lights[index].id === id) {
  11820. return this.lights[index];
  11821. }
  11822. }
  11823. return null;
  11824. };
  11825. Scene.prototype.getNodeByName = function (name) {
  11826. var mesh = this.getMeshByName(name);
  11827. if (mesh) {
  11828. return mesh;
  11829. }
  11830. var light = this.getLightByName(name);
  11831. if (light) {
  11832. return light;
  11833. }
  11834. return this.getCameraByName(name);
  11835. };
  11836. Scene.prototype.getMeshByName = function (name) {
  11837. for (var index = 0; index < this.meshes.length; index++) {
  11838. if (this.meshes[index].name === name) {
  11839. return this.meshes[index];
  11840. }
  11841. }
  11842. return null;
  11843. };
  11844. Scene.prototype.getSoundByName = function (name) {
  11845. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  11846. if (this.mainSoundTrack.soundCollection[index].name === name) {
  11847. return this.mainSoundTrack.soundCollection[index];
  11848. }
  11849. }
  11850. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  11851. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  11852. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  11853. return this.soundTracks[sdIndex].soundCollection[index];
  11854. }
  11855. }
  11856. }
  11857. return null;
  11858. };
  11859. Scene.prototype.getLastSkeletonByID = function (id) {
  11860. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  11861. if (this.skeletons[index].id === id) {
  11862. return this.skeletons[index];
  11863. }
  11864. }
  11865. return null;
  11866. };
  11867. Scene.prototype.getSkeletonById = function (id) {
  11868. for (var index = 0; index < this.skeletons.length; index++) {
  11869. if (this.skeletons[index].id === id) {
  11870. return this.skeletons[index];
  11871. }
  11872. }
  11873. return null;
  11874. };
  11875. Scene.prototype.getSkeletonByName = function (name) {
  11876. for (var index = 0; index < this.skeletons.length; index++) {
  11877. if (this.skeletons[index].name === name) {
  11878. return this.skeletons[index];
  11879. }
  11880. }
  11881. return null;
  11882. };
  11883. Scene.prototype.isActiveMesh = function (mesh) {
  11884. return (this._activeMeshes.indexOf(mesh) !== -1);
  11885. };
  11886. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  11887. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  11888. var material = subMesh.getMaterial();
  11889. if (mesh.showSubMeshesBoundingBox) {
  11890. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  11891. }
  11892. if (material) {
  11893. // Render targets
  11894. if (material.getRenderTargetTextures) {
  11895. if (this._processedMaterials.indexOf(material) === -1) {
  11896. this._processedMaterials.push(material);
  11897. this._renderTargets.concat(material.getRenderTargetTextures());
  11898. }
  11899. }
  11900. // Dispatch
  11901. this._activeIndices += subMesh.indexCount;
  11902. this._renderingManager.dispatch(subMesh);
  11903. }
  11904. }
  11905. };
  11906. Scene.prototype._evaluateActiveMeshes = function () {
  11907. this.activeCamera._activeMeshes.reset();
  11908. this._activeMeshes.reset();
  11909. this._renderingManager.reset();
  11910. this._processedMaterials.reset();
  11911. this._activeParticleSystems.reset();
  11912. this._activeSkeletons.reset();
  11913. this._boundingBoxRenderer.reset();
  11914. if (!this._frustumPlanes) {
  11915. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  11916. }
  11917. else {
  11918. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  11919. }
  11920. // Meshes
  11921. var meshes;
  11922. var len;
  11923. if (this._selectionOctree) {
  11924. var selection = this._selectionOctree.select(this._frustumPlanes);
  11925. meshes = selection.data;
  11926. len = selection.length;
  11927. }
  11928. else {
  11929. len = this.meshes.length;
  11930. meshes = this.meshes;
  11931. }
  11932. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  11933. var mesh = meshes[meshIndex];
  11934. if (mesh.isBlocked) {
  11935. continue;
  11936. }
  11937. this._totalVertices += mesh.getTotalVertices();
  11938. if (!mesh.isReady() || !mesh.isEnabled()) {
  11939. continue;
  11940. }
  11941. mesh.computeWorldMatrix();
  11942. // Intersections
  11943. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  11944. this._meshesForIntersections.pushNoDuplicate(mesh);
  11945. }
  11946. // Switch to current LOD
  11947. var meshLOD = mesh.getLOD(this.activeCamera);
  11948. if (!meshLOD) {
  11949. continue;
  11950. }
  11951. mesh._preActivate();
  11952. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  11953. this._activeMeshes.push(mesh);
  11954. this.activeCamera._activeMeshes.push(mesh);
  11955. mesh._activate(this._renderId);
  11956. this._activeMesh(meshLOD);
  11957. }
  11958. }
  11959. // Particle systems
  11960. var beforeParticlesDate = BABYLON.Tools.Now;
  11961. if (this.particlesEnabled) {
  11962. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  11963. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  11964. var particleSystem = this.particleSystems[particleIndex];
  11965. if (!particleSystem.isStarted()) {
  11966. continue;
  11967. }
  11968. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  11969. this._activeParticleSystems.push(particleSystem);
  11970. particleSystem.animate();
  11971. }
  11972. }
  11973. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  11974. }
  11975. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11976. };
  11977. Scene.prototype._activeMesh = function (mesh) {
  11978. if (mesh.skeleton && this.skeletonsEnabled) {
  11979. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  11980. }
  11981. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  11982. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  11983. }
  11984. if (mesh && mesh.subMeshes) {
  11985. // Submeshes Octrees
  11986. var len;
  11987. var subMeshes;
  11988. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  11989. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  11990. len = intersections.length;
  11991. subMeshes = intersections.data;
  11992. }
  11993. else {
  11994. subMeshes = mesh.subMeshes;
  11995. len = subMeshes.length;
  11996. }
  11997. for (var subIndex = 0; subIndex < len; subIndex++) {
  11998. var subMesh = subMeshes[subIndex];
  11999. this._evaluateSubMesh(subMesh, mesh);
  12000. }
  12001. }
  12002. };
  12003. Scene.prototype.updateTransformMatrix = function (force) {
  12004. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12005. };
  12006. Scene.prototype._renderForCamera = function (camera) {
  12007. var engine = this._engine;
  12008. this.activeCamera = camera;
  12009. if (!this.activeCamera)
  12010. throw new Error("Active camera not set");
  12011. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12012. // Viewport
  12013. engine.setViewport(this.activeCamera.viewport);
  12014. // Camera
  12015. this._renderId++;
  12016. this.updateTransformMatrix();
  12017. if (this.beforeCameraRender) {
  12018. this.beforeCameraRender(this.activeCamera);
  12019. }
  12020. // Meshes
  12021. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12022. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12023. this._evaluateActiveMeshes();
  12024. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12025. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12026. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12027. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12028. skeleton.prepare();
  12029. }
  12030. // Render targets
  12031. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12032. if (this.renderTargetsEnabled) {
  12033. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12034. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12035. var renderTarget = this._renderTargets.data[renderIndex];
  12036. if (renderTarget._shouldRender()) {
  12037. this._renderId++;
  12038. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12039. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12040. }
  12041. }
  12042. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12043. this._renderId++;
  12044. }
  12045. if (this._renderTargets.length > 0) {
  12046. engine.restoreDefaultFramebuffer();
  12047. }
  12048. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12049. // Prepare Frame
  12050. this.postProcessManager._prepareFrame();
  12051. var beforeRenderDate = BABYLON.Tools.Now;
  12052. // Backgrounds
  12053. if (this.layers.length) {
  12054. engine.setDepthBuffer(false);
  12055. var layerIndex;
  12056. var layer;
  12057. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12058. layer = this.layers[layerIndex];
  12059. if (layer.isBackground) {
  12060. layer.render();
  12061. }
  12062. }
  12063. engine.setDepthBuffer(true);
  12064. }
  12065. // Render
  12066. BABYLON.Tools.StartPerformanceCounter("Main render");
  12067. this._renderingManager.render(null, null, true, true);
  12068. BABYLON.Tools.EndPerformanceCounter("Main render");
  12069. // Bounding boxes
  12070. this._boundingBoxRenderer.render();
  12071. // Lens flares
  12072. if (this.lensFlaresEnabled) {
  12073. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12074. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12075. this.lensFlareSystems[lensFlareSystemIndex].render();
  12076. }
  12077. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12078. }
  12079. // Foregrounds
  12080. if (this.layers.length) {
  12081. engine.setDepthBuffer(false);
  12082. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12083. layer = this.layers[layerIndex];
  12084. if (!layer.isBackground) {
  12085. layer.render();
  12086. }
  12087. }
  12088. engine.setDepthBuffer(true);
  12089. }
  12090. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12091. // Finalize frame
  12092. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12093. // Update camera
  12094. this.activeCamera._updateFromScene();
  12095. // Reset some special arrays
  12096. this._renderTargets.reset();
  12097. if (this.afterCameraRender) {
  12098. this.afterCameraRender(this.activeCamera);
  12099. }
  12100. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12101. };
  12102. Scene.prototype._processSubCameras = function (camera) {
  12103. if (camera.subCameras.length === 0) {
  12104. this._renderForCamera(camera);
  12105. return;
  12106. }
  12107. for (var index = 0; index < camera.subCameras.length; index++) {
  12108. this._renderForCamera(camera.subCameras[index]);
  12109. }
  12110. this.activeCamera = camera;
  12111. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12112. // Update camera
  12113. this.activeCamera._updateFromScene();
  12114. };
  12115. Scene.prototype._checkIntersections = function () {
  12116. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12117. var sourceMesh = this._meshesForIntersections.data[index];
  12118. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12119. var action = sourceMesh.actionManager.actions[actionIndex];
  12120. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12121. var parameters = action.getTriggerParameter();
  12122. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12123. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12124. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12125. if (areIntersecting && currentIntersectionInProgress === -1) {
  12126. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12127. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12128. sourceMesh._intersectionsInProgress.push(otherMesh);
  12129. }
  12130. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12131. sourceMesh._intersectionsInProgress.push(otherMesh);
  12132. }
  12133. }
  12134. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12135. //They intersected, and now they don't.
  12136. //is this trigger an exit trigger? execute an event.
  12137. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12138. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12139. }
  12140. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12141. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12142. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12143. }
  12144. }
  12145. }
  12146. }
  12147. }
  12148. };
  12149. Scene.prototype.render = function () {
  12150. var startDate = BABYLON.Tools.Now;
  12151. this._particlesDuration = 0;
  12152. this._spritesDuration = 0;
  12153. this._activeParticles = 0;
  12154. this._renderDuration = 0;
  12155. this._renderTargetsDuration = 0;
  12156. this._evaluateActiveMeshesDuration = 0;
  12157. this._totalVertices = 0;
  12158. this._activeIndices = 0;
  12159. this._activeBones = 0;
  12160. this.getEngine().resetDrawCalls();
  12161. this._meshesForIntersections.reset();
  12162. this.resetCachedMaterial();
  12163. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12164. // Actions
  12165. if (this.actionManager) {
  12166. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12167. }
  12168. //Simplification Queue
  12169. if (!this.simplificationQueue.running) {
  12170. this.simplificationQueue.executeNext();
  12171. }
  12172. // Before render
  12173. if (this.beforeRender) {
  12174. this.beforeRender();
  12175. }
  12176. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12177. this._onBeforeRenderCallbacks[callbackIndex]();
  12178. }
  12179. // Animations
  12180. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12181. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12182. this._animate();
  12183. // Physics
  12184. if (this._physicsEngine) {
  12185. BABYLON.Tools.StartPerformanceCounter("Physics");
  12186. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12187. BABYLON.Tools.EndPerformanceCounter("Physics");
  12188. }
  12189. // Customs render targets
  12190. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12191. var engine = this.getEngine();
  12192. var currentActiveCamera = this.activeCamera;
  12193. if (this.renderTargetsEnabled) {
  12194. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12195. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12196. var renderTarget = this.customRenderTargets[customIndex];
  12197. if (renderTarget._shouldRender()) {
  12198. this._renderId++;
  12199. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12200. if (!this.activeCamera)
  12201. throw new Error("Active camera not set");
  12202. // Viewport
  12203. engine.setViewport(this.activeCamera.viewport);
  12204. // Camera
  12205. this.updateTransformMatrix();
  12206. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12207. }
  12208. }
  12209. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12210. this._renderId++;
  12211. }
  12212. if (this.customRenderTargets.length > 0) {
  12213. engine.restoreDefaultFramebuffer();
  12214. }
  12215. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12216. this.activeCamera = currentActiveCamera;
  12217. // Procedural textures
  12218. if (this.proceduralTexturesEnabled) {
  12219. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12220. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12221. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12222. if (proceduralTexture._shouldRender()) {
  12223. proceduralTexture.render();
  12224. }
  12225. }
  12226. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12227. }
  12228. // Clear
  12229. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12230. // Shadows
  12231. if (this.shadowsEnabled) {
  12232. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12233. var light = this.lights[lightIndex];
  12234. var shadowGenerator = light.getShadowGenerator();
  12235. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12236. this._renderTargets.push(shadowGenerator.getShadowMap());
  12237. }
  12238. }
  12239. }
  12240. // Depth renderer
  12241. if (this._depthRenderer) {
  12242. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12243. }
  12244. // RenderPipeline
  12245. this.postProcessRenderPipelineManager.update();
  12246. // Multi-cameras?
  12247. if (this.activeCameras.length > 0) {
  12248. var currentRenderId = this._renderId;
  12249. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12250. this._renderId = currentRenderId;
  12251. this._processSubCameras(this.activeCameras[cameraIndex]);
  12252. }
  12253. }
  12254. else {
  12255. if (!this.activeCamera) {
  12256. throw new Error("No camera defined");
  12257. }
  12258. this._processSubCameras(this.activeCamera);
  12259. }
  12260. // Intersection checks
  12261. this._checkIntersections();
  12262. // Update the audio listener attached to the camera
  12263. this._updateAudioParameters();
  12264. // After render
  12265. if (this.afterRender) {
  12266. this.afterRender();
  12267. }
  12268. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12269. this._onAfterRenderCallbacks[callbackIndex]();
  12270. }
  12271. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12272. this._toBeDisposed.data[index].dispose();
  12273. this._toBeDisposed[index] = null;
  12274. }
  12275. this._toBeDisposed.reset();
  12276. if (this.dumpNextRenderTargets) {
  12277. this.dumpNextRenderTargets = false;
  12278. }
  12279. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12280. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12281. };
  12282. Scene.prototype._updateAudioParameters = function () {
  12283. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12284. return;
  12285. }
  12286. var listeningCamera;
  12287. var audioEngine = BABYLON.Engine.audioEngine;
  12288. if (this.activeCameras.length > 0) {
  12289. listeningCamera = this.activeCameras[0];
  12290. }
  12291. else {
  12292. listeningCamera = this.activeCamera;
  12293. }
  12294. if (listeningCamera && audioEngine.canUseWebAudio) {
  12295. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12296. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12297. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12298. cameraDirection.normalize();
  12299. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12300. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12301. var sound = this.mainSoundTrack.soundCollection[i];
  12302. if (sound.useCustomAttenuation) {
  12303. sound.updateDistanceFromListener();
  12304. }
  12305. }
  12306. for (i = 0; i < this.soundTracks.length; i++) {
  12307. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12308. sound = this.soundTracks[i].soundCollection[j];
  12309. if (sound.useCustomAttenuation) {
  12310. sound.updateDistanceFromListener();
  12311. }
  12312. }
  12313. }
  12314. }
  12315. };
  12316. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12317. // Audio
  12318. get: function () {
  12319. return this._audioEnabled;
  12320. },
  12321. set: function (value) {
  12322. this._audioEnabled = value;
  12323. if (this._audioEnabled) {
  12324. this._enableAudio();
  12325. }
  12326. else {
  12327. this._disableAudio();
  12328. }
  12329. },
  12330. enumerable: true,
  12331. configurable: true
  12332. });
  12333. Scene.prototype._disableAudio = function () {
  12334. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12335. this.mainSoundTrack.soundCollection[i].pause();
  12336. }
  12337. for (i = 0; i < this.soundTracks.length; i++) {
  12338. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12339. this.soundTracks[i].soundCollection[j].pause();
  12340. }
  12341. }
  12342. };
  12343. Scene.prototype._enableAudio = function () {
  12344. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12345. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12346. this.mainSoundTrack.soundCollection[i].play();
  12347. }
  12348. }
  12349. for (i = 0; i < this.soundTracks.length; i++) {
  12350. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12351. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12352. this.soundTracks[i].soundCollection[j].play();
  12353. }
  12354. }
  12355. }
  12356. };
  12357. Object.defineProperty(Scene.prototype, "headphone", {
  12358. get: function () {
  12359. return this._headphone;
  12360. },
  12361. set: function (value) {
  12362. this._headphone = value;
  12363. if (this._headphone) {
  12364. this._switchAudioModeForHeadphones();
  12365. }
  12366. else {
  12367. this._switchAudioModeForNormalSpeakers();
  12368. }
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Scene.prototype._switchAudioModeForHeadphones = function () {
  12374. this.mainSoundTrack.switchPanningModelToHRTF();
  12375. for (var i = 0; i < this.soundTracks.length; i++) {
  12376. this.soundTracks[i].switchPanningModelToHRTF();
  12377. }
  12378. };
  12379. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12380. this.mainSoundTrack.switchPanningModelToEqualPower();
  12381. for (var i = 0; i < this.soundTracks.length; i++) {
  12382. this.soundTracks[i].switchPanningModelToEqualPower();
  12383. }
  12384. };
  12385. Scene.prototype.enableDepthRenderer = function () {
  12386. if (this._depthRenderer) {
  12387. return this._depthRenderer;
  12388. }
  12389. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12390. return this._depthRenderer;
  12391. };
  12392. Scene.prototype.disableDepthRenderer = function () {
  12393. if (!this._depthRenderer) {
  12394. return;
  12395. }
  12396. this._depthRenderer.dispose();
  12397. this._depthRenderer = null;
  12398. };
  12399. Scene.prototype.dispose = function () {
  12400. this.beforeRender = null;
  12401. this.afterRender = null;
  12402. this.skeletons = [];
  12403. this._boundingBoxRenderer.dispose();
  12404. if (this._depthRenderer) {
  12405. this._depthRenderer.dispose();
  12406. }
  12407. // Debug layer
  12408. this.debugLayer.hide();
  12409. // Events
  12410. if (this.onDispose) {
  12411. this.onDispose();
  12412. }
  12413. this._onBeforeRenderCallbacks = [];
  12414. this._onAfterRenderCallbacks = [];
  12415. this.detachControl();
  12416. // Release sounds & sounds tracks
  12417. this.disposeSounds();
  12418. // Detach cameras
  12419. var canvas = this._engine.getRenderingCanvas();
  12420. var index;
  12421. for (index = 0; index < this.cameras.length; index++) {
  12422. this.cameras[index].detachControl(canvas);
  12423. }
  12424. while (this.lights.length) {
  12425. this.lights[0].dispose();
  12426. }
  12427. while (this.meshes.length) {
  12428. this.meshes[0].dispose(true);
  12429. }
  12430. while (this.cameras.length) {
  12431. this.cameras[0].dispose();
  12432. }
  12433. while (this.materials.length) {
  12434. this.materials[0].dispose();
  12435. }
  12436. while (this.particleSystems.length) {
  12437. this.particleSystems[0].dispose();
  12438. }
  12439. while (this.spriteManagers.length) {
  12440. this.spriteManagers[0].dispose();
  12441. }
  12442. while (this.layers.length) {
  12443. this.layers[0].dispose();
  12444. }
  12445. while (this.textures.length) {
  12446. this.textures[0].dispose();
  12447. }
  12448. // Post-processes
  12449. this.postProcessManager.dispose();
  12450. // Physics
  12451. if (this._physicsEngine) {
  12452. this.disablePhysicsEngine();
  12453. }
  12454. // Remove from engine
  12455. index = this._engine.scenes.indexOf(this);
  12456. if (index > -1) {
  12457. this._engine.scenes.splice(index, 1);
  12458. }
  12459. this._engine.wipeCaches();
  12460. };
  12461. // Release sounds & sounds tracks
  12462. Scene.prototype.disposeSounds = function () {
  12463. this.mainSoundTrack.dispose();
  12464. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12465. this.soundTracks[scIndex].dispose();
  12466. }
  12467. };
  12468. // Octrees
  12469. Scene.prototype.getWorldExtends = function () {
  12470. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12471. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12472. for (var index = 0; index < this.meshes.length; index++) {
  12473. var mesh = this.meshes[index];
  12474. mesh.computeWorldMatrix(true);
  12475. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12476. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12477. BABYLON.Tools.CheckExtends(minBox, min, max);
  12478. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12479. }
  12480. return {
  12481. min: min,
  12482. max: max
  12483. };
  12484. };
  12485. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12486. if (maxCapacity === void 0) { maxCapacity = 64; }
  12487. if (maxDepth === void 0) { maxDepth = 2; }
  12488. if (!this._selectionOctree) {
  12489. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12490. }
  12491. var worldExtends = this.getWorldExtends();
  12492. // Update octree
  12493. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12494. return this._selectionOctree;
  12495. };
  12496. // Picking
  12497. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12498. var engine = this._engine;
  12499. if (!camera) {
  12500. if (!this.activeCamera)
  12501. throw new Error("Active camera not set");
  12502. camera = this.activeCamera;
  12503. }
  12504. var cameraViewport = camera.viewport;
  12505. var viewport = cameraViewport.toGlobal(engine);
  12506. // Moving coordinates to local viewport world
  12507. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12508. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12509. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12510. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12511. };
  12512. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12513. var pickingInfo = null;
  12514. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12515. var mesh = this.meshes[meshIndex];
  12516. if (predicate) {
  12517. if (!predicate(mesh)) {
  12518. continue;
  12519. }
  12520. }
  12521. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12522. continue;
  12523. }
  12524. var world = mesh.getWorldMatrix();
  12525. var ray = rayFunction(world);
  12526. var result = mesh.intersects(ray, fastCheck);
  12527. if (!result || !result.hit)
  12528. continue;
  12529. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12530. continue;
  12531. pickingInfo = result;
  12532. if (fastCheck) {
  12533. break;
  12534. }
  12535. }
  12536. return pickingInfo || new BABYLON.PickingInfo();
  12537. };
  12538. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12539. var _this = this;
  12540. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12541. /// <param name="x">X position on screen</param>
  12542. /// <param name="y">Y position on screen</param>
  12543. /// <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>
  12544. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12545. /// <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>
  12546. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12547. };
  12548. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12549. var _this = this;
  12550. return this._internalPick(function (world) {
  12551. if (!_this._pickWithRayInverseMatrix) {
  12552. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12553. }
  12554. world.invertToRef(_this._pickWithRayInverseMatrix);
  12555. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12556. }, predicate, fastCheck);
  12557. };
  12558. Scene.prototype.setPointerOverMesh = function (mesh) {
  12559. if (this._pointerOverMesh === mesh) {
  12560. return;
  12561. }
  12562. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12563. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12564. }
  12565. this._pointerOverMesh = mesh;
  12566. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12567. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12568. }
  12569. };
  12570. Scene.prototype.getPointerOverMesh = function () {
  12571. return this._pointerOverMesh;
  12572. };
  12573. // Physics
  12574. Scene.prototype.getPhysicsEngine = function () {
  12575. return this._physicsEngine;
  12576. };
  12577. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12578. if (this._physicsEngine) {
  12579. return true;
  12580. }
  12581. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12582. if (!this._physicsEngine.isSupported()) {
  12583. this._physicsEngine = null;
  12584. return false;
  12585. }
  12586. this._physicsEngine._initialize(gravity);
  12587. return true;
  12588. };
  12589. Scene.prototype.disablePhysicsEngine = function () {
  12590. if (!this._physicsEngine) {
  12591. return;
  12592. }
  12593. this._physicsEngine.dispose();
  12594. this._physicsEngine = undefined;
  12595. };
  12596. Scene.prototype.isPhysicsEnabled = function () {
  12597. return this._physicsEngine !== undefined;
  12598. };
  12599. Scene.prototype.setGravity = function (gravity) {
  12600. if (!this._physicsEngine) {
  12601. return;
  12602. }
  12603. this._physicsEngine._setGravity(gravity);
  12604. };
  12605. Scene.prototype.createCompoundImpostor = function (parts, options) {
  12606. if (parts.parts) {
  12607. options = parts;
  12608. parts = parts.parts;
  12609. }
  12610. if (!this._physicsEngine) {
  12611. return null;
  12612. }
  12613. for (var index = 0; index < parts.length; index++) {
  12614. var mesh = parts[index].mesh;
  12615. mesh._physicImpostor = parts[index].impostor;
  12616. mesh._physicsMass = options.mass / parts.length;
  12617. mesh._physicsFriction = options.friction;
  12618. mesh._physicRestitution = options.restitution;
  12619. }
  12620. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  12621. };
  12622. Scene.prototype.deleteCompoundImpostor = function (compound) {
  12623. for (var index = 0; index < compound.parts.length; index++) {
  12624. var mesh = compound.parts[index].mesh;
  12625. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  12626. this._physicsEngine._unregisterMesh(mesh);
  12627. }
  12628. };
  12629. // Misc.
  12630. Scene.prototype.createDefaultCameraOrLight = function () {
  12631. // Light
  12632. if (this.lights.length === 0) {
  12633. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  12634. }
  12635. // Camera
  12636. if (!this.activeCamera) {
  12637. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  12638. // Compute position
  12639. var worldExtends = this.getWorldExtends();
  12640. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  12641. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  12642. camera.setTarget(worldCenter);
  12643. this.activeCamera = camera;
  12644. }
  12645. };
  12646. // Tags
  12647. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  12648. if (tagsQuery === undefined) {
  12649. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  12650. return list;
  12651. }
  12652. var listByTags = [];
  12653. forEach = forEach || (function (item) {
  12654. return;
  12655. });
  12656. for (var i in list) {
  12657. var item = list[i];
  12658. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  12659. listByTags.push(item);
  12660. forEach(item);
  12661. }
  12662. }
  12663. return listByTags;
  12664. };
  12665. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  12666. return this._getByTags(this.meshes, tagsQuery, forEach);
  12667. };
  12668. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  12669. return this._getByTags(this.cameras, tagsQuery, forEach);
  12670. };
  12671. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  12672. return this._getByTags(this.lights, tagsQuery, forEach);
  12673. };
  12674. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  12675. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  12676. };
  12677. // Statics
  12678. Scene._FOGMODE_NONE = 0;
  12679. Scene._FOGMODE_EXP = 1;
  12680. Scene._FOGMODE_EXP2 = 2;
  12681. Scene._FOGMODE_LINEAR = 3;
  12682. Scene.MinDeltaTime = 1.0;
  12683. Scene.MaxDeltaTime = 1000.0;
  12684. return Scene;
  12685. })();
  12686. BABYLON.Scene = Scene;
  12687. })(BABYLON || (BABYLON = {}));
  12688. //# sourceMappingURL=babylon.scene.js.map
  12689. var BABYLON;
  12690. (function (BABYLON) {
  12691. var VertexBuffer = (function () {
  12692. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  12693. if (engine instanceof BABYLON.Mesh) {
  12694. this._engine = engine.getScene().getEngine();
  12695. }
  12696. else {
  12697. this._engine = engine;
  12698. }
  12699. this._updatable = updatable;
  12700. this._data = data;
  12701. if (!postponeInternalCreation) {
  12702. this.create();
  12703. }
  12704. this._kind = kind;
  12705. if (stride) {
  12706. this._strideSize = stride;
  12707. return;
  12708. }
  12709. switch (kind) {
  12710. case VertexBuffer.PositionKind:
  12711. this._strideSize = 3;
  12712. break;
  12713. case VertexBuffer.NormalKind:
  12714. this._strideSize = 3;
  12715. break;
  12716. case VertexBuffer.UVKind:
  12717. this._strideSize = 2;
  12718. break;
  12719. case VertexBuffer.UV2Kind:
  12720. this._strideSize = 2;
  12721. break;
  12722. case VertexBuffer.ColorKind:
  12723. this._strideSize = 4;
  12724. break;
  12725. case VertexBuffer.MatricesIndicesKind:
  12726. this._strideSize = 4;
  12727. break;
  12728. case VertexBuffer.MatricesWeightsKind:
  12729. this._strideSize = 4;
  12730. break;
  12731. }
  12732. }
  12733. // Properties
  12734. VertexBuffer.prototype.isUpdatable = function () {
  12735. return this._updatable;
  12736. };
  12737. VertexBuffer.prototype.getData = function () {
  12738. return this._data;
  12739. };
  12740. VertexBuffer.prototype.getBuffer = function () {
  12741. return this._buffer;
  12742. };
  12743. VertexBuffer.prototype.getStrideSize = function () {
  12744. return this._strideSize;
  12745. };
  12746. // Methods
  12747. VertexBuffer.prototype.create = function (data) {
  12748. if (!data && this._buffer) {
  12749. return; // nothing to do
  12750. }
  12751. data = data || this._data;
  12752. if (!this._buffer) {
  12753. if (this._updatable) {
  12754. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  12755. }
  12756. else {
  12757. this._buffer = this._engine.createVertexBuffer(data);
  12758. }
  12759. }
  12760. if (this._updatable) {
  12761. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  12762. this._data = data;
  12763. }
  12764. };
  12765. VertexBuffer.prototype.update = function (data) {
  12766. this.create(data);
  12767. };
  12768. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  12769. if (!this._buffer) {
  12770. return;
  12771. }
  12772. if (this._updatable) {
  12773. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  12774. this._data = null;
  12775. }
  12776. };
  12777. VertexBuffer.prototype.dispose = function () {
  12778. if (!this._buffer) {
  12779. return;
  12780. }
  12781. if (this._engine._releaseBuffer(this._buffer)) {
  12782. this._buffer = null;
  12783. }
  12784. };
  12785. Object.defineProperty(VertexBuffer, "PositionKind", {
  12786. get: function () {
  12787. return VertexBuffer._PositionKind;
  12788. },
  12789. enumerable: true,
  12790. configurable: true
  12791. });
  12792. Object.defineProperty(VertexBuffer, "NormalKind", {
  12793. get: function () {
  12794. return VertexBuffer._NormalKind;
  12795. },
  12796. enumerable: true,
  12797. configurable: true
  12798. });
  12799. Object.defineProperty(VertexBuffer, "UVKind", {
  12800. get: function () {
  12801. return VertexBuffer._UVKind;
  12802. },
  12803. enumerable: true,
  12804. configurable: true
  12805. });
  12806. Object.defineProperty(VertexBuffer, "UV2Kind", {
  12807. get: function () {
  12808. return VertexBuffer._UV2Kind;
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. Object.defineProperty(VertexBuffer, "ColorKind", {
  12814. get: function () {
  12815. return VertexBuffer._ColorKind;
  12816. },
  12817. enumerable: true,
  12818. configurable: true
  12819. });
  12820. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  12821. get: function () {
  12822. return VertexBuffer._MatricesIndicesKind;
  12823. },
  12824. enumerable: true,
  12825. configurable: true
  12826. });
  12827. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  12828. get: function () {
  12829. return VertexBuffer._MatricesWeightsKind;
  12830. },
  12831. enumerable: true,
  12832. configurable: true
  12833. });
  12834. // Enums
  12835. VertexBuffer._PositionKind = "position";
  12836. VertexBuffer._NormalKind = "normal";
  12837. VertexBuffer._UVKind = "uv";
  12838. VertexBuffer._UV2Kind = "uv2";
  12839. VertexBuffer._ColorKind = "color";
  12840. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  12841. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  12842. return VertexBuffer;
  12843. })();
  12844. BABYLON.VertexBuffer = VertexBuffer;
  12845. })(BABYLON || (BABYLON = {}));
  12846. //# sourceMappingURL=babylon.vertexBuffer.js.map
  12847. var __extends = this.__extends || function (d, b) {
  12848. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12849. function __() { this.constructor = d; }
  12850. __.prototype = b.prototype;
  12851. d.prototype = new __();
  12852. };
  12853. var BABYLON;
  12854. (function (BABYLON) {
  12855. /**
  12856. * Creates an instance based on a source mesh.
  12857. */
  12858. var InstancedMesh = (function (_super) {
  12859. __extends(InstancedMesh, _super);
  12860. function InstancedMesh(name, source) {
  12861. _super.call(this, name, source.getScene());
  12862. source.instances.push(this);
  12863. this._sourceMesh = source;
  12864. this.position.copyFrom(source.position);
  12865. this.rotation.copyFrom(source.rotation);
  12866. this.scaling.copyFrom(source.scaling);
  12867. if (source.rotationQuaternion) {
  12868. this.rotationQuaternion = source.rotationQuaternion.clone();
  12869. }
  12870. this.infiniteDistance = source.infiniteDistance;
  12871. this.setPivotMatrix(source.getPivotMatrix());
  12872. this.refreshBoundingInfo();
  12873. this._syncSubMeshes();
  12874. }
  12875. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12876. // Methods
  12877. get: function () {
  12878. return this._sourceMesh.receiveShadows;
  12879. },
  12880. enumerable: true,
  12881. configurable: true
  12882. });
  12883. Object.defineProperty(InstancedMesh.prototype, "material", {
  12884. get: function () {
  12885. return this._sourceMesh.material;
  12886. },
  12887. enumerable: true,
  12888. configurable: true
  12889. });
  12890. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12891. get: function () {
  12892. return this._sourceMesh.visibility;
  12893. },
  12894. enumerable: true,
  12895. configurable: true
  12896. });
  12897. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12898. get: function () {
  12899. return this._sourceMesh.skeleton;
  12900. },
  12901. enumerable: true,
  12902. configurable: true
  12903. });
  12904. InstancedMesh.prototype.getTotalVertices = function () {
  12905. return this._sourceMesh.getTotalVertices();
  12906. };
  12907. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12908. get: function () {
  12909. return this._sourceMesh;
  12910. },
  12911. enumerable: true,
  12912. configurable: true
  12913. });
  12914. InstancedMesh.prototype.getVerticesData = function (kind) {
  12915. return this._sourceMesh.getVerticesData(kind);
  12916. };
  12917. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12918. return this._sourceMesh.isVerticesDataPresent(kind);
  12919. };
  12920. InstancedMesh.prototype.getIndices = function () {
  12921. return this._sourceMesh.getIndices();
  12922. };
  12923. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12924. get: function () {
  12925. return this._sourceMesh._positions;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12931. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12932. if (data) {
  12933. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12934. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12935. }
  12936. this._updateBoundingInfo();
  12937. };
  12938. InstancedMesh.prototype._preActivate = function () {
  12939. if (this._currentLOD) {
  12940. this._currentLOD._preActivate();
  12941. }
  12942. };
  12943. InstancedMesh.prototype._activate = function (renderId) {
  12944. if (this._currentLOD) {
  12945. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12946. }
  12947. };
  12948. InstancedMesh.prototype.getLOD = function (camera) {
  12949. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12950. if (this._currentLOD === this.sourceMesh) {
  12951. return this;
  12952. }
  12953. return this._currentLOD;
  12954. };
  12955. InstancedMesh.prototype._syncSubMeshes = function () {
  12956. this.releaseSubMeshes();
  12957. if (this._sourceMesh.subMeshes) {
  12958. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12959. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12960. }
  12961. }
  12962. };
  12963. InstancedMesh.prototype._generatePointsArray = function () {
  12964. return this._sourceMesh._generatePointsArray();
  12965. };
  12966. // Clone
  12967. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12968. var result = this._sourceMesh.createInstance(name);
  12969. // Deep copy
  12970. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12971. // Bounding info
  12972. this.refreshBoundingInfo();
  12973. // Parent
  12974. if (newParent) {
  12975. result.parent = newParent;
  12976. }
  12977. if (!doNotCloneChildren) {
  12978. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12979. var mesh = this.getScene().meshes[index];
  12980. if (mesh.parent === this) {
  12981. mesh.clone(mesh.name, result);
  12982. }
  12983. }
  12984. }
  12985. result.computeWorldMatrix(true);
  12986. return result;
  12987. };
  12988. // Dispoe
  12989. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12990. // Remove from mesh
  12991. var index = this._sourceMesh.instances.indexOf(this);
  12992. this._sourceMesh.instances.splice(index, 1);
  12993. _super.prototype.dispose.call(this, doNotRecurse);
  12994. };
  12995. return InstancedMesh;
  12996. })(BABYLON.AbstractMesh);
  12997. BABYLON.InstancedMesh = InstancedMesh;
  12998. })(BABYLON || (BABYLON = {}));
  12999. //# sourceMappingURL=babylon.instancedMesh.js.map
  13000. var __extends = this.__extends || function (d, b) {
  13001. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13002. function __() { this.constructor = d; }
  13003. __.prototype = b.prototype;
  13004. d.prototype = new __();
  13005. };
  13006. var BABYLON;
  13007. (function (BABYLON) {
  13008. var _InstancesBatch = (function () {
  13009. function _InstancesBatch() {
  13010. this.mustReturn = false;
  13011. this.visibleInstances = new Array();
  13012. this.renderSelf = new Array();
  13013. }
  13014. return _InstancesBatch;
  13015. })();
  13016. BABYLON._InstancesBatch = _InstancesBatch;
  13017. var Mesh = (function (_super) {
  13018. __extends(Mesh, _super);
  13019. /**
  13020. * @constructor
  13021. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13022. * @param {Scene} scene - The scene to add this mesh to.
  13023. * @param {Node} parent - The parent of this mesh, if it has one
  13024. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13025. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13026. * When false, achieved by calling a clone(), also passing False.
  13027. * This will make creation of children, recursive.
  13028. */
  13029. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13030. if (parent === void 0) { parent = null; }
  13031. _super.call(this, name, scene);
  13032. // Members
  13033. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13034. this.instances = new Array();
  13035. this._LODLevels = new Array();
  13036. this._onBeforeRenderCallbacks = new Array();
  13037. this._onAfterRenderCallbacks = new Array();
  13038. this._visibleInstances = {};
  13039. this._renderIdForInstances = new Array();
  13040. this._batchCache = new _InstancesBatch();
  13041. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13042. this._sideOrientation = Mesh._DEFAULTSIDE;
  13043. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13044. if (source) {
  13045. // Geometry
  13046. if (source._geometry) {
  13047. source._geometry.applyToMesh(this);
  13048. }
  13049. // Deep copy
  13050. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13051. // Material
  13052. this.material = source.material;
  13053. if (!doNotCloneChildren) {
  13054. for (var index = 0; index < scene.meshes.length; index++) {
  13055. var mesh = scene.meshes[index];
  13056. if (mesh.parent === source) {
  13057. // doNotCloneChildren is always going to be False
  13058. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13059. }
  13060. }
  13061. }
  13062. for (index = 0; index < scene.particleSystems.length; index++) {
  13063. var system = scene.particleSystems[index];
  13064. if (system.emitter === source) {
  13065. system.clone(system.name, this);
  13066. }
  13067. }
  13068. this.computeWorldMatrix(true);
  13069. }
  13070. // Parent
  13071. if (parent !== null) {
  13072. this.parent = parent;
  13073. }
  13074. }
  13075. Object.defineProperty(Mesh, "FRONTSIDE", {
  13076. get: function () {
  13077. return Mesh._FRONTSIDE;
  13078. },
  13079. enumerable: true,
  13080. configurable: true
  13081. });
  13082. Object.defineProperty(Mesh, "BACKSIDE", {
  13083. get: function () {
  13084. return Mesh._BACKSIDE;
  13085. },
  13086. enumerable: true,
  13087. configurable: true
  13088. });
  13089. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13090. get: function () {
  13091. return Mesh._DOUBLESIDE;
  13092. },
  13093. enumerable: true,
  13094. configurable: true
  13095. });
  13096. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13097. get: function () {
  13098. return Mesh._DEFAULTSIDE;
  13099. },
  13100. enumerable: true,
  13101. configurable: true
  13102. });
  13103. Object.defineProperty(Mesh, "NO_CAP", {
  13104. get: function () {
  13105. return Mesh._NO_CAP;
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Object.defineProperty(Mesh, "CAP_START", {
  13111. get: function () {
  13112. return Mesh._CAP_START;
  13113. },
  13114. enumerable: true,
  13115. configurable: true
  13116. });
  13117. Object.defineProperty(Mesh, "CAP_END", {
  13118. get: function () {
  13119. return Mesh._CAP_END;
  13120. },
  13121. enumerable: true,
  13122. configurable: true
  13123. });
  13124. Object.defineProperty(Mesh, "CAP_ALL", {
  13125. get: function () {
  13126. return Mesh._CAP_ALL;
  13127. },
  13128. enumerable: true,
  13129. configurable: true
  13130. });
  13131. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13132. // Methods
  13133. get: function () {
  13134. return this._LODLevels.length > 0;
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. Mesh.prototype._sortLODLevels = function () {
  13140. this._LODLevels.sort(function (a, b) {
  13141. if (a.distance < b.distance) {
  13142. return 1;
  13143. }
  13144. if (a.distance > b.distance) {
  13145. return -1;
  13146. }
  13147. return 0;
  13148. });
  13149. };
  13150. /**
  13151. * Add a mesh as LOD level triggered at the given distance.
  13152. * @param {number} distance - the distance from the center of the object to show this level
  13153. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13154. * @return {BABYLON.Mesh} this mesh (for chaining)
  13155. */
  13156. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13157. if (mesh && mesh._masterMesh) {
  13158. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13159. return this;
  13160. }
  13161. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13162. this._LODLevels.push(level);
  13163. if (mesh) {
  13164. mesh._masterMesh = this;
  13165. }
  13166. this._sortLODLevels();
  13167. return this;
  13168. };
  13169. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13170. for (var index = 0; index < this._LODLevels.length; index++) {
  13171. var level = this._LODLevels[index];
  13172. if (level.distance === distance) {
  13173. return level.mesh;
  13174. }
  13175. }
  13176. return null;
  13177. };
  13178. /**
  13179. * Remove a mesh from the LOD array
  13180. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13181. * @return {BABYLON.Mesh} this mesh (for chaining)
  13182. */
  13183. Mesh.prototype.removeLODLevel = function (mesh) {
  13184. for (var index = 0; index < this._LODLevels.length; index++) {
  13185. if (this._LODLevels[index].mesh === mesh) {
  13186. this._LODLevels.splice(index, 1);
  13187. if (mesh) {
  13188. mesh._masterMesh = null;
  13189. }
  13190. }
  13191. }
  13192. this._sortLODLevels();
  13193. return this;
  13194. };
  13195. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13196. if (!this._LODLevels || this._LODLevels.length === 0) {
  13197. return this;
  13198. }
  13199. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13200. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13201. if (this.onLODLevelSelection) {
  13202. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13203. }
  13204. return this;
  13205. }
  13206. for (var index = 0; index < this._LODLevels.length; index++) {
  13207. var level = this._LODLevels[index];
  13208. if (level.distance < distanceToCamera) {
  13209. if (level.mesh) {
  13210. level.mesh._preActivate();
  13211. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13212. }
  13213. if (this.onLODLevelSelection) {
  13214. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13215. }
  13216. return level.mesh;
  13217. }
  13218. }
  13219. if (this.onLODLevelSelection) {
  13220. this.onLODLevelSelection(distanceToCamera, this, this);
  13221. }
  13222. return this;
  13223. };
  13224. Object.defineProperty(Mesh.prototype, "geometry", {
  13225. get: function () {
  13226. return this._geometry;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Mesh.prototype.getTotalVertices = function () {
  13232. if (!this._geometry) {
  13233. return 0;
  13234. }
  13235. return this._geometry.getTotalVertices();
  13236. };
  13237. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13238. if (!this._geometry) {
  13239. return null;
  13240. }
  13241. return this._geometry.getVerticesData(kind, copyWhenShared);
  13242. };
  13243. Mesh.prototype.getVertexBuffer = function (kind) {
  13244. if (!this._geometry) {
  13245. return undefined;
  13246. }
  13247. return this._geometry.getVertexBuffer(kind);
  13248. };
  13249. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13250. if (!this._geometry) {
  13251. if (this._delayInfo) {
  13252. return this._delayInfo.indexOf(kind) !== -1;
  13253. }
  13254. return false;
  13255. }
  13256. return this._geometry.isVerticesDataPresent(kind);
  13257. };
  13258. Mesh.prototype.getVerticesDataKinds = function () {
  13259. if (!this._geometry) {
  13260. var result = [];
  13261. if (this._delayInfo) {
  13262. for (var kind in this._delayInfo) {
  13263. result.push(kind);
  13264. }
  13265. }
  13266. return result;
  13267. }
  13268. return this._geometry.getVerticesDataKinds();
  13269. };
  13270. Mesh.prototype.getTotalIndices = function () {
  13271. if (!this._geometry) {
  13272. return 0;
  13273. }
  13274. return this._geometry.getTotalIndices();
  13275. };
  13276. Mesh.prototype.getIndices = function (copyWhenShared) {
  13277. if (!this._geometry) {
  13278. return [];
  13279. }
  13280. return this._geometry.getIndices(copyWhenShared);
  13281. };
  13282. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13283. get: function () {
  13284. return this._masterMesh !== null && this._masterMesh !== undefined;
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. Mesh.prototype.isReady = function () {
  13290. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13291. return false;
  13292. }
  13293. return _super.prototype.isReady.call(this);
  13294. };
  13295. Mesh.prototype.isDisposed = function () {
  13296. return this._isDisposed;
  13297. };
  13298. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13299. get: function () {
  13300. return this._sideOrientation;
  13301. },
  13302. set: function (sideO) {
  13303. this._sideOrientation = sideO;
  13304. },
  13305. enumerable: true,
  13306. configurable: true
  13307. });
  13308. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13309. get: function () {
  13310. return this._areNormalsFrozen;
  13311. },
  13312. enumerable: true,
  13313. configurable: true
  13314. });
  13315. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13316. Mesh.prototype.freezeNormals = function () {
  13317. this._areNormalsFrozen = true;
  13318. };
  13319. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13320. Mesh.prototype.unfreezeNormals = function () {
  13321. this._areNormalsFrozen = false;
  13322. };
  13323. // Methods
  13324. Mesh.prototype._preActivate = function () {
  13325. var sceneRenderId = this.getScene().getRenderId();
  13326. if (this._preActivateId === sceneRenderId) {
  13327. return;
  13328. }
  13329. this._preActivateId = sceneRenderId;
  13330. this._visibleInstances = null;
  13331. };
  13332. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13333. if (!this._visibleInstances) {
  13334. this._visibleInstances = {};
  13335. this._visibleInstances.defaultRenderId = renderId;
  13336. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13337. }
  13338. if (!this._visibleInstances[renderId]) {
  13339. this._visibleInstances[renderId] = new Array();
  13340. }
  13341. this._visibleInstances[renderId].push(instance);
  13342. };
  13343. Mesh.prototype.refreshBoundingInfo = function () {
  13344. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13345. if (data) {
  13346. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13347. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13348. }
  13349. if (this.subMeshes) {
  13350. for (var index = 0; index < this.subMeshes.length; index++) {
  13351. this.subMeshes[index].refreshBoundingInfo();
  13352. }
  13353. }
  13354. this._updateBoundingInfo();
  13355. };
  13356. Mesh.prototype._createGlobalSubMesh = function () {
  13357. var totalVertices = this.getTotalVertices();
  13358. if (!totalVertices || !this.getIndices()) {
  13359. return null;
  13360. }
  13361. this.releaseSubMeshes();
  13362. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13363. };
  13364. Mesh.prototype.subdivide = function (count) {
  13365. if (count < 1) {
  13366. return;
  13367. }
  13368. var totalIndices = this.getTotalIndices();
  13369. var subdivisionSize = (totalIndices / count) | 0;
  13370. var offset = 0;
  13371. while (subdivisionSize % 3 !== 0) {
  13372. subdivisionSize++;
  13373. }
  13374. this.releaseSubMeshes();
  13375. for (var index = 0; index < count; index++) {
  13376. if (offset >= totalIndices) {
  13377. break;
  13378. }
  13379. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13380. offset += subdivisionSize;
  13381. }
  13382. this.synchronizeInstances();
  13383. };
  13384. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13385. if (kind instanceof Array) {
  13386. var temp = data;
  13387. data = kind;
  13388. kind = temp;
  13389. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13390. }
  13391. if (!this._geometry) {
  13392. var vertexData = new BABYLON.VertexData();
  13393. vertexData.set(data, kind);
  13394. var scene = this.getScene();
  13395. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13396. }
  13397. else {
  13398. this._geometry.setVerticesData(kind, data, updatable, stride);
  13399. }
  13400. };
  13401. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13402. if (!this._geometry) {
  13403. return;
  13404. }
  13405. if (!makeItUnique) {
  13406. this._geometry.updateVerticesData(kind, data, updateExtends);
  13407. }
  13408. else {
  13409. this.makeGeometryUnique();
  13410. this.updateVerticesData(kind, data, updateExtends, false);
  13411. }
  13412. };
  13413. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13414. if (!this._geometry) {
  13415. return;
  13416. }
  13417. if (!makeItUnique) {
  13418. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13419. }
  13420. else {
  13421. this.makeGeometryUnique();
  13422. this.updateVerticesDataDirectly(kind, data, offset, false);
  13423. }
  13424. };
  13425. // Mesh positions update function :
  13426. // updates the mesh positions according to the positionFunction returned values.
  13427. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13428. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13429. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13430. if (computeNormals === void 0) { computeNormals = true; }
  13431. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13432. positionFunction(positions);
  13433. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13434. if (computeNormals) {
  13435. var indices = this.getIndices();
  13436. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13437. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13438. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13439. }
  13440. };
  13441. Mesh.prototype.makeGeometryUnique = function () {
  13442. if (!this._geometry) {
  13443. return;
  13444. }
  13445. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13446. geometry.applyToMesh(this);
  13447. };
  13448. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13449. if (!this._geometry) {
  13450. var vertexData = new BABYLON.VertexData();
  13451. vertexData.indices = indices;
  13452. var scene = this.getScene();
  13453. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13454. }
  13455. else {
  13456. this._geometry.setIndices(indices, totalVertices);
  13457. }
  13458. };
  13459. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13460. var engine = this.getScene().getEngine();
  13461. // Wireframe
  13462. var indexToBind;
  13463. switch (fillMode) {
  13464. case BABYLON.Material.PointFillMode:
  13465. indexToBind = null;
  13466. break;
  13467. case BABYLON.Material.WireFrameFillMode:
  13468. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13469. break;
  13470. default:
  13471. case BABYLON.Material.TriangleFillMode:
  13472. indexToBind = this._geometry.getIndexBuffer();
  13473. break;
  13474. }
  13475. // VBOs
  13476. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13477. };
  13478. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13479. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13480. return;
  13481. }
  13482. var engine = this.getScene().getEngine();
  13483. switch (fillMode) {
  13484. case BABYLON.Material.PointFillMode:
  13485. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13486. break;
  13487. case BABYLON.Material.WireFrameFillMode:
  13488. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13489. break;
  13490. default:
  13491. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13492. }
  13493. };
  13494. Mesh.prototype.registerBeforeRender = function (func) {
  13495. this._onBeforeRenderCallbacks.push(func);
  13496. };
  13497. Mesh.prototype.unregisterBeforeRender = function (func) {
  13498. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13499. if (index > -1) {
  13500. this._onBeforeRenderCallbacks.splice(index, 1);
  13501. }
  13502. };
  13503. Mesh.prototype.registerAfterRender = function (func) {
  13504. this._onAfterRenderCallbacks.push(func);
  13505. };
  13506. Mesh.prototype.unregisterAfterRender = function (func) {
  13507. var index = this._onAfterRenderCallbacks.indexOf(func);
  13508. if (index > -1) {
  13509. this._onAfterRenderCallbacks.splice(index, 1);
  13510. }
  13511. };
  13512. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13513. var scene = this.getScene();
  13514. this._batchCache.mustReturn = false;
  13515. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13516. this._batchCache.visibleInstances[subMeshId] = null;
  13517. if (this._visibleInstances) {
  13518. var currentRenderId = scene.getRenderId();
  13519. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13520. var selfRenderId = this._renderId;
  13521. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13522. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13523. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13524. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13525. }
  13526. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13527. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13528. this._batchCache.mustReturn = true;
  13529. return this._batchCache;
  13530. }
  13531. if (currentRenderId !== selfRenderId) {
  13532. this._batchCache.renderSelf[subMeshId] = false;
  13533. }
  13534. }
  13535. this._renderIdForInstances[subMeshId] = currentRenderId;
  13536. }
  13537. return this._batchCache;
  13538. };
  13539. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13540. var visibleInstances = batch.visibleInstances[subMesh._id];
  13541. var matricesCount = visibleInstances.length + 1;
  13542. var bufferSize = matricesCount * 16 * 4;
  13543. while (this._instancesBufferSize < bufferSize) {
  13544. this._instancesBufferSize *= 2;
  13545. }
  13546. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13547. if (this._worldMatricesInstancesBuffer) {
  13548. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13549. }
  13550. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13551. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13552. }
  13553. var offset = 0;
  13554. var instancesCount = 0;
  13555. var world = this.getWorldMatrix();
  13556. if (batch.renderSelf[subMesh._id]) {
  13557. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13558. offset += 16;
  13559. instancesCount++;
  13560. }
  13561. if (visibleInstances) {
  13562. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13563. var instance = visibleInstances[instanceIndex];
  13564. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13565. offset += 16;
  13566. instancesCount++;
  13567. }
  13568. }
  13569. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13570. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13571. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13572. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13573. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13574. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13575. this._draw(subMesh, fillMode, instancesCount);
  13576. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13577. };
  13578. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13579. var scene = this.getScene();
  13580. var engine = scene.getEngine();
  13581. if (hardwareInstancedRendering) {
  13582. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13583. }
  13584. else {
  13585. if (batch.renderSelf[subMesh._id]) {
  13586. // Draw
  13587. if (onBeforeDraw) {
  13588. onBeforeDraw(false, this.getWorldMatrix());
  13589. }
  13590. this._draw(subMesh, fillMode);
  13591. }
  13592. if (batch.visibleInstances[subMesh._id]) {
  13593. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13594. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13595. // World
  13596. var world = instance.getWorldMatrix();
  13597. if (onBeforeDraw) {
  13598. onBeforeDraw(true, world);
  13599. }
  13600. // Draw
  13601. this._draw(subMesh, fillMode);
  13602. }
  13603. }
  13604. }
  13605. };
  13606. Mesh.prototype.render = function (subMesh) {
  13607. var scene = this.getScene();
  13608. // Managing instances
  13609. var batch = this._getInstancesRenderList(subMesh._id);
  13610. if (batch.mustReturn) {
  13611. return;
  13612. }
  13613. // Checking geometry state
  13614. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13615. return;
  13616. }
  13617. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13618. this._onBeforeRenderCallbacks[callbackIndex](this);
  13619. }
  13620. var engine = scene.getEngine();
  13621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  13622. // Material
  13623. var effectiveMaterial = subMesh.getMaterial();
  13624. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  13625. return;
  13626. }
  13627. // Outline - step 1
  13628. var savedDepthWrite = engine.getDepthWrite();
  13629. if (this.renderOutline) {
  13630. engine.setDepthWrite(false);
  13631. scene.getOutlineRenderer().render(subMesh, batch);
  13632. engine.setDepthWrite(savedDepthWrite);
  13633. }
  13634. effectiveMaterial._preBind();
  13635. var effect = effectiveMaterial.getEffect();
  13636. // Bind
  13637. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  13638. this._bind(subMesh, effect, fillMode);
  13639. var world = this.getWorldMatrix();
  13640. effectiveMaterial.bind(world, this);
  13641. // Draw
  13642. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  13643. if (isInstance) {
  13644. effectiveMaterial.bindOnlyWorldMatrix(world);
  13645. }
  13646. });
  13647. // Unbind
  13648. effectiveMaterial.unbind();
  13649. // Outline - step 2
  13650. if (this.renderOutline && savedDepthWrite) {
  13651. engine.setDepthWrite(true);
  13652. engine.setColorWrite(false);
  13653. scene.getOutlineRenderer().render(subMesh, batch);
  13654. engine.setColorWrite(true);
  13655. }
  13656. // Overlay
  13657. if (this.renderOverlay) {
  13658. var currentMode = engine.getAlphaMode();
  13659. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13660. scene.getOutlineRenderer().render(subMesh, batch, true);
  13661. engine.setAlphaMode(currentMode);
  13662. }
  13663. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13664. this._onAfterRenderCallbacks[callbackIndex](this);
  13665. }
  13666. };
  13667. Mesh.prototype.getEmittedParticleSystems = function () {
  13668. var results = new Array();
  13669. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13670. var particleSystem = this.getScene().particleSystems[index];
  13671. if (particleSystem.emitter === this) {
  13672. results.push(particleSystem);
  13673. }
  13674. }
  13675. return results;
  13676. };
  13677. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  13678. var results = new Array();
  13679. var descendants = this.getDescendants();
  13680. descendants.push(this);
  13681. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13682. var particleSystem = this.getScene().particleSystems[index];
  13683. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  13684. results.push(particleSystem);
  13685. }
  13686. }
  13687. return results;
  13688. };
  13689. Mesh.prototype.getChildren = function () {
  13690. var results = [];
  13691. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13692. var mesh = this.getScene().meshes[index];
  13693. if (mesh.parent === this) {
  13694. results.push(mesh);
  13695. }
  13696. }
  13697. return results;
  13698. };
  13699. Mesh.prototype._checkDelayState = function () {
  13700. var _this = this;
  13701. var that = this;
  13702. var scene = this.getScene();
  13703. if (this._geometry) {
  13704. this._geometry.load(scene);
  13705. }
  13706. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13707. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  13708. scene._addPendingData(that);
  13709. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  13710. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  13711. if (data instanceof ArrayBuffer) {
  13712. _this._delayLoadingFunction(data, _this);
  13713. }
  13714. else {
  13715. _this._delayLoadingFunction(JSON.parse(data), _this);
  13716. }
  13717. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13718. scene._removePendingData(_this);
  13719. }, function () {
  13720. }, scene.database, getBinaryData);
  13721. }
  13722. };
  13723. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  13724. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13725. return false;
  13726. }
  13727. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  13728. return false;
  13729. }
  13730. this._checkDelayState();
  13731. return true;
  13732. };
  13733. Mesh.prototype.setMaterialByID = function (id) {
  13734. var materials = this.getScene().materials;
  13735. for (var index = 0; index < materials.length; index++) {
  13736. if (materials[index].id === id) {
  13737. this.material = materials[index];
  13738. return;
  13739. }
  13740. }
  13741. // Multi
  13742. var multiMaterials = this.getScene().multiMaterials;
  13743. for (index = 0; index < multiMaterials.length; index++) {
  13744. if (multiMaterials[index].id === id) {
  13745. this.material = multiMaterials[index];
  13746. return;
  13747. }
  13748. }
  13749. };
  13750. Mesh.prototype.getAnimatables = function () {
  13751. var results = [];
  13752. if (this.material) {
  13753. results.push(this.material);
  13754. }
  13755. if (this.skeleton) {
  13756. results.push(this.skeleton);
  13757. }
  13758. return results;
  13759. };
  13760. // Geometry
  13761. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  13762. // Position
  13763. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13764. return;
  13765. }
  13766. this._resetPointsArrayCache();
  13767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13768. var temp = [];
  13769. for (var index = 0; index < data.length; index += 3) {
  13770. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13771. }
  13772. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  13773. // Normals
  13774. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13775. return;
  13776. }
  13777. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13778. temp = [];
  13779. for (index = 0; index < data.length; index += 3) {
  13780. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13781. }
  13782. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  13783. };
  13784. // Cache
  13785. Mesh.prototype._resetPointsArrayCache = function () {
  13786. this._positions = null;
  13787. };
  13788. Mesh.prototype._generatePointsArray = function () {
  13789. if (this._positions)
  13790. return true;
  13791. this._positions = [];
  13792. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13793. if (!data) {
  13794. return false;
  13795. }
  13796. for (var index = 0; index < data.length; index += 3) {
  13797. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  13798. }
  13799. return true;
  13800. };
  13801. // Clone
  13802. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13803. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  13804. };
  13805. // Dispose
  13806. Mesh.prototype.dispose = function (doNotRecurse) {
  13807. if (this._geometry) {
  13808. this._geometry.releaseForMesh(this, true);
  13809. }
  13810. // Instances
  13811. if (this._worldMatricesInstancesBuffer) {
  13812. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13813. this._worldMatricesInstancesBuffer = null;
  13814. }
  13815. while (this.instances.length) {
  13816. this.instances[0].dispose();
  13817. }
  13818. _super.prototype.dispose.call(this, doNotRecurse);
  13819. };
  13820. // Geometric tools
  13821. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  13822. var _this = this;
  13823. var scene = this.getScene();
  13824. var onload = function (img) {
  13825. // Getting height map data
  13826. var canvas = document.createElement("canvas");
  13827. var context = canvas.getContext("2d");
  13828. var heightMapWidth = img.width;
  13829. var heightMapHeight = img.height;
  13830. canvas.width = heightMapWidth;
  13831. canvas.height = heightMapHeight;
  13832. context.drawImage(img, 0, 0);
  13833. // Create VertexData from map data
  13834. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  13835. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  13836. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  13837. //execute success callback, if set
  13838. if (onSuccess) {
  13839. onSuccess(_this);
  13840. }
  13841. };
  13842. BABYLON.Tools.LoadImage(url, onload, function () {
  13843. }, scene.database);
  13844. };
  13845. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  13846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13847. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  13848. return;
  13849. }
  13850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13852. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13853. var position = BABYLON.Vector3.Zero();
  13854. var normal = BABYLON.Vector3.Zero();
  13855. var uv = BABYLON.Vector2.Zero();
  13856. for (var index = 0; index < positions.length; index += 3) {
  13857. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  13858. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  13859. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  13860. // Compute height
  13861. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  13862. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  13863. var pos = (u + v * heightMapWidth) * 4;
  13864. var r = buffer[pos] / 255.0;
  13865. var g = buffer[pos + 1] / 255.0;
  13866. var b = buffer[pos + 2] / 255.0;
  13867. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  13868. normal.normalize();
  13869. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  13870. position = position.add(normal);
  13871. position.toArray(positions, index);
  13872. }
  13873. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  13874. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  13875. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  13876. };
  13877. Mesh.prototype.convertToFlatShadedMesh = function () {
  13878. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  13879. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  13880. var kinds = this.getVerticesDataKinds();
  13881. var vbs = [];
  13882. var data = [];
  13883. var newdata = [];
  13884. var updatableNormals = false;
  13885. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13886. var kind = kinds[kindIndex];
  13887. var vertexBuffer = this.getVertexBuffer(kind);
  13888. if (kind === BABYLON.VertexBuffer.NormalKind) {
  13889. updatableNormals = vertexBuffer.isUpdatable();
  13890. kinds.splice(kindIndex, 1);
  13891. kindIndex--;
  13892. continue;
  13893. }
  13894. vbs[kind] = vertexBuffer;
  13895. data[kind] = vbs[kind].getData();
  13896. newdata[kind] = [];
  13897. }
  13898. // Save previous submeshes
  13899. var previousSubmeshes = this.subMeshes.slice(0);
  13900. var indices = this.getIndices();
  13901. var totalIndices = this.getTotalIndices();
  13902. for (var index = 0; index < totalIndices; index++) {
  13903. var vertexIndex = indices[index];
  13904. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13905. kind = kinds[kindIndex];
  13906. var stride = vbs[kind].getStrideSize();
  13907. for (var offset = 0; offset < stride; offset++) {
  13908. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  13909. }
  13910. }
  13911. }
  13912. // Updating faces & normal
  13913. var normals = [];
  13914. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  13915. for (index = 0; index < totalIndices; index += 3) {
  13916. indices[index] = index;
  13917. indices[index + 1] = index + 1;
  13918. indices[index + 2] = index + 2;
  13919. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  13920. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  13921. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  13922. var p1p2 = p1.subtract(p2);
  13923. var p3p2 = p3.subtract(p2);
  13924. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  13925. for (var localIndex = 0; localIndex < 3; localIndex++) {
  13926. normals.push(normal.x);
  13927. normals.push(normal.y);
  13928. normals.push(normal.z);
  13929. }
  13930. }
  13931. this.setIndices(indices);
  13932. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  13933. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13934. kind = kinds[kindIndex];
  13935. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  13936. }
  13937. // Updating submeshes
  13938. this.releaseSubMeshes();
  13939. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  13940. var previousOne = previousSubmeshes[submeshIndex];
  13941. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  13942. }
  13943. this.synchronizeInstances();
  13944. };
  13945. // Instances
  13946. Mesh.prototype.createInstance = function (name) {
  13947. return new BABYLON.InstancedMesh(name, this);
  13948. };
  13949. Mesh.prototype.synchronizeInstances = function () {
  13950. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  13951. var instance = this.instances[instanceIndex];
  13952. instance._syncSubMeshes();
  13953. }
  13954. };
  13955. /**
  13956. * Simplify the mesh according to the given array of settings.
  13957. * Function will return immediately and will simplify async.
  13958. * @param settings a collection of simplification settings.
  13959. * @param parallelProcessing should all levels calculate parallel or one after the other.
  13960. * @param type the type of simplification to run.
  13961. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  13962. */
  13963. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  13964. if (parallelProcessing === void 0) { parallelProcessing = true; }
  13965. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  13966. this.getScene().simplificationQueue.addTask({
  13967. settings: settings,
  13968. parallelProcessing: parallelProcessing,
  13969. mesh: this,
  13970. simplificationType: simplificationType,
  13971. successCallback: successCallback
  13972. });
  13973. };
  13974. /**
  13975. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  13976. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  13977. * This should be used together with the simplification to avoid disappearing triangles.
  13978. * @param successCallback an optional success callback to be called after the optimization finished.
  13979. */
  13980. Mesh.prototype.optimizeIndices = function (successCallback) {
  13981. var _this = this;
  13982. var indices = this.getIndices();
  13983. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13984. var vectorPositions = [];
  13985. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  13986. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  13987. }
  13988. var dupes = [];
  13989. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  13990. var realPos = vectorPositions.length - 1 - iteration;
  13991. var testedPosition = vectorPositions[realPos];
  13992. for (var j = 0; j < realPos; ++j) {
  13993. var againstPosition = vectorPositions[j];
  13994. if (testedPosition.equals(againstPosition)) {
  13995. dupes[realPos] = j;
  13996. break;
  13997. }
  13998. }
  13999. }, function () {
  14000. for (var i = 0; i < indices.length; ++i) {
  14001. indices[i] = dupes[indices[i]] || indices[i];
  14002. }
  14003. //indices are now reordered
  14004. var originalSubMeshes = _this.subMeshes.slice(0);
  14005. _this.setIndices(indices);
  14006. _this.subMeshes = originalSubMeshes;
  14007. if (successCallback) {
  14008. successCallback(_this);
  14009. }
  14010. });
  14011. };
  14012. // Statics
  14013. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  14014. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14015. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14016. if (ribbonInstance) {
  14017. // positionFunction : ribbon case
  14018. // only pathArray and sideOrientation parameters are taken into account for positions update
  14019. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14020. var positionFunction = function (positions) {
  14021. var minlg = pathArray[0].length;
  14022. var i = 0;
  14023. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14024. for (var si = 1; si <= ns; si++) {
  14025. for (var p = 0; p < pathArray.length; p++) {
  14026. var path = pathArray[p];
  14027. var l = path.length;
  14028. minlg = (minlg < l) ? minlg : l;
  14029. var j = 0;
  14030. while (j < minlg) {
  14031. positions[i] = path[j].x;
  14032. positions[i + 1] = path[j].y;
  14033. positions[i + 2] = path[j].z;
  14034. j++;
  14035. i += 3;
  14036. }
  14037. }
  14038. }
  14039. };
  14040. return positionFunction;
  14041. };
  14042. var sideOrientation = ribbonInstance.sideOrientation;
  14043. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14044. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14045. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14046. return ribbonInstance;
  14047. }
  14048. else {
  14049. var ribbon = new Mesh(name, scene);
  14050. ribbon.sideOrientation = sideOrientation;
  14051. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14052. vertexData.applyToMesh(ribbon, updatable);
  14053. return ribbon;
  14054. }
  14055. };
  14056. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14057. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14058. var disc = new Mesh(name, scene);
  14059. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14060. vertexData.applyToMesh(disc, updatable);
  14061. return disc;
  14062. };
  14063. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14064. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14065. var box = new Mesh(name, scene);
  14066. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14067. vertexData.applyToMesh(box, updatable);
  14068. return box;
  14069. };
  14070. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14071. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14072. var sphere = new Mesh(name, scene);
  14073. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14074. vertexData.applyToMesh(sphere, updatable);
  14075. return sphere;
  14076. };
  14077. // Cylinder and cone (Code inspired by SharpDX.org)
  14078. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14079. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14080. // subdivisions is a new parameter, we need to support old signature
  14081. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14082. if (scene !== undefined) {
  14083. updatable = scene;
  14084. }
  14085. scene = subdivisions;
  14086. subdivisions = 1;
  14087. }
  14088. var cylinder = new Mesh(name, scene);
  14089. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14090. vertexData.applyToMesh(cylinder, updatable);
  14091. return cylinder;
  14092. };
  14093. // Torus (Code from SharpDX.org)
  14094. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14095. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14096. var torus = new Mesh(name, scene);
  14097. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14098. vertexData.applyToMesh(torus, updatable);
  14099. return torus;
  14100. };
  14101. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14102. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14103. var torusKnot = new Mesh(name, scene);
  14104. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14105. vertexData.applyToMesh(torusKnot, updatable);
  14106. return torusKnot;
  14107. };
  14108. // Lines
  14109. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14110. if (linesInstance === void 0) { linesInstance = null; }
  14111. if (linesInstance) {
  14112. var positionsOfLines = function (points) {
  14113. var positionFunction = function (positions) {
  14114. var i = 0;
  14115. for (var p = 0; p < points.length; p++) {
  14116. positions[i] = points[p].x;
  14117. positions[i + 1] = points[p].y;
  14118. positions[i + 2] = points[p].z;
  14119. i += 3;
  14120. }
  14121. };
  14122. return positionFunction;
  14123. };
  14124. var positionFunction = positionsOfLines(points);
  14125. linesInstance.updateMeshPositions(positionFunction, false);
  14126. return linesInstance;
  14127. }
  14128. // lines creation
  14129. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14130. var vertexData = BABYLON.VertexData.CreateLines(points);
  14131. vertexData.applyToMesh(lines, updatable);
  14132. return lines;
  14133. };
  14134. // Extrusion
  14135. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14136. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14137. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14138. scale = scale || 1;
  14139. rotation = rotation || 0;
  14140. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14141. return extruded;
  14142. };
  14143. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14144. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14145. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14146. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14147. return extrudedCustom;
  14148. };
  14149. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14150. // extrusion geometry
  14151. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14152. var tangents = path3D.getTangents();
  14153. var normals = path3D.getNormals();
  14154. var binormals = path3D.getBinormals();
  14155. var distances = path3D.getDistances();
  14156. var angle = 0;
  14157. var returnScale = function (i, distance) {
  14158. return scale;
  14159. };
  14160. var returnRotation = function (i, distance) {
  14161. return rotation;
  14162. };
  14163. var rotate = custom ? rotateFunction : returnRotation;
  14164. var scl = custom ? scaleFunction : returnScale;
  14165. var index = 0;
  14166. for (var i = 0; i < curve.length; i++) {
  14167. var shapePath = new Array();
  14168. var angleStep = rotate(i, distances[i]);
  14169. var scaleRatio = scl(i, distances[i]);
  14170. for (var p = 0; p < shape.length; p++) {
  14171. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14172. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14173. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14174. shapePath.push(rotated);
  14175. }
  14176. shapePaths[index] = shapePath;
  14177. angle += angleStep;
  14178. index++;
  14179. }
  14180. // cap
  14181. var capPath = function (shapePath) {
  14182. var pointCap = Array();
  14183. var barycenter = BABYLON.Vector3.Zero();
  14184. var i;
  14185. for (i = 0; i < shapePath.length; i++) {
  14186. barycenter.addInPlace(shapePath[i]);
  14187. }
  14188. barycenter.scaleInPlace(1 / shapePath.length);
  14189. for (i = 0; i < shapePath.length; i++) {
  14190. pointCap.push(barycenter);
  14191. }
  14192. return pointCap;
  14193. };
  14194. switch (cap) {
  14195. case BABYLON.Mesh.NO_CAP:
  14196. break;
  14197. case BABYLON.Mesh.CAP_START:
  14198. shapePaths.unshift(capPath(shapePaths[0]));
  14199. break;
  14200. case BABYLON.Mesh.CAP_END:
  14201. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14202. break;
  14203. case BABYLON.Mesh.CAP_ALL:
  14204. shapePaths.unshift(capPath(shapePaths[0]));
  14205. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14206. break;
  14207. default:
  14208. break;
  14209. }
  14210. return shapePaths;
  14211. };
  14212. if (instance) {
  14213. var path3D = (instance.path3D).update(curve);
  14214. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14215. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14216. return instance;
  14217. }
  14218. // extruded shape creation
  14219. var path3D = new BABYLON.Path3D(curve);
  14220. var newShapePaths = new Array();
  14221. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14222. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14223. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14224. extrudedGeneric.pathArray = pathArray;
  14225. extrudedGeneric.path3D = path3D;
  14226. extrudedGeneric.cap = cap;
  14227. return extrudedGeneric;
  14228. };
  14229. // Plane & ground
  14230. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14231. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14232. var plane = new Mesh(name, scene);
  14233. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14234. vertexData.applyToMesh(plane, updatable);
  14235. return plane;
  14236. };
  14237. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14238. var ground = new BABYLON.GroundMesh(name, scene);
  14239. ground._setReady(false);
  14240. ground._subdivisions = subdivisions;
  14241. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14242. vertexData.applyToMesh(ground, updatable);
  14243. ground._setReady(true);
  14244. return ground;
  14245. };
  14246. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14247. var tiledGround = new Mesh(name, scene);
  14248. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14249. vertexData.applyToMesh(tiledGround, updatable);
  14250. return tiledGround;
  14251. };
  14252. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14253. var ground = new BABYLON.GroundMesh(name, scene);
  14254. ground._subdivisions = subdivisions;
  14255. ground._setReady(false);
  14256. var onload = function (img) {
  14257. // Getting height map data
  14258. var canvas = document.createElement("canvas");
  14259. var context = canvas.getContext("2d");
  14260. var heightMapWidth = img.width;
  14261. var heightMapHeight = img.height;
  14262. canvas.width = heightMapWidth;
  14263. canvas.height = heightMapHeight;
  14264. context.drawImage(img, 0, 0);
  14265. // Create VertexData from map data
  14266. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14267. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14268. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14269. vertexData.applyToMesh(ground, updatable);
  14270. ground._setReady(true);
  14271. //execute ready callback, if set
  14272. if (onReady) {
  14273. onReady(ground);
  14274. }
  14275. };
  14276. BABYLON.Tools.LoadImage(url, onload, function () {
  14277. }, scene.database);
  14278. return ground;
  14279. };
  14280. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14281. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14282. if (tubeInstance === void 0) { tubeInstance = null; }
  14283. // tube geometry
  14284. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14285. var tangents = path3D.getTangents();
  14286. var normals = path3D.getNormals();
  14287. var distances = path3D.getDistances();
  14288. var pi2 = Math.PI * 2;
  14289. var step = pi2 / tessellation;
  14290. var returnRadius = function (i, distance) { return radius; };
  14291. var radiusFunctionFinal = radiusFunction || returnRadius;
  14292. var circlePath;
  14293. var rad;
  14294. var normal;
  14295. var rotated;
  14296. var rotationMatrix;
  14297. var index = 0;
  14298. for (var i = 0; i < path.length; i++) {
  14299. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14300. circlePath = Array(); // current circle array
  14301. normal = normals[i]; // current normal
  14302. for (var t = 0; t < tessellation; t++) {
  14303. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14304. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14305. circlePath.push(rotated);
  14306. }
  14307. circlePath.push(circlePath[0]);
  14308. circlePaths[index] = circlePath;
  14309. index++;
  14310. }
  14311. // cap
  14312. var capPath = function (nbPoints, pathIndex) {
  14313. var pointCap = Array();
  14314. for (var i = 0; i < nbPoints; i++) {
  14315. pointCap.push(path[pathIndex]);
  14316. }
  14317. return pointCap;
  14318. };
  14319. switch (cap) {
  14320. case BABYLON.Mesh.NO_CAP:
  14321. break;
  14322. case BABYLON.Mesh.CAP_START:
  14323. circlePaths.unshift(capPath(tessellation + 1, 0));
  14324. break;
  14325. case BABYLON.Mesh.CAP_END:
  14326. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14327. break;
  14328. case BABYLON.Mesh.CAP_ALL:
  14329. circlePaths.unshift(capPath(tessellation + 1, 0));
  14330. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14331. break;
  14332. default:
  14333. break;
  14334. }
  14335. return circlePaths;
  14336. };
  14337. if (tubeInstance) {
  14338. var path3D = (tubeInstance.path3D).update(path);
  14339. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14340. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14341. return tubeInstance;
  14342. }
  14343. // tube creation
  14344. var path3D = new BABYLON.Path3D(path);
  14345. var newPathArray = new Array();
  14346. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14347. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14348. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14349. tube.pathArray = pathArray;
  14350. tube.path3D = path3D;
  14351. tube.tessellation = tessellation;
  14352. tube.cap = cap;
  14353. return tube;
  14354. };
  14355. // Decals
  14356. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14357. if (angle === void 0) { angle = 0; }
  14358. var indices = sourceMesh.getIndices();
  14359. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14360. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14361. // Getting correct rotation
  14362. if (!normal) {
  14363. var target = new BABYLON.Vector3(0, 0, 1);
  14364. var camera = sourceMesh.getScene().activeCamera;
  14365. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14366. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14367. }
  14368. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14369. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14370. var pitch = Math.atan2(normal.y, len);
  14371. // Matrix
  14372. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14373. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14374. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14375. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14376. var vertexData = new BABYLON.VertexData();
  14377. vertexData.indices = [];
  14378. vertexData.positions = [];
  14379. vertexData.normals = [];
  14380. vertexData.uvs = [];
  14381. var currentVertexDataIndex = 0;
  14382. var extractDecalVector3 = function (indexId) {
  14383. var vertexId = indices[indexId];
  14384. var result = new BABYLON.PositionNormalVertex();
  14385. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14386. // Send vector to decal local world
  14387. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14388. // Get normal
  14389. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14390. return result;
  14391. };
  14392. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14393. var clip = function (vertices, axis) {
  14394. if (vertices.length === 0) {
  14395. return vertices;
  14396. }
  14397. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14398. var clipVertices = function (v0, v1) {
  14399. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14400. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14401. };
  14402. var result = new Array();
  14403. for (var index = 0; index < vertices.length; index += 3) {
  14404. var v1Out;
  14405. var v2Out;
  14406. var v3Out;
  14407. var total = 0;
  14408. var nV1, nV2, nV3, nV4;
  14409. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14410. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14411. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14412. v1Out = d1 > 0;
  14413. v2Out = d2 > 0;
  14414. v3Out = d3 > 0;
  14415. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14416. switch (total) {
  14417. case 0:
  14418. result.push(vertices[index]);
  14419. result.push(vertices[index + 1]);
  14420. result.push(vertices[index + 2]);
  14421. break;
  14422. case 1:
  14423. if (v1Out) {
  14424. nV1 = vertices[index + 1];
  14425. nV2 = vertices[index + 2];
  14426. nV3 = clipVertices(vertices[index], nV1);
  14427. nV4 = clipVertices(vertices[index], nV2);
  14428. }
  14429. if (v2Out) {
  14430. nV1 = vertices[index];
  14431. nV2 = vertices[index + 2];
  14432. nV3 = clipVertices(vertices[index + 1], nV1);
  14433. nV4 = clipVertices(vertices[index + 1], nV2);
  14434. result.push(nV3);
  14435. result.push(nV2.clone());
  14436. result.push(nV1.clone());
  14437. result.push(nV2.clone());
  14438. result.push(nV3.clone());
  14439. result.push(nV4);
  14440. break;
  14441. }
  14442. if (v3Out) {
  14443. nV1 = vertices[index];
  14444. nV2 = vertices[index + 1];
  14445. nV3 = clipVertices(vertices[index + 2], nV1);
  14446. nV4 = clipVertices(vertices[index + 2], nV2);
  14447. }
  14448. result.push(nV1.clone());
  14449. result.push(nV2.clone());
  14450. result.push(nV3);
  14451. result.push(nV4);
  14452. result.push(nV3.clone());
  14453. result.push(nV2.clone());
  14454. break;
  14455. case 2:
  14456. if (!v1Out) {
  14457. nV1 = vertices[index].clone();
  14458. nV2 = clipVertices(nV1, vertices[index + 1]);
  14459. nV3 = clipVertices(nV1, vertices[index + 2]);
  14460. result.push(nV1);
  14461. result.push(nV2);
  14462. result.push(nV3);
  14463. }
  14464. if (!v2Out) {
  14465. nV1 = vertices[index + 1].clone();
  14466. nV2 = clipVertices(nV1, vertices[index + 2]);
  14467. nV3 = clipVertices(nV1, vertices[index]);
  14468. result.push(nV1);
  14469. result.push(nV2);
  14470. result.push(nV3);
  14471. }
  14472. if (!v3Out) {
  14473. nV1 = vertices[index + 2].clone();
  14474. nV2 = clipVertices(nV1, vertices[index]);
  14475. nV3 = clipVertices(nV1, vertices[index + 1]);
  14476. result.push(nV1);
  14477. result.push(nV2);
  14478. result.push(nV3);
  14479. }
  14480. break;
  14481. case 3:
  14482. break;
  14483. }
  14484. }
  14485. return result;
  14486. };
  14487. for (var index = 0; index < indices.length; index += 3) {
  14488. var faceVertices = new Array();
  14489. faceVertices.push(extractDecalVector3(index));
  14490. faceVertices.push(extractDecalVector3(index + 1));
  14491. faceVertices.push(extractDecalVector3(index + 2));
  14492. // Clip
  14493. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14494. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14495. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14496. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14497. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14498. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14499. if (faceVertices.length === 0) {
  14500. continue;
  14501. }
  14502. // Add UVs and get back to world
  14503. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14504. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14505. var vertex = faceVertices[vIndex];
  14506. vertexData.indices.push(currentVertexDataIndex);
  14507. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14508. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14509. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14510. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14511. currentVertexDataIndex++;
  14512. }
  14513. }
  14514. // Return mesh
  14515. var decal = new Mesh(name, sourceMesh.getScene());
  14516. vertexData.applyToMesh(decal);
  14517. decal.position = position.clone();
  14518. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14519. return decal;
  14520. };
  14521. // Tools
  14522. Mesh.MinMax = function (meshes) {
  14523. var minVector = null;
  14524. var maxVector = null;
  14525. for (var i in meshes) {
  14526. var mesh = meshes[i];
  14527. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14528. if (!minVector) {
  14529. minVector = boundingBox.minimumWorld;
  14530. maxVector = boundingBox.maximumWorld;
  14531. continue;
  14532. }
  14533. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14534. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14535. }
  14536. return {
  14537. min: minVector,
  14538. max: maxVector
  14539. };
  14540. };
  14541. Mesh.Center = function (meshesOrMinMaxVector) {
  14542. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14543. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14544. };
  14545. /**
  14546. * Merge the array of meshes into a single mesh for performance reasons.
  14547. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14548. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14549. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14550. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14551. */
  14552. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14553. if (disposeSource === void 0) { disposeSource = true; }
  14554. if (!allow32BitsIndices) {
  14555. var totalVertices = 0;
  14556. for (var index = 0; index < meshes.length; index++) {
  14557. if (meshes[index]) {
  14558. totalVertices += meshes[index].getTotalVertices();
  14559. if (totalVertices > 65536) {
  14560. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14561. return null;
  14562. }
  14563. }
  14564. }
  14565. }
  14566. // Merge
  14567. var vertexData;
  14568. var otherVertexData;
  14569. var source;
  14570. for (index = 0; index < meshes.length; index++) {
  14571. if (meshes[index]) {
  14572. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14573. otherVertexData.transform(meshes[index].getWorldMatrix());
  14574. if (vertexData) {
  14575. vertexData.merge(otherVertexData);
  14576. }
  14577. else {
  14578. vertexData = otherVertexData;
  14579. source = meshes[index];
  14580. }
  14581. }
  14582. }
  14583. if (!meshSubclass) {
  14584. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14585. }
  14586. vertexData.applyToMesh(meshSubclass);
  14587. // Setting properties
  14588. meshSubclass.material = source.material;
  14589. meshSubclass.checkCollisions = source.checkCollisions;
  14590. // Cleaning
  14591. if (disposeSource) {
  14592. for (index = 0; index < meshes.length; index++) {
  14593. if (meshes[index]) {
  14594. meshes[index].dispose();
  14595. }
  14596. }
  14597. }
  14598. return meshSubclass;
  14599. };
  14600. // Consts
  14601. Mesh._FRONTSIDE = 0;
  14602. Mesh._BACKSIDE = 1;
  14603. Mesh._DOUBLESIDE = 2;
  14604. Mesh._DEFAULTSIDE = 0;
  14605. Mesh._NO_CAP = 0;
  14606. Mesh._CAP_START = 1;
  14607. Mesh._CAP_END = 2;
  14608. Mesh._CAP_ALL = 3;
  14609. return Mesh;
  14610. })(BABYLON.AbstractMesh);
  14611. BABYLON.Mesh = Mesh;
  14612. })(BABYLON || (BABYLON = {}));
  14613. //# sourceMappingURL=babylon.mesh.js.map
  14614. var BABYLON;
  14615. (function (BABYLON) {
  14616. var SubMesh = (function () {
  14617. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  14618. if (createBoundingBox === void 0) { createBoundingBox = true; }
  14619. this.materialIndex = materialIndex;
  14620. this.verticesStart = verticesStart;
  14621. this.verticesCount = verticesCount;
  14622. this.indexStart = indexStart;
  14623. this.indexCount = indexCount;
  14624. this._renderId = 0;
  14625. this._mesh = mesh;
  14626. this._renderingMesh = renderingMesh || mesh;
  14627. mesh.subMeshes.push(this);
  14628. this._trianglePlanes = [];
  14629. this._id = mesh.subMeshes.length - 1;
  14630. if (createBoundingBox) {
  14631. this.refreshBoundingInfo();
  14632. mesh.computeWorldMatrix(true);
  14633. }
  14634. }
  14635. SubMesh.prototype.getBoundingInfo = function () {
  14636. return this._boundingInfo;
  14637. };
  14638. SubMesh.prototype.getMesh = function () {
  14639. return this._mesh;
  14640. };
  14641. SubMesh.prototype.getRenderingMesh = function () {
  14642. return this._renderingMesh;
  14643. };
  14644. SubMesh.prototype.getMaterial = function () {
  14645. var rootMaterial = this._renderingMesh.material;
  14646. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  14647. var multiMaterial = rootMaterial;
  14648. return multiMaterial.getSubMaterial(this.materialIndex);
  14649. }
  14650. if (!rootMaterial) {
  14651. return this._mesh.getScene().defaultMaterial;
  14652. }
  14653. return rootMaterial;
  14654. };
  14655. // Methods
  14656. SubMesh.prototype.refreshBoundingInfo = function () {
  14657. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14658. if (!data) {
  14659. this._boundingInfo = this._mesh._boundingInfo;
  14660. return;
  14661. }
  14662. var indices = this._renderingMesh.getIndices();
  14663. var extend;
  14664. if (this.indexStart === 0 && this.indexCount === indices.length) {
  14665. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  14666. }
  14667. else {
  14668. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  14669. }
  14670. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14671. };
  14672. SubMesh.prototype._checkCollision = function (collider) {
  14673. return this._boundingInfo._checkCollision(collider);
  14674. };
  14675. SubMesh.prototype.updateBoundingInfo = function (world) {
  14676. if (!this._boundingInfo) {
  14677. this.refreshBoundingInfo();
  14678. }
  14679. this._boundingInfo._update(world);
  14680. };
  14681. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  14682. return this._boundingInfo.isInFrustum(frustumPlanes);
  14683. };
  14684. SubMesh.prototype.render = function () {
  14685. this._renderingMesh.render(this);
  14686. };
  14687. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  14688. if (!this._linesIndexBuffer) {
  14689. var linesIndices = [];
  14690. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14691. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  14692. }
  14693. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  14694. this.linesIndexCount = linesIndices.length;
  14695. }
  14696. return this._linesIndexBuffer;
  14697. };
  14698. SubMesh.prototype.canIntersects = function (ray) {
  14699. return ray.intersectsBox(this._boundingInfo.boundingBox);
  14700. };
  14701. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  14702. var intersectInfo = null;
  14703. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14704. var p0 = positions[indices[index]];
  14705. var p1 = positions[indices[index + 1]];
  14706. var p2 = positions[indices[index + 2]];
  14707. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  14708. if (currentIntersectInfo) {
  14709. if (currentIntersectInfo.distance < 0) {
  14710. continue;
  14711. }
  14712. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14713. intersectInfo = currentIntersectInfo;
  14714. intersectInfo.faceId = index / 3;
  14715. if (fastCheck) {
  14716. break;
  14717. }
  14718. }
  14719. }
  14720. }
  14721. return intersectInfo;
  14722. };
  14723. // Clone
  14724. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  14725. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  14726. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  14727. return result;
  14728. };
  14729. // Dispose
  14730. SubMesh.prototype.dispose = function () {
  14731. if (this._linesIndexBuffer) {
  14732. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  14733. this._linesIndexBuffer = null;
  14734. }
  14735. // Remove from mesh
  14736. var index = this._mesh.subMeshes.indexOf(this);
  14737. this._mesh.subMeshes.splice(index, 1);
  14738. };
  14739. // Statics
  14740. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  14741. var minVertexIndex = Number.MAX_VALUE;
  14742. var maxVertexIndex = -Number.MAX_VALUE;
  14743. renderingMesh = renderingMesh || mesh;
  14744. var indices = renderingMesh.getIndices();
  14745. for (var index = startIndex; index < startIndex + indexCount; index++) {
  14746. var vertexIndex = indices[index];
  14747. if (vertexIndex < minVertexIndex)
  14748. minVertexIndex = vertexIndex;
  14749. if (vertexIndex > maxVertexIndex)
  14750. maxVertexIndex = vertexIndex;
  14751. }
  14752. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  14753. };
  14754. return SubMesh;
  14755. })();
  14756. BABYLON.SubMesh = SubMesh;
  14757. })(BABYLON || (BABYLON = {}));
  14758. //# sourceMappingURL=babylon.subMesh.js.map
  14759. var BABYLON;
  14760. (function (BABYLON) {
  14761. var BaseTexture = (function () {
  14762. function BaseTexture(scene) {
  14763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14764. this.hasAlpha = false;
  14765. this.getAlphaFromRGB = false;
  14766. this.level = 1;
  14767. this.isCube = false;
  14768. this.isRenderTarget = false;
  14769. this.animations = new Array();
  14770. this.coordinatesIndex = 0;
  14771. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  14772. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14773. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14774. this.anisotropicFilteringLevel = 4;
  14775. this._scene = scene;
  14776. this._scene.textures.push(this);
  14777. }
  14778. BaseTexture.prototype.getScene = function () {
  14779. return this._scene;
  14780. };
  14781. BaseTexture.prototype.getTextureMatrix = function () {
  14782. return null;
  14783. };
  14784. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  14785. return null;
  14786. };
  14787. BaseTexture.prototype.getInternalTexture = function () {
  14788. return this._texture;
  14789. };
  14790. BaseTexture.prototype.isReady = function () {
  14791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14792. return true;
  14793. }
  14794. if (this._texture) {
  14795. return this._texture.isReady;
  14796. }
  14797. return false;
  14798. };
  14799. BaseTexture.prototype.getSize = function () {
  14800. if (this._texture._width) {
  14801. return { width: this._texture._width, height: this._texture._height };
  14802. }
  14803. if (this._texture._size) {
  14804. return { width: this._texture._size, height: this._texture._size };
  14805. }
  14806. return { width: 0, height: 0 };
  14807. };
  14808. BaseTexture.prototype.getBaseSize = function () {
  14809. if (!this.isReady())
  14810. return { width: 0, height: 0 };
  14811. if (this._texture._size) {
  14812. return { width: this._texture._size, height: this._texture._size };
  14813. }
  14814. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  14815. };
  14816. BaseTexture.prototype.scale = function (ratio) {
  14817. };
  14818. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  14819. get: function () {
  14820. return false;
  14821. },
  14822. enumerable: true,
  14823. configurable: true
  14824. });
  14825. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  14826. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14827. for (var index = 0; index < texturesCache.length; index++) {
  14828. var texturesCacheEntry = texturesCache[index];
  14829. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14830. texturesCache.splice(index, 1);
  14831. return;
  14832. }
  14833. }
  14834. };
  14835. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  14836. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14837. for (var index = 0; index < texturesCache.length; index++) {
  14838. var texturesCacheEntry = texturesCache[index];
  14839. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14840. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  14841. texturesCacheEntry.references++;
  14842. return texturesCacheEntry;
  14843. }
  14844. }
  14845. }
  14846. return null;
  14847. };
  14848. BaseTexture.prototype.delayLoad = function () {
  14849. };
  14850. BaseTexture.prototype.releaseInternalTexture = function () {
  14851. if (!this._texture) {
  14852. return;
  14853. }
  14854. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14855. this._texture.references--;
  14856. // Final reference ?
  14857. if (this._texture.references === 0) {
  14858. var index = texturesCache.indexOf(this._texture);
  14859. texturesCache.splice(index, 1);
  14860. this._scene.getEngine()._releaseTexture(this._texture);
  14861. delete this._texture;
  14862. }
  14863. };
  14864. BaseTexture.prototype.clone = function () {
  14865. return null;
  14866. };
  14867. BaseTexture.prototype.dispose = function () {
  14868. // Remove from scene
  14869. var index = this._scene.textures.indexOf(this);
  14870. if (index >= 0) {
  14871. this._scene.textures.splice(index, 1);
  14872. }
  14873. if (this._texture === undefined) {
  14874. return;
  14875. }
  14876. this.releaseInternalTexture();
  14877. // Callback
  14878. if (this.onDispose) {
  14879. this.onDispose();
  14880. }
  14881. };
  14882. return BaseTexture;
  14883. })();
  14884. BABYLON.BaseTexture = BaseTexture;
  14885. })(BABYLON || (BABYLON = {}));
  14886. //# sourceMappingURL=babylon.baseTexture.js.map
  14887. var __extends = this.__extends || function (d, b) {
  14888. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14889. function __() { this.constructor = d; }
  14890. __.prototype = b.prototype;
  14891. d.prototype = new __();
  14892. };
  14893. var BABYLON;
  14894. (function (BABYLON) {
  14895. var Texture = (function (_super) {
  14896. __extends(Texture, _super);
  14897. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  14898. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  14899. if (onLoad === void 0) { onLoad = null; }
  14900. if (onError === void 0) { onError = null; }
  14901. if (buffer === void 0) { buffer = null; }
  14902. if (deleteBuffer === void 0) { deleteBuffer = false; }
  14903. _super.call(this, scene);
  14904. this.uOffset = 0;
  14905. this.vOffset = 0;
  14906. this.uScale = 1.0;
  14907. this.vScale = 1.0;
  14908. this.uAng = 0;
  14909. this.vAng = 0;
  14910. this.wAng = 0;
  14911. this.name = url;
  14912. this.url = url;
  14913. this._noMipmap = noMipmap;
  14914. this._invertY = invertY;
  14915. this._samplingMode = samplingMode;
  14916. this._buffer = buffer;
  14917. this._deleteBuffer = deleteBuffer;
  14918. if (!url) {
  14919. return;
  14920. }
  14921. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  14922. if (!this._texture) {
  14923. if (!scene.useDelayedTextureLoading) {
  14924. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  14925. if (deleteBuffer) {
  14926. delete this._buffer;
  14927. }
  14928. }
  14929. else {
  14930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14931. }
  14932. }
  14933. else {
  14934. BABYLON.Tools.SetImmediate(function () {
  14935. if (onLoad) {
  14936. onLoad();
  14937. }
  14938. });
  14939. }
  14940. }
  14941. Texture.prototype.delayLoad = function () {
  14942. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14943. return;
  14944. }
  14945. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14946. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  14947. if (!this._texture) {
  14948. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  14949. if (this._deleteBuffer) {
  14950. delete this._buffer;
  14951. }
  14952. }
  14953. };
  14954. Texture.prototype.updateSamplingMode = function (samplingMode) {
  14955. if (!this._texture) {
  14956. return;
  14957. }
  14958. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  14959. };
  14960. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  14961. x -= this.uOffset + 0.5;
  14962. y -= this.vOffset + 0.5;
  14963. z -= 0.5;
  14964. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  14965. t.x *= this.uScale;
  14966. t.y *= this.vScale;
  14967. t.x += 0.5;
  14968. t.y += 0.5;
  14969. t.z += 0.5;
  14970. };
  14971. Texture.prototype.getTextureMatrix = function () {
  14972. 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) {
  14973. return this._cachedTextureMatrix;
  14974. }
  14975. this._cachedUOffset = this.uOffset;
  14976. this._cachedVOffset = this.vOffset;
  14977. this._cachedUScale = this.uScale;
  14978. this._cachedVScale = this.vScale;
  14979. this._cachedUAng = this.uAng;
  14980. this._cachedVAng = this.vAng;
  14981. this._cachedWAng = this.wAng;
  14982. if (!this._cachedTextureMatrix) {
  14983. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14984. this._rowGenerationMatrix = new BABYLON.Matrix();
  14985. this._t0 = BABYLON.Vector3.Zero();
  14986. this._t1 = BABYLON.Vector3.Zero();
  14987. this._t2 = BABYLON.Vector3.Zero();
  14988. }
  14989. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  14990. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  14991. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  14992. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  14993. this._t1.subtractInPlace(this._t0);
  14994. this._t2.subtractInPlace(this._t0);
  14995. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  14996. this._cachedTextureMatrix.m[0] = this._t1.x;
  14997. this._cachedTextureMatrix.m[1] = this._t1.y;
  14998. this._cachedTextureMatrix.m[2] = this._t1.z;
  14999. this._cachedTextureMatrix.m[4] = this._t2.x;
  15000. this._cachedTextureMatrix.m[5] = this._t2.y;
  15001. this._cachedTextureMatrix.m[6] = this._t2.z;
  15002. this._cachedTextureMatrix.m[8] = this._t0.x;
  15003. this._cachedTextureMatrix.m[9] = this._t0.y;
  15004. this._cachedTextureMatrix.m[10] = this._t0.z;
  15005. return this._cachedTextureMatrix;
  15006. };
  15007. Texture.prototype.getReflectionTextureMatrix = function () {
  15008. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  15009. return this._cachedTextureMatrix;
  15010. }
  15011. if (!this._cachedTextureMatrix) {
  15012. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  15013. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  15014. }
  15015. this._cachedCoordinatesMode = this.coordinatesMode;
  15016. switch (this.coordinatesMode) {
  15017. case Texture.SPHERICAL_MODE:
  15018. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15019. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  15020. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  15021. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15022. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15023. break;
  15024. case Texture.PLANAR_MODE:
  15025. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15026. this._cachedTextureMatrix[0] = this.uScale;
  15027. this._cachedTextureMatrix[5] = this.vScale;
  15028. this._cachedTextureMatrix[12] = this.uOffset;
  15029. this._cachedTextureMatrix[13] = this.vOffset;
  15030. break;
  15031. case Texture.PROJECTION_MODE:
  15032. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15033. this._projectionModeMatrix.m[0] = 0.5;
  15034. this._projectionModeMatrix.m[5] = -0.5;
  15035. this._projectionModeMatrix.m[10] = 0.0;
  15036. this._projectionModeMatrix.m[12] = 0.5;
  15037. this._projectionModeMatrix.m[13] = 0.5;
  15038. this._projectionModeMatrix.m[14] = 1.0;
  15039. this._projectionModeMatrix.m[15] = 1.0;
  15040. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15041. break;
  15042. default:
  15043. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15044. break;
  15045. }
  15046. return this._cachedTextureMatrix;
  15047. };
  15048. Texture.prototype.clone = function () {
  15049. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15050. // Base texture
  15051. newTexture.hasAlpha = this.hasAlpha;
  15052. newTexture.level = this.level;
  15053. newTexture.wrapU = this.wrapU;
  15054. newTexture.wrapV = this.wrapV;
  15055. newTexture.coordinatesIndex = this.coordinatesIndex;
  15056. newTexture.coordinatesMode = this.coordinatesMode;
  15057. // Texture
  15058. newTexture.uOffset = this.uOffset;
  15059. newTexture.vOffset = this.vOffset;
  15060. newTexture.uScale = this.uScale;
  15061. newTexture.vScale = this.vScale;
  15062. newTexture.uAng = this.uAng;
  15063. newTexture.vAng = this.vAng;
  15064. newTexture.wAng = this.wAng;
  15065. return newTexture;
  15066. };
  15067. // Statics
  15068. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15069. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15070. if (onLoad === void 0) { onLoad = null; }
  15071. if (onError === void 0) { onError = null; }
  15072. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15073. };
  15074. // Constants
  15075. Texture.NEAREST_SAMPLINGMODE = 1;
  15076. Texture.BILINEAR_SAMPLINGMODE = 2;
  15077. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15078. Texture.EXPLICIT_MODE = 0;
  15079. Texture.SPHERICAL_MODE = 1;
  15080. Texture.PLANAR_MODE = 2;
  15081. Texture.CUBIC_MODE = 3;
  15082. Texture.PROJECTION_MODE = 4;
  15083. Texture.SKYBOX_MODE = 5;
  15084. Texture.CLAMP_ADDRESSMODE = 0;
  15085. Texture.WRAP_ADDRESSMODE = 1;
  15086. Texture.MIRROR_ADDRESSMODE = 2;
  15087. return Texture;
  15088. })(BABYLON.BaseTexture);
  15089. BABYLON.Texture = Texture;
  15090. })(BABYLON || (BABYLON = {}));
  15091. //# sourceMappingURL=babylon.texture.js.map
  15092. var __extends = this.__extends || function (d, b) {
  15093. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15094. function __() { this.constructor = d; }
  15095. __.prototype = b.prototype;
  15096. d.prototype = new __();
  15097. };
  15098. var BABYLON;
  15099. (function (BABYLON) {
  15100. var CubeTexture = (function (_super) {
  15101. __extends(CubeTexture, _super);
  15102. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15103. _super.call(this, scene);
  15104. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15105. this.name = rootUrl;
  15106. this.url = rootUrl;
  15107. this._noMipmap = noMipmap;
  15108. this.hasAlpha = false;
  15109. this._texture = this._getFromCache(rootUrl, noMipmap);
  15110. if (!extensions) {
  15111. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15112. }
  15113. this._extensions = extensions;
  15114. if (!this._texture) {
  15115. if (!scene.useDelayedTextureLoading) {
  15116. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15117. }
  15118. else {
  15119. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15120. }
  15121. }
  15122. this.isCube = true;
  15123. this._textureMatrix = BABYLON.Matrix.Identity();
  15124. }
  15125. CubeTexture.prototype.clone = function () {
  15126. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15127. // Base texture
  15128. newTexture.level = this.level;
  15129. newTexture.wrapU = this.wrapU;
  15130. newTexture.wrapV = this.wrapV;
  15131. newTexture.coordinatesIndex = this.coordinatesIndex;
  15132. newTexture.coordinatesMode = this.coordinatesMode;
  15133. return newTexture;
  15134. };
  15135. // Methods
  15136. CubeTexture.prototype.delayLoad = function () {
  15137. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15138. return;
  15139. }
  15140. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15141. this._texture = this._getFromCache(this.url, this._noMipmap);
  15142. if (!this._texture) {
  15143. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15144. }
  15145. };
  15146. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15147. return this._textureMatrix;
  15148. };
  15149. return CubeTexture;
  15150. })(BABYLON.BaseTexture);
  15151. BABYLON.CubeTexture = CubeTexture;
  15152. })(BABYLON || (BABYLON = {}));
  15153. //# sourceMappingURL=babylon.cubeTexture.js.map
  15154. var __extends = this.__extends || function (d, b) {
  15155. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15156. function __() { this.constructor = d; }
  15157. __.prototype = b.prototype;
  15158. d.prototype = new __();
  15159. };
  15160. var BABYLON;
  15161. (function (BABYLON) {
  15162. var RenderTargetTexture = (function (_super) {
  15163. __extends(RenderTargetTexture, _super);
  15164. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15165. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15166. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15167. _super.call(this, null, scene, !generateMipMaps);
  15168. this.renderList = new Array();
  15169. this.renderParticles = true;
  15170. this.renderSprites = false;
  15171. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15172. this._currentRefreshId = -1;
  15173. this._refreshRate = 1;
  15174. this.name = name;
  15175. this.isRenderTarget = true;
  15176. this._size = size;
  15177. this._generateMipMaps = generateMipMaps;
  15178. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15179. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15180. // Rendering groups
  15181. this._renderingManager = new BABYLON.RenderingManager(scene);
  15182. }
  15183. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15184. this._currentRefreshId = -1;
  15185. };
  15186. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15187. get: function () {
  15188. return this._refreshRate;
  15189. },
  15190. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15191. set: function (value) {
  15192. this._refreshRate = value;
  15193. this.resetRefreshCounter();
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. RenderTargetTexture.prototype._shouldRender = function () {
  15199. if (this._currentRefreshId === -1) {
  15200. this._currentRefreshId = 1;
  15201. return true;
  15202. }
  15203. if (this.refreshRate === this._currentRefreshId) {
  15204. this._currentRefreshId = 1;
  15205. return true;
  15206. }
  15207. this._currentRefreshId++;
  15208. return false;
  15209. };
  15210. RenderTargetTexture.prototype.isReady = function () {
  15211. if (!this.getScene().renderTargetsEnabled) {
  15212. return false;
  15213. }
  15214. return _super.prototype.isReady.call(this);
  15215. };
  15216. RenderTargetTexture.prototype.getRenderSize = function () {
  15217. return this._size;
  15218. };
  15219. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15220. get: function () {
  15221. return true;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. RenderTargetTexture.prototype.scale = function (ratio) {
  15227. var newSize = this._size * ratio;
  15228. this.resize(newSize, this._generateMipMaps);
  15229. };
  15230. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15231. this.releaseInternalTexture();
  15232. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15233. };
  15234. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15235. var scene = this.getScene();
  15236. var engine = scene.getEngine();
  15237. if (this._waitingRenderList) {
  15238. this.renderList = [];
  15239. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15240. var id = this._waitingRenderList[index];
  15241. this.renderList.push(scene.getMeshByID(id));
  15242. }
  15243. delete this._waitingRenderList;
  15244. }
  15245. if (this.renderList && this.renderList.length === 0) {
  15246. return;
  15247. }
  15248. // Bind
  15249. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15250. engine.bindFramebuffer(this._texture);
  15251. }
  15252. this._renderingManager.reset();
  15253. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15254. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15255. var mesh = currentRenderList[meshIndex];
  15256. if (mesh) {
  15257. if (!mesh.isReady()) {
  15258. // Reset _currentRefreshId
  15259. this.resetRefreshCounter();
  15260. continue;
  15261. }
  15262. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15263. mesh._activate(scene.getRenderId());
  15264. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15265. var subMesh = mesh.subMeshes[subIndex];
  15266. scene._activeIndices += subMesh.indexCount;
  15267. this._renderingManager.dispatch(subMesh);
  15268. }
  15269. }
  15270. }
  15271. }
  15272. if (this.onBeforeRender) {
  15273. this.onBeforeRender();
  15274. }
  15275. // Clear
  15276. if (this.onClear) {
  15277. this.onClear(engine);
  15278. }
  15279. else {
  15280. engine.clear(scene.clearColor, true, true);
  15281. }
  15282. if (!this._doNotChangeAspectRatio) {
  15283. scene.updateTransformMatrix(true);
  15284. }
  15285. // Render
  15286. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15287. if (useCameraPostProcess) {
  15288. scene.postProcessManager._finalizeFrame(false, this._texture);
  15289. }
  15290. if (!this._doNotChangeAspectRatio) {
  15291. scene.updateTransformMatrix(true);
  15292. }
  15293. if (this.onAfterRender) {
  15294. this.onAfterRender();
  15295. }
  15296. // Dump ?
  15297. if (dumpForDebug) {
  15298. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15299. }
  15300. // Unbind
  15301. engine.unBindFramebuffer(this._texture);
  15302. if (this.onAfterUnbind) {
  15303. this.onAfterUnbind();
  15304. }
  15305. };
  15306. RenderTargetTexture.prototype.clone = function () {
  15307. var textureSize = this.getSize();
  15308. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15309. // Base texture
  15310. newTexture.hasAlpha = this.hasAlpha;
  15311. newTexture.level = this.level;
  15312. // RenderTarget Texture
  15313. newTexture.coordinatesMode = this.coordinatesMode;
  15314. newTexture.renderList = this.renderList.slice(0);
  15315. return newTexture;
  15316. };
  15317. return RenderTargetTexture;
  15318. })(BABYLON.Texture);
  15319. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15320. })(BABYLON || (BABYLON = {}));
  15321. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15322. var __extends = this.__extends || function (d, b) {
  15323. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15324. function __() { this.constructor = d; }
  15325. __.prototype = b.prototype;
  15326. d.prototype = new __();
  15327. };
  15328. var BABYLON;
  15329. (function (BABYLON) {
  15330. var ProceduralTexture = (function (_super) {
  15331. __extends(ProceduralTexture, _super);
  15332. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15333. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15334. _super.call(this, null, scene, !generateMipMaps);
  15335. this._currentRefreshId = -1;
  15336. this._refreshRate = 1;
  15337. this._vertexDeclaration = [2];
  15338. this._vertexStrideSize = 2 * 4;
  15339. this._uniforms = new Array();
  15340. this._samplers = new Array();
  15341. this._textures = new Array();
  15342. this._floats = new Array();
  15343. this._floatsArrays = {};
  15344. this._colors3 = new Array();
  15345. this._colors4 = new Array();
  15346. this._vectors2 = new Array();
  15347. this._vectors3 = new Array();
  15348. this._matrices = new Array();
  15349. this._fallbackTextureUsed = false;
  15350. scene._proceduralTextures.push(this);
  15351. this.name = name;
  15352. this.isRenderTarget = true;
  15353. this._size = size;
  15354. this._generateMipMaps = generateMipMaps;
  15355. this.setFragment(fragment);
  15356. this._fallbackTexture = fallbackTexture;
  15357. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15358. // VBO
  15359. var vertices = [];
  15360. vertices.push(1, 1);
  15361. vertices.push(-1, 1);
  15362. vertices.push(-1, -1);
  15363. vertices.push(1, -1);
  15364. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15365. // Indices
  15366. var indices = [];
  15367. indices.push(0);
  15368. indices.push(1);
  15369. indices.push(2);
  15370. indices.push(0);
  15371. indices.push(2);
  15372. indices.push(3);
  15373. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15374. }
  15375. ProceduralTexture.prototype.reset = function () {
  15376. if (this._effect === undefined) {
  15377. return;
  15378. }
  15379. var engine = this.getScene().getEngine();
  15380. engine._releaseEffect(this._effect);
  15381. };
  15382. ProceduralTexture.prototype.isReady = function () {
  15383. var _this = this;
  15384. var engine = this.getScene().getEngine();
  15385. var shaders;
  15386. if (!this._fragment) {
  15387. return false;
  15388. }
  15389. if (this._fallbackTextureUsed) {
  15390. return true;
  15391. }
  15392. if (this._fragment.fragmentElement !== undefined) {
  15393. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15394. }
  15395. else {
  15396. shaders = { vertex: "procedural", fragment: this._fragment };
  15397. }
  15398. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15399. _this.releaseInternalTexture();
  15400. if (_this._fallbackTexture) {
  15401. _this._texture = _this._fallbackTexture._texture;
  15402. _this._texture.references++;
  15403. }
  15404. _this._fallbackTextureUsed = true;
  15405. });
  15406. return this._effect.isReady();
  15407. };
  15408. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15409. this._currentRefreshId = -1;
  15410. };
  15411. ProceduralTexture.prototype.setFragment = function (fragment) {
  15412. this._fragment = fragment;
  15413. };
  15414. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15415. get: function () {
  15416. return this._refreshRate;
  15417. },
  15418. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15419. set: function (value) {
  15420. this._refreshRate = value;
  15421. this.resetRefreshCounter();
  15422. },
  15423. enumerable: true,
  15424. configurable: true
  15425. });
  15426. ProceduralTexture.prototype._shouldRender = function () {
  15427. if (!this.isReady() || !this._texture) {
  15428. return false;
  15429. }
  15430. if (this._fallbackTextureUsed) {
  15431. return false;
  15432. }
  15433. if (this._currentRefreshId === -1) {
  15434. this._currentRefreshId = 1;
  15435. return true;
  15436. }
  15437. if (this.refreshRate === this._currentRefreshId) {
  15438. this._currentRefreshId = 1;
  15439. return true;
  15440. }
  15441. this._currentRefreshId++;
  15442. return false;
  15443. };
  15444. ProceduralTexture.prototype.getRenderSize = function () {
  15445. return this._size;
  15446. };
  15447. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15448. if (this._fallbackTextureUsed) {
  15449. return;
  15450. }
  15451. this.releaseInternalTexture();
  15452. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15453. };
  15454. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15455. if (this._uniforms.indexOf(uniformName) === -1) {
  15456. this._uniforms.push(uniformName);
  15457. }
  15458. };
  15459. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15460. if (this._samplers.indexOf(name) === -1) {
  15461. this._samplers.push(name);
  15462. }
  15463. this._textures[name] = texture;
  15464. return this;
  15465. };
  15466. ProceduralTexture.prototype.setFloat = function (name, value) {
  15467. this._checkUniform(name);
  15468. this._floats[name] = value;
  15469. return this;
  15470. };
  15471. ProceduralTexture.prototype.setFloats = function (name, value) {
  15472. this._checkUniform(name);
  15473. this._floatsArrays[name] = value;
  15474. return this;
  15475. };
  15476. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15477. this._checkUniform(name);
  15478. this._colors3[name] = value;
  15479. return this;
  15480. };
  15481. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15482. this._checkUniform(name);
  15483. this._colors4[name] = value;
  15484. return this;
  15485. };
  15486. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15487. this._checkUniform(name);
  15488. this._vectors2[name] = value;
  15489. return this;
  15490. };
  15491. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15492. this._checkUniform(name);
  15493. this._vectors3[name] = value;
  15494. return this;
  15495. };
  15496. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15497. this._checkUniform(name);
  15498. this._matrices[name] = value;
  15499. return this;
  15500. };
  15501. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15502. var scene = this.getScene();
  15503. var engine = scene.getEngine();
  15504. engine.bindFramebuffer(this._texture);
  15505. // Clear
  15506. engine.clear(scene.clearColor, true, true);
  15507. // Render
  15508. engine.enableEffect(this._effect);
  15509. engine.setState(false);
  15510. for (var name in this._textures) {
  15511. this._effect.setTexture(name, this._textures[name]);
  15512. }
  15513. for (name in this._floats) {
  15514. this._effect.setFloat(name, this._floats[name]);
  15515. }
  15516. for (name in this._floatsArrays) {
  15517. this._effect.setArray(name, this._floatsArrays[name]);
  15518. }
  15519. for (name in this._colors3) {
  15520. this._effect.setColor3(name, this._colors3[name]);
  15521. }
  15522. for (name in this._colors4) {
  15523. var color = this._colors4[name];
  15524. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15525. }
  15526. for (name in this._vectors2) {
  15527. this._effect.setVector2(name, this._vectors2[name]);
  15528. }
  15529. for (name in this._vectors3) {
  15530. this._effect.setVector3(name, this._vectors3[name]);
  15531. }
  15532. for (name in this._matrices) {
  15533. this._effect.setMatrix(name, this._matrices[name]);
  15534. }
  15535. // VBOs
  15536. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15537. // Draw order
  15538. engine.draw(true, 0, 6);
  15539. // Unbind
  15540. engine.unBindFramebuffer(this._texture);
  15541. };
  15542. ProceduralTexture.prototype.clone = function () {
  15543. var textureSize = this.getSize();
  15544. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15545. // Base texture
  15546. newTexture.hasAlpha = this.hasAlpha;
  15547. newTexture.level = this.level;
  15548. // RenderTarget Texture
  15549. newTexture.coordinatesMode = this.coordinatesMode;
  15550. return newTexture;
  15551. };
  15552. ProceduralTexture.prototype.dispose = function () {
  15553. var index = this.getScene()._proceduralTextures.indexOf(this);
  15554. if (index >= 0) {
  15555. this.getScene()._proceduralTextures.splice(index, 1);
  15556. }
  15557. _super.prototype.dispose.call(this);
  15558. };
  15559. return ProceduralTexture;
  15560. })(BABYLON.Texture);
  15561. BABYLON.ProceduralTexture = ProceduralTexture;
  15562. })(BABYLON || (BABYLON = {}));
  15563. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15564. var __extends = this.__extends || function (d, b) {
  15565. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15566. function __() { this.constructor = d; }
  15567. __.prototype = b.prototype;
  15568. d.prototype = new __();
  15569. };
  15570. var BABYLON;
  15571. (function (BABYLON) {
  15572. var MirrorTexture = (function (_super) {
  15573. __extends(MirrorTexture, _super);
  15574. function MirrorTexture(name, size, scene, generateMipMaps) {
  15575. var _this = this;
  15576. _super.call(this, name, size, scene, generateMipMaps, true);
  15577. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15578. this._transformMatrix = BABYLON.Matrix.Zero();
  15579. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15580. this.onBeforeRender = function () {
  15581. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15582. _this._savedViewMatrix = scene.getViewMatrix();
  15583. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15584. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15585. scene.clipPlane = _this.mirrorPlane;
  15586. scene.getEngine().cullBackFaces = false;
  15587. };
  15588. this.onAfterRender = function () {
  15589. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15590. scene.getEngine().cullBackFaces = true;
  15591. delete scene.clipPlane;
  15592. };
  15593. }
  15594. MirrorTexture.prototype.clone = function () {
  15595. var textureSize = this.getSize();
  15596. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15597. // Base texture
  15598. newTexture.hasAlpha = this.hasAlpha;
  15599. newTexture.level = this.level;
  15600. // Mirror Texture
  15601. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15602. newTexture.renderList = this.renderList.slice(0);
  15603. return newTexture;
  15604. };
  15605. return MirrorTexture;
  15606. })(BABYLON.RenderTargetTexture);
  15607. BABYLON.MirrorTexture = MirrorTexture;
  15608. })(BABYLON || (BABYLON = {}));
  15609. //# sourceMappingURL=babylon.mirrorTexture.js.map
  15610. var __extends = this.__extends || function (d, b) {
  15611. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15612. function __() { this.constructor = d; }
  15613. __.prototype = b.prototype;
  15614. d.prototype = new __();
  15615. };
  15616. var BABYLON;
  15617. (function (BABYLON) {
  15618. var DynamicTexture = (function (_super) {
  15619. __extends(DynamicTexture, _super);
  15620. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  15621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15622. _super.call(this, null, scene, !generateMipMaps);
  15623. this.name = name;
  15624. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15625. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15626. this._generateMipMaps = generateMipMaps;
  15627. if (options.getContext) {
  15628. this._canvas = options;
  15629. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15630. }
  15631. else {
  15632. this._canvas = document.createElement("canvas");
  15633. if (options.width) {
  15634. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15635. }
  15636. else {
  15637. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  15638. }
  15639. }
  15640. var textureSize = this.getSize();
  15641. this._canvas.width = textureSize.width;
  15642. this._canvas.height = textureSize.height;
  15643. this._context = this._canvas.getContext("2d");
  15644. }
  15645. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  15646. get: function () {
  15647. return true;
  15648. },
  15649. enumerable: true,
  15650. configurable: true
  15651. });
  15652. DynamicTexture.prototype.scale = function (ratio) {
  15653. var textureSize = this.getSize();
  15654. textureSize.width *= ratio;
  15655. textureSize.height *= ratio;
  15656. this._canvas.width = textureSize.width;
  15657. this._canvas.height = textureSize.height;
  15658. this.releaseInternalTexture();
  15659. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  15660. };
  15661. DynamicTexture.prototype.getContext = function () {
  15662. return this._context;
  15663. };
  15664. DynamicTexture.prototype.clear = function () {
  15665. var size = this.getSize();
  15666. this._context.fillRect(0, 0, size.width, size.height);
  15667. };
  15668. DynamicTexture.prototype.update = function (invertY) {
  15669. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  15670. };
  15671. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  15672. if (update === void 0) { update = true; }
  15673. var size = this.getSize();
  15674. if (clearColor) {
  15675. this._context.fillStyle = clearColor;
  15676. this._context.fillRect(0, 0, size.width, size.height);
  15677. }
  15678. this._context.font = font;
  15679. if (x === null) {
  15680. var textSize = this._context.measureText(text);
  15681. x = (size.width - textSize.width) / 2;
  15682. }
  15683. this._context.fillStyle = color;
  15684. this._context.fillText(text, x, y);
  15685. if (update) {
  15686. this.update(invertY);
  15687. }
  15688. };
  15689. DynamicTexture.prototype.clone = function () {
  15690. var textureSize = this.getSize();
  15691. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15692. // Base texture
  15693. newTexture.hasAlpha = this.hasAlpha;
  15694. newTexture.level = this.level;
  15695. // Dynamic Texture
  15696. newTexture.wrapU = this.wrapU;
  15697. newTexture.wrapV = this.wrapV;
  15698. return newTexture;
  15699. };
  15700. return DynamicTexture;
  15701. })(BABYLON.Texture);
  15702. BABYLON.DynamicTexture = DynamicTexture;
  15703. })(BABYLON || (BABYLON = {}));
  15704. //# sourceMappingURL=babylon.dynamicTexture.js.map
  15705. var __extends = this.__extends || function (d, b) {
  15706. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15707. function __() { this.constructor = d; }
  15708. __.prototype = b.prototype;
  15709. d.prototype = new __();
  15710. };
  15711. var BABYLON;
  15712. (function (BABYLON) {
  15713. var VideoTexture = (function (_super) {
  15714. __extends(VideoTexture, _super);
  15715. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  15716. var _this = this;
  15717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15718. _super.call(this, null, scene, !generateMipMaps, invertY);
  15719. this._autoLaunch = true;
  15720. this.name = name;
  15721. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15722. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15723. var requiredWidth = size.width || size;
  15724. var requiredHeight = size.height || size;
  15725. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  15726. var textureSize = this.getSize();
  15727. this.video = document.createElement("video");
  15728. this.video.width = textureSize.width;
  15729. this.video.height = textureSize.height;
  15730. this.video.autoplay = false;
  15731. this.video.loop = true;
  15732. this.video.addEventListener("canplaythrough", function () {
  15733. if (_this._texture) {
  15734. _this._texture.isReady = true;
  15735. }
  15736. });
  15737. urls.forEach(function (url) {
  15738. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  15739. var source = document.createElement("source");
  15740. source.src = url;
  15741. _this.video.appendChild(source);
  15742. });
  15743. this._lastUpdate = BABYLON.Tools.Now;
  15744. }
  15745. VideoTexture.prototype.update = function () {
  15746. if (this._autoLaunch) {
  15747. this._autoLaunch = false;
  15748. this.video.play();
  15749. }
  15750. var now = BABYLON.Tools.Now;
  15751. if (now - this._lastUpdate < 15) {
  15752. return false;
  15753. }
  15754. this._lastUpdate = now;
  15755. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  15756. return true;
  15757. };
  15758. return VideoTexture;
  15759. })(BABYLON.Texture);
  15760. BABYLON.VideoTexture = VideoTexture;
  15761. })(BABYLON || (BABYLON = {}));
  15762. //# sourceMappingURL=babylon.videoTexture.js.map
  15763. var __extends = this.__extends || function (d, b) {
  15764. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15765. function __() { this.constructor = d; }
  15766. __.prototype = b.prototype;
  15767. d.prototype = new __();
  15768. };
  15769. var BABYLON;
  15770. (function (BABYLON) {
  15771. var CustomProceduralTexture = (function (_super) {
  15772. __extends(CustomProceduralTexture, _super);
  15773. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  15774. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  15775. this._animate = true;
  15776. this._time = 0;
  15777. this._texturePath = texturePath;
  15778. //Try to load json
  15779. this.loadJson(texturePath);
  15780. this.refreshRate = 1;
  15781. }
  15782. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  15783. var _this = this;
  15784. var that = this;
  15785. function noConfigFile() {
  15786. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  15787. try {
  15788. that.setFragment(that._texturePath);
  15789. }
  15790. catch (ex) {
  15791. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  15792. }
  15793. }
  15794. var configFileUrl = jsonUrl + "/config.json";
  15795. var xhr = new XMLHttpRequest();
  15796. xhr.open("GET", configFileUrl, true);
  15797. xhr.addEventListener("load", function () {
  15798. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15799. try {
  15800. _this._config = JSON.parse(xhr.response);
  15801. _this.updateShaderUniforms();
  15802. _this.updateTextures();
  15803. _this.setFragment(_this._texturePath + "/custom");
  15804. _this._animate = _this._config.animate;
  15805. _this.refreshRate = _this._config.refreshrate;
  15806. }
  15807. catch (ex) {
  15808. noConfigFile();
  15809. }
  15810. }
  15811. else {
  15812. noConfigFile();
  15813. }
  15814. }, false);
  15815. xhr.addEventListener("error", function () {
  15816. noConfigFile();
  15817. }, false);
  15818. try {
  15819. xhr.send();
  15820. }
  15821. catch (ex) {
  15822. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  15823. }
  15824. };
  15825. CustomProceduralTexture.prototype.isReady = function () {
  15826. if (!_super.prototype.isReady.call(this)) {
  15827. return false;
  15828. }
  15829. for (var name in this._textures) {
  15830. var texture = this._textures[name];
  15831. if (!texture.isReady()) {
  15832. return false;
  15833. }
  15834. }
  15835. return true;
  15836. };
  15837. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15838. if (this._animate) {
  15839. this._time += this.getScene().getAnimationRatio() * 0.03;
  15840. this.updateShaderUniforms();
  15841. }
  15842. _super.prototype.render.call(this, useCameraPostProcess);
  15843. };
  15844. CustomProceduralTexture.prototype.updateTextures = function () {
  15845. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  15846. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  15847. }
  15848. };
  15849. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  15850. if (this._config) {
  15851. for (var j = 0; j < this._config.uniforms.length; j++) {
  15852. var uniform = this._config.uniforms[j];
  15853. switch (uniform.type) {
  15854. case "float":
  15855. this.setFloat(uniform.name, uniform.value);
  15856. break;
  15857. case "color3":
  15858. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  15859. break;
  15860. case "color4":
  15861. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  15862. break;
  15863. case "vector2":
  15864. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  15865. break;
  15866. case "vector3":
  15867. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  15868. break;
  15869. }
  15870. }
  15871. }
  15872. this.setFloat("time", this._time);
  15873. };
  15874. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  15875. get: function () {
  15876. return this._animate;
  15877. },
  15878. set: function (value) {
  15879. this._animate = value;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. return CustomProceduralTexture;
  15885. })(BABYLON.ProceduralTexture);
  15886. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  15887. })(BABYLON || (BABYLON = {}));
  15888. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  15889. var __extends = this.__extends || function (d, b) {
  15890. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15891. function __() { this.constructor = d; }
  15892. __.prototype = b.prototype;
  15893. d.prototype = new __();
  15894. };
  15895. var BABYLON;
  15896. (function (BABYLON) {
  15897. var WoodProceduralTexture = (function (_super) {
  15898. __extends(WoodProceduralTexture, _super);
  15899. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15900. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  15901. this._ampScale = 100.0;
  15902. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  15903. this.updateShaderUniforms();
  15904. this.refreshRate = 0;
  15905. }
  15906. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  15907. this.setFloat("ampScale", this._ampScale);
  15908. this.setColor3("woodColor", this._woodColor);
  15909. };
  15910. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  15911. get: function () {
  15912. return this._ampScale;
  15913. },
  15914. set: function (value) {
  15915. this._ampScale = value;
  15916. this.updateShaderUniforms();
  15917. },
  15918. enumerable: true,
  15919. configurable: true
  15920. });
  15921. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  15922. get: function () {
  15923. return this._woodColor;
  15924. },
  15925. set: function (value) {
  15926. this._woodColor = value;
  15927. this.updateShaderUniforms();
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. return WoodProceduralTexture;
  15933. })(BABYLON.ProceduralTexture);
  15934. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  15935. var FireProceduralTexture = (function (_super) {
  15936. __extends(FireProceduralTexture, _super);
  15937. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15938. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  15939. this._time = 0.0;
  15940. this._speed = new BABYLON.Vector2(0.5, 0.3);
  15941. this._autoGenerateTime = true;
  15942. this._alphaThreshold = 0.5;
  15943. this._fireColors = FireProceduralTexture.RedFireColors;
  15944. this.updateShaderUniforms();
  15945. this.refreshRate = 1;
  15946. }
  15947. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  15948. this.setFloat("time", this._time);
  15949. this.setVector2("speed", this._speed);
  15950. this.setColor3("c1", this._fireColors[0]);
  15951. this.setColor3("c2", this._fireColors[1]);
  15952. this.setColor3("c3", this._fireColors[2]);
  15953. this.setColor3("c4", this._fireColors[3]);
  15954. this.setColor3("c5", this._fireColors[4]);
  15955. this.setColor3("c6", this._fireColors[5]);
  15956. this.setFloat("alphaThreshold", this._alphaThreshold);
  15957. };
  15958. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15959. if (this._autoGenerateTime) {
  15960. this._time += this.getScene().getAnimationRatio() * 0.03;
  15961. this.updateShaderUniforms();
  15962. }
  15963. _super.prototype.render.call(this, useCameraPostProcess);
  15964. };
  15965. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  15966. get: function () {
  15967. return [
  15968. new BABYLON.Color3(0.5, 0.0, 1.0),
  15969. new BABYLON.Color3(0.9, 0.0, 1.0),
  15970. new BABYLON.Color3(0.2, 0.0, 1.0),
  15971. new BABYLON.Color3(1.0, 0.9, 1.0),
  15972. new BABYLON.Color3(0.1, 0.1, 1.0),
  15973. new BABYLON.Color3(0.9, 0.9, 1.0)
  15974. ];
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  15980. get: function () {
  15981. return [
  15982. new BABYLON.Color3(0.5, 1.0, 0.0),
  15983. new BABYLON.Color3(0.5, 1.0, 0.0),
  15984. new BABYLON.Color3(0.3, 0.4, 0.0),
  15985. new BABYLON.Color3(0.5, 1.0, 0.0),
  15986. new BABYLON.Color3(0.2, 0.0, 0.0),
  15987. new BABYLON.Color3(0.5, 1.0, 0.0)
  15988. ];
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  15994. get: function () {
  15995. return [
  15996. new BABYLON.Color3(0.5, 0.0, 0.1),
  15997. new BABYLON.Color3(0.9, 0.0, 0.0),
  15998. new BABYLON.Color3(0.2, 0.0, 0.0),
  15999. new BABYLON.Color3(1.0, 0.9, 0.0),
  16000. new BABYLON.Color3(0.1, 0.1, 0.1),
  16001. new BABYLON.Color3(0.9, 0.9, 0.9)
  16002. ];
  16003. },
  16004. enumerable: true,
  16005. configurable: true
  16006. });
  16007. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  16008. get: function () {
  16009. return [
  16010. new BABYLON.Color3(0.1, 0.0, 0.5),
  16011. new BABYLON.Color3(0.0, 0.0, 0.5),
  16012. new BABYLON.Color3(0.1, 0.0, 0.2),
  16013. new BABYLON.Color3(0.0, 0.0, 1.0),
  16014. new BABYLON.Color3(0.1, 0.2, 0.3),
  16015. new BABYLON.Color3(0.0, 0.2, 0.9)
  16016. ];
  16017. },
  16018. enumerable: true,
  16019. configurable: true
  16020. });
  16021. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16022. get: function () {
  16023. return this._fireColors;
  16024. },
  16025. set: function (value) {
  16026. this._fireColors = value;
  16027. this.updateShaderUniforms();
  16028. },
  16029. enumerable: true,
  16030. configurable: true
  16031. });
  16032. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16033. get: function () {
  16034. return this._time;
  16035. },
  16036. set: function (value) {
  16037. this._time = value;
  16038. this.updateShaderUniforms();
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16044. get: function () {
  16045. return this._speed;
  16046. },
  16047. set: function (value) {
  16048. this._speed = value;
  16049. this.updateShaderUniforms();
  16050. },
  16051. enumerable: true,
  16052. configurable: true
  16053. });
  16054. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16055. get: function () {
  16056. return this._alphaThreshold;
  16057. },
  16058. set: function (value) {
  16059. this._alphaThreshold = value;
  16060. this.updateShaderUniforms();
  16061. },
  16062. enumerable: true,
  16063. configurable: true
  16064. });
  16065. return FireProceduralTexture;
  16066. })(BABYLON.ProceduralTexture);
  16067. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16068. var CloudProceduralTexture = (function (_super) {
  16069. __extends(CloudProceduralTexture, _super);
  16070. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16071. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16072. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16073. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16074. this.updateShaderUniforms();
  16075. this.refreshRate = 0;
  16076. }
  16077. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16078. this.setColor3("skyColor", this._skyColor);
  16079. this.setColor3("cloudColor", this._cloudColor);
  16080. };
  16081. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16082. get: function () {
  16083. return this._skyColor;
  16084. },
  16085. set: function (value) {
  16086. this._skyColor = value;
  16087. this.updateShaderUniforms();
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16093. get: function () {
  16094. return this._cloudColor;
  16095. },
  16096. set: function (value) {
  16097. this._cloudColor = value;
  16098. this.updateShaderUniforms();
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. return CloudProceduralTexture;
  16104. })(BABYLON.ProceduralTexture);
  16105. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16106. var GrassProceduralTexture = (function (_super) {
  16107. __extends(GrassProceduralTexture, _super);
  16108. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16109. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16110. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16111. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16112. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16113. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16114. this._grassColors = [
  16115. new BABYLON.Color3(0.29, 0.38, 0.02),
  16116. new BABYLON.Color3(0.36, 0.49, 0.09),
  16117. new BABYLON.Color3(0.51, 0.6, 0.28)
  16118. ];
  16119. this.updateShaderUniforms();
  16120. this.refreshRate = 0;
  16121. }
  16122. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16123. this.setColor3("herb1Color", this._grassColors[0]);
  16124. this.setColor3("herb2Color", this._grassColors[1]);
  16125. this.setColor3("herb3Color", this._grassColors[2]);
  16126. this.setColor3("groundColor", this._groundColor);
  16127. };
  16128. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16129. get: function () {
  16130. return this._grassColors;
  16131. },
  16132. set: function (value) {
  16133. this._grassColors = value;
  16134. this.updateShaderUniforms();
  16135. },
  16136. enumerable: true,
  16137. configurable: true
  16138. });
  16139. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16140. get: function () {
  16141. return this._groundColor;
  16142. },
  16143. set: function (value) {
  16144. this.groundColor = value;
  16145. this.updateShaderUniforms();
  16146. },
  16147. enumerable: true,
  16148. configurable: true
  16149. });
  16150. return GrassProceduralTexture;
  16151. })(BABYLON.ProceduralTexture);
  16152. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16153. var RoadProceduralTexture = (function (_super) {
  16154. __extends(RoadProceduralTexture, _super);
  16155. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16156. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16157. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16158. this.updateShaderUniforms();
  16159. this.refreshRate = 0;
  16160. }
  16161. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16162. this.setColor3("roadColor", this._roadColor);
  16163. };
  16164. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16165. get: function () {
  16166. return this._roadColor;
  16167. },
  16168. set: function (value) {
  16169. this._roadColor = value;
  16170. this.updateShaderUniforms();
  16171. },
  16172. enumerable: true,
  16173. configurable: true
  16174. });
  16175. return RoadProceduralTexture;
  16176. })(BABYLON.ProceduralTexture);
  16177. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16178. var BrickProceduralTexture = (function (_super) {
  16179. __extends(BrickProceduralTexture, _super);
  16180. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16181. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16182. this._numberOfBricksHeight = 15;
  16183. this._numberOfBricksWidth = 5;
  16184. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16185. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16186. this.updateShaderUniforms();
  16187. this.refreshRate = 0;
  16188. }
  16189. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16190. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16191. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16192. this.setColor3("brickColor", this._brickColor);
  16193. this.setColor3("jointColor", this._jointColor);
  16194. };
  16195. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16196. get: function () {
  16197. return this._numberOfBricksHeight;
  16198. },
  16199. set: function (value) {
  16200. this._numberOfBricksHeight = value;
  16201. this.updateShaderUniforms();
  16202. },
  16203. enumerable: true,
  16204. configurable: true
  16205. });
  16206. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16207. get: function () {
  16208. return this._numberOfBricksWidth;
  16209. },
  16210. set: function (value) {
  16211. this._numberOfBricksHeight = value;
  16212. this.updateShaderUniforms();
  16213. },
  16214. enumerable: true,
  16215. configurable: true
  16216. });
  16217. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16218. get: function () {
  16219. return this._jointColor;
  16220. },
  16221. set: function (value) {
  16222. this._jointColor = value;
  16223. this.updateShaderUniforms();
  16224. },
  16225. enumerable: true,
  16226. configurable: true
  16227. });
  16228. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16229. get: function () {
  16230. return this._brickColor;
  16231. },
  16232. set: function (value) {
  16233. this._brickColor = value;
  16234. this.updateShaderUniforms();
  16235. },
  16236. enumerable: true,
  16237. configurable: true
  16238. });
  16239. return BrickProceduralTexture;
  16240. })(BABYLON.ProceduralTexture);
  16241. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16242. var MarbleProceduralTexture = (function (_super) {
  16243. __extends(MarbleProceduralTexture, _super);
  16244. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16245. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16246. this._numberOfTilesHeight = 3;
  16247. this._numberOfTilesWidth = 3;
  16248. this._amplitude = 9.0;
  16249. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16250. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16251. this.updateShaderUniforms();
  16252. this.refreshRate = 0;
  16253. }
  16254. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16255. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16256. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16257. this.setFloat("amplitude", this._amplitude);
  16258. this.setColor3("marbleColor", this._marbleColor);
  16259. this.setColor3("jointColor", this._jointColor);
  16260. };
  16261. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16262. get: function () {
  16263. return this._numberOfTilesHeight;
  16264. },
  16265. set: function (value) {
  16266. this._numberOfTilesHeight = value;
  16267. this.updateShaderUniforms();
  16268. },
  16269. enumerable: true,
  16270. configurable: true
  16271. });
  16272. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16273. get: function () {
  16274. return this._numberOfTilesWidth;
  16275. },
  16276. set: function (value) {
  16277. this._numberOfTilesWidth = value;
  16278. this.updateShaderUniforms();
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16284. get: function () {
  16285. return this._jointColor;
  16286. },
  16287. set: function (value) {
  16288. this._jointColor = value;
  16289. this.updateShaderUniforms();
  16290. },
  16291. enumerable: true,
  16292. configurable: true
  16293. });
  16294. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16295. get: function () {
  16296. return this._marbleColor;
  16297. },
  16298. set: function (value) {
  16299. this._marbleColor = value;
  16300. this.updateShaderUniforms();
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. return MarbleProceduralTexture;
  16306. })(BABYLON.ProceduralTexture);
  16307. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var EffectFallbacks = (function () {
  16313. function EffectFallbacks() {
  16314. this._defines = {};
  16315. this._currentRank = 32;
  16316. this._maxRank = -1;
  16317. }
  16318. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16319. if (!this._defines[rank]) {
  16320. if (rank < this._currentRank) {
  16321. this._currentRank = rank;
  16322. }
  16323. if (rank > this._maxRank) {
  16324. this._maxRank = rank;
  16325. }
  16326. this._defines[rank] = new Array();
  16327. }
  16328. this._defines[rank].push(define);
  16329. };
  16330. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16331. get: function () {
  16332. return this._currentRank <= this._maxRank;
  16333. },
  16334. enumerable: true,
  16335. configurable: true
  16336. });
  16337. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16338. var currentFallbacks = this._defines[this._currentRank];
  16339. for (var index = 0; index < currentFallbacks.length; index++) {
  16340. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16341. }
  16342. this._currentRank++;
  16343. return currentDefines;
  16344. };
  16345. return EffectFallbacks;
  16346. })();
  16347. BABYLON.EffectFallbacks = EffectFallbacks;
  16348. var Effect = (function () {
  16349. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16350. var _this = this;
  16351. this._isReady = false;
  16352. this._compilationError = "";
  16353. this._valueCache = [];
  16354. this._engine = engine;
  16355. this.name = baseName;
  16356. this.defines = defines;
  16357. this._uniformsNames = uniformsNames.concat(samplers);
  16358. this._samplers = samplers;
  16359. this._attributesNames = attributesNames;
  16360. this.onError = onError;
  16361. this.onCompiled = onCompiled;
  16362. var vertexSource;
  16363. var fragmentSource;
  16364. if (baseName.vertexElement) {
  16365. vertexSource = document.getElementById(baseName.vertexElement);
  16366. if (!vertexSource) {
  16367. vertexSource = baseName.vertexElement;
  16368. }
  16369. }
  16370. else {
  16371. vertexSource = baseName.vertex || baseName;
  16372. }
  16373. if (baseName.fragmentElement) {
  16374. fragmentSource = document.getElementById(baseName.fragmentElement);
  16375. if (!fragmentSource) {
  16376. fragmentSource = baseName.fragmentElement;
  16377. }
  16378. }
  16379. else {
  16380. fragmentSource = baseName.fragment || baseName;
  16381. }
  16382. this._loadVertexShader(vertexSource, function (vertexCode) {
  16383. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16384. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16385. });
  16386. });
  16387. }
  16388. // Properties
  16389. Effect.prototype.isReady = function () {
  16390. return this._isReady;
  16391. };
  16392. Effect.prototype.getProgram = function () {
  16393. return this._program;
  16394. };
  16395. Effect.prototype.getAttributesNames = function () {
  16396. return this._attributesNames;
  16397. };
  16398. Effect.prototype.getAttributeLocation = function (index) {
  16399. return this._attributes[index];
  16400. };
  16401. Effect.prototype.getAttributeLocationByName = function (name) {
  16402. var index = this._attributesNames.indexOf(name);
  16403. return this._attributes[index];
  16404. };
  16405. Effect.prototype.getAttributesCount = function () {
  16406. return this._attributes.length;
  16407. };
  16408. Effect.prototype.getUniformIndex = function (uniformName) {
  16409. return this._uniformsNames.indexOf(uniformName);
  16410. };
  16411. Effect.prototype.getUniform = function (uniformName) {
  16412. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16413. };
  16414. Effect.prototype.getSamplers = function () {
  16415. return this._samplers;
  16416. };
  16417. Effect.prototype.getCompilationError = function () {
  16418. return this._compilationError;
  16419. };
  16420. // Methods
  16421. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16422. // DOM element ?
  16423. if (vertex instanceof HTMLElement) {
  16424. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16425. callback(vertexCode);
  16426. return;
  16427. }
  16428. // Is in local store ?
  16429. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16430. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16431. return;
  16432. }
  16433. var vertexShaderUrl;
  16434. if (vertex[0] === ".") {
  16435. vertexShaderUrl = vertex;
  16436. }
  16437. else {
  16438. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16439. }
  16440. // Vertex shader
  16441. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16442. };
  16443. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16444. // DOM element ?
  16445. if (fragment instanceof HTMLElement) {
  16446. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16447. callback(fragmentCode);
  16448. return;
  16449. }
  16450. // Is in local store ?
  16451. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16452. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16453. return;
  16454. }
  16455. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16456. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16457. return;
  16458. }
  16459. var fragmentShaderUrl;
  16460. if (fragment[0] === ".") {
  16461. fragmentShaderUrl = fragment;
  16462. }
  16463. else {
  16464. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16465. }
  16466. // Fragment shader
  16467. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16468. };
  16469. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16470. try {
  16471. var engine = this._engine;
  16472. if (!engine.getCaps().highPrecisionShaderSupported) {
  16473. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16474. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16475. }
  16476. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16477. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16478. this._attributes = engine.getAttributes(this._program, attributesNames);
  16479. for (var index = 0; index < this._samplers.length; index++) {
  16480. var sampler = this.getUniform(this._samplers[index]);
  16481. if (sampler == null) {
  16482. this._samplers.splice(index, 1);
  16483. index--;
  16484. }
  16485. }
  16486. engine.bindSamplers(this);
  16487. this._isReady = true;
  16488. if (this.onCompiled) {
  16489. this.onCompiled(this);
  16490. }
  16491. }
  16492. catch (e) {
  16493. // Is it a problem with precision?
  16494. if (e.message.indexOf("highp") !== -1) {
  16495. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16496. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16497. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16498. return;
  16499. }
  16500. // Let's go through fallbacks then
  16501. if (fallbacks && fallbacks.isMoreFallbacks) {
  16502. defines = fallbacks.reduce(defines);
  16503. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16504. }
  16505. else {
  16506. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16507. BABYLON.Tools.Error("Defines: " + defines);
  16508. BABYLON.Tools.Error("Error: " + e.message);
  16509. this._compilationError = e.message;
  16510. if (this.onError) {
  16511. this.onError(this, this._compilationError);
  16512. }
  16513. }
  16514. }
  16515. };
  16516. Effect.prototype._bindTexture = function (channel, texture) {
  16517. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16518. };
  16519. Effect.prototype.setTexture = function (channel, texture) {
  16520. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16521. };
  16522. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16523. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16524. };
  16525. //public _cacheMatrix(uniformName, matrix) {
  16526. // if (!this._valueCache[uniformName]) {
  16527. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16528. // }
  16529. // for (var index = 0; index < 16; index++) {
  16530. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16531. // }
  16532. //};
  16533. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16534. if (!this._valueCache[uniformName]) {
  16535. this._valueCache[uniformName] = [x, y];
  16536. return;
  16537. }
  16538. this._valueCache[uniformName][0] = x;
  16539. this._valueCache[uniformName][1] = y;
  16540. };
  16541. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16542. if (!this._valueCache[uniformName]) {
  16543. this._valueCache[uniformName] = [x, y, z];
  16544. return;
  16545. }
  16546. this._valueCache[uniformName][0] = x;
  16547. this._valueCache[uniformName][1] = y;
  16548. this._valueCache[uniformName][2] = z;
  16549. };
  16550. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16551. if (!this._valueCache[uniformName]) {
  16552. this._valueCache[uniformName] = [x, y, z, w];
  16553. return;
  16554. }
  16555. this._valueCache[uniformName][0] = x;
  16556. this._valueCache[uniformName][1] = y;
  16557. this._valueCache[uniformName][2] = z;
  16558. this._valueCache[uniformName][3] = w;
  16559. };
  16560. Effect.prototype.setArray = function (uniformName, array) {
  16561. this._engine.setArray(this.getUniform(uniformName), array);
  16562. return this;
  16563. };
  16564. Effect.prototype.setArray2 = function (uniformName, array) {
  16565. this._engine.setArray2(this.getUniform(uniformName), array);
  16566. return this;
  16567. };
  16568. Effect.prototype.setArray3 = function (uniformName, array) {
  16569. this._engine.setArray3(this.getUniform(uniformName), array);
  16570. return this;
  16571. };
  16572. Effect.prototype.setArray4 = function (uniformName, array) {
  16573. this._engine.setArray4(this.getUniform(uniformName), array);
  16574. return this;
  16575. };
  16576. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16577. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16578. return this;
  16579. };
  16580. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16581. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16582. // return;
  16583. //this._cacheMatrix(uniformName, matrix);
  16584. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16585. return this;
  16586. };
  16587. Effect.prototype.setFloat = function (uniformName, value) {
  16588. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16589. return this;
  16590. this._valueCache[uniformName] = value;
  16591. this._engine.setFloat(this.getUniform(uniformName), value);
  16592. return this;
  16593. };
  16594. Effect.prototype.setBool = function (uniformName, bool) {
  16595. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16596. return this;
  16597. this._valueCache[uniformName] = bool;
  16598. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16599. return this;
  16600. };
  16601. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16602. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  16603. return this;
  16604. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  16605. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  16606. return this;
  16607. };
  16608. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  16609. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  16610. return this;
  16611. this._cacheFloat2(uniformName, x, y);
  16612. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  16613. return this;
  16614. };
  16615. Effect.prototype.setVector3 = function (uniformName, vector3) {
  16616. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  16617. return this;
  16618. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  16619. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  16620. return this;
  16621. };
  16622. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  16623. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  16624. return this;
  16625. this._cacheFloat3(uniformName, x, y, z);
  16626. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  16627. return this;
  16628. };
  16629. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  16630. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  16631. return this;
  16632. this._cacheFloat4(uniformName, x, y, z, w);
  16633. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  16634. return this;
  16635. };
  16636. Effect.prototype.setColor3 = function (uniformName, color3) {
  16637. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  16638. return this;
  16639. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  16640. this._engine.setColor3(this.getUniform(uniformName), color3);
  16641. return this;
  16642. };
  16643. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  16644. 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)
  16645. return this;
  16646. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  16647. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  16648. return this;
  16649. };
  16650. // Statics
  16651. Effect.ShadersStore = {};
  16652. return Effect;
  16653. })();
  16654. BABYLON.Effect = Effect;
  16655. })(BABYLON || (BABYLON = {}));
  16656. //# sourceMappingURL=babylon.effect.js.map
  16657. var BABYLON;
  16658. (function (BABYLON) {
  16659. var Material = (function () {
  16660. function Material(name, scene, doNotAdd) {
  16661. this.name = name;
  16662. this.checkReadyOnEveryCall = true;
  16663. this.checkReadyOnlyOnce = false;
  16664. this.state = "";
  16665. this.alpha = 1.0;
  16666. this.backFaceCulling = true;
  16667. this._wasPreviouslyReady = false;
  16668. this._fillMode = Material.TriangleFillMode;
  16669. this.pointSize = 1.0;
  16670. this.zOffset = 0;
  16671. this.id = name;
  16672. this._scene = scene;
  16673. if (!doNotAdd) {
  16674. scene.materials.push(this);
  16675. }
  16676. }
  16677. Object.defineProperty(Material, "TriangleFillMode", {
  16678. get: function () {
  16679. return Material._TriangleFillMode;
  16680. },
  16681. enumerable: true,
  16682. configurable: true
  16683. });
  16684. Object.defineProperty(Material, "WireFrameFillMode", {
  16685. get: function () {
  16686. return Material._WireFrameFillMode;
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. Object.defineProperty(Material, "PointFillMode", {
  16692. get: function () {
  16693. return Material._PointFillMode;
  16694. },
  16695. enumerable: true,
  16696. configurable: true
  16697. });
  16698. Object.defineProperty(Material.prototype, "wireframe", {
  16699. get: function () {
  16700. return this._fillMode === Material.WireFrameFillMode;
  16701. },
  16702. set: function (value) {
  16703. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  16704. },
  16705. enumerable: true,
  16706. configurable: true
  16707. });
  16708. Object.defineProperty(Material.prototype, "pointsCloud", {
  16709. get: function () {
  16710. return this._fillMode === Material.PointFillMode;
  16711. },
  16712. set: function (value) {
  16713. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. Object.defineProperty(Material.prototype, "fillMode", {
  16719. get: function () {
  16720. return this._fillMode;
  16721. },
  16722. set: function (value) {
  16723. this._fillMode = value;
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. Material.prototype.isReady = function (mesh, useInstances) {
  16729. return true;
  16730. };
  16731. Material.prototype.getEffect = function () {
  16732. return this._effect;
  16733. };
  16734. Material.prototype.getScene = function () {
  16735. return this._scene;
  16736. };
  16737. Material.prototype.needAlphaBlending = function () {
  16738. return (this.alpha < 1.0);
  16739. };
  16740. Material.prototype.needAlphaTesting = function () {
  16741. return false;
  16742. };
  16743. Material.prototype.getAlphaTestTexture = function () {
  16744. return null;
  16745. };
  16746. Material.prototype.trackCreation = function (onCompiled, onError) {
  16747. };
  16748. Material.prototype._preBind = function () {
  16749. var engine = this._scene.getEngine();
  16750. engine.enableEffect(this._effect);
  16751. engine.setState(this.backFaceCulling, this.zOffset);
  16752. };
  16753. Material.prototype.bind = function (world, mesh) {
  16754. this._scene._cachedMaterial = this;
  16755. if (this.onBind) {
  16756. this.onBind(this, mesh);
  16757. }
  16758. };
  16759. Material.prototype.bindOnlyWorldMatrix = function (world) {
  16760. };
  16761. Material.prototype.unbind = function () {
  16762. };
  16763. Material.prototype.dispose = function (forceDisposeEffect) {
  16764. // Remove from scene
  16765. var index = this._scene.materials.indexOf(this);
  16766. this._scene.materials.splice(index, 1);
  16767. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  16768. if (forceDisposeEffect && this._effect) {
  16769. this._scene.getEngine()._releaseEffect(this._effect);
  16770. this._effect = null;
  16771. }
  16772. // Callback
  16773. if (this.onDispose) {
  16774. this.onDispose();
  16775. }
  16776. };
  16777. Material._TriangleFillMode = 0;
  16778. Material._WireFrameFillMode = 1;
  16779. Material._PointFillMode = 2;
  16780. return Material;
  16781. })();
  16782. BABYLON.Material = Material;
  16783. })(BABYLON || (BABYLON = {}));
  16784. //# sourceMappingURL=babylon.material.js.map
  16785. var __extends = this.__extends || function (d, b) {
  16786. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16787. function __() { this.constructor = d; }
  16788. __.prototype = b.prototype;
  16789. d.prototype = new __();
  16790. };
  16791. var BABYLON;
  16792. (function (BABYLON) {
  16793. var maxSimultaneousLights = 4;
  16794. var FresnelParameters = (function () {
  16795. function FresnelParameters() {
  16796. this.isEnabled = true;
  16797. this.leftColor = BABYLON.Color3.White();
  16798. this.rightColor = BABYLON.Color3.Black();
  16799. this.bias = 0;
  16800. this.power = 1;
  16801. }
  16802. return FresnelParameters;
  16803. })();
  16804. BABYLON.FresnelParameters = FresnelParameters;
  16805. var StandardMaterial = (function (_super) {
  16806. __extends(StandardMaterial, _super);
  16807. function StandardMaterial(name, scene) {
  16808. var _this = this;
  16809. _super.call(this, name, scene);
  16810. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16811. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  16812. this.specularColor = new BABYLON.Color3(1, 1, 1);
  16813. this.specularPower = 64;
  16814. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  16815. this.useAlphaFromDiffuseTexture = false;
  16816. this.useSpecularOverAlpha = true;
  16817. this.fogEnabled = true;
  16818. this._cachedDefines = null;
  16819. this._renderTargets = new BABYLON.SmartArray(16);
  16820. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  16821. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  16822. this._scaledDiffuse = new BABYLON.Color3();
  16823. this._scaledSpecular = new BABYLON.Color3();
  16824. this.getRenderTargetTextures = function () {
  16825. _this._renderTargets.reset();
  16826. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  16827. _this._renderTargets.push(_this.reflectionTexture);
  16828. }
  16829. return _this._renderTargets;
  16830. };
  16831. }
  16832. StandardMaterial.prototype.needAlphaBlending = function () {
  16833. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  16834. };
  16835. StandardMaterial.prototype.needAlphaTesting = function () {
  16836. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  16837. };
  16838. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  16839. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  16840. };
  16841. StandardMaterial.prototype.getAlphaTestTexture = function () {
  16842. return this.diffuseTexture;
  16843. };
  16844. // Methods
  16845. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  16846. if (this.checkReadyOnlyOnce) {
  16847. if (this._wasPreviouslyReady) {
  16848. return true;
  16849. }
  16850. }
  16851. var scene = this.getScene();
  16852. if (!this.checkReadyOnEveryCall) {
  16853. if (this._renderId === scene.getRenderId()) {
  16854. return true;
  16855. }
  16856. }
  16857. var engine = scene.getEngine();
  16858. var defines = [];
  16859. var fallbacks = new BABYLON.EffectFallbacks();
  16860. var needNormals = false;
  16861. var needUVs = false;
  16862. // Textures
  16863. if (scene.texturesEnabled) {
  16864. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  16865. if (!this.diffuseTexture.isReady()) {
  16866. return false;
  16867. }
  16868. else {
  16869. needUVs = true;
  16870. defines.push("#define DIFFUSE");
  16871. }
  16872. }
  16873. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  16874. if (!this.ambientTexture.isReady()) {
  16875. return false;
  16876. }
  16877. else {
  16878. needUVs = true;
  16879. defines.push("#define AMBIENT");
  16880. }
  16881. }
  16882. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  16883. if (!this.opacityTexture.isReady()) {
  16884. return false;
  16885. }
  16886. else {
  16887. needUVs = true;
  16888. defines.push("#define OPACITY");
  16889. if (this.opacityTexture.getAlphaFromRGB) {
  16890. defines.push("#define OPACITYRGB");
  16891. }
  16892. }
  16893. }
  16894. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  16895. if (!this.reflectionTexture.isReady()) {
  16896. return false;
  16897. }
  16898. else {
  16899. needNormals = true;
  16900. needUVs = true;
  16901. defines.push("#define REFLECTION");
  16902. fallbacks.addFallback(0, "REFLECTION");
  16903. }
  16904. }
  16905. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  16906. if (!this.emissiveTexture.isReady()) {
  16907. return false;
  16908. }
  16909. else {
  16910. needUVs = true;
  16911. defines.push("#define EMISSIVE");
  16912. }
  16913. }
  16914. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  16915. if (!this.specularTexture.isReady()) {
  16916. return false;
  16917. }
  16918. else {
  16919. needUVs = true;
  16920. defines.push("#define SPECULAR");
  16921. fallbacks.addFallback(0, "SPECULAR");
  16922. }
  16923. }
  16924. }
  16925. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  16926. if (!this.bumpTexture.isReady()) {
  16927. return false;
  16928. }
  16929. else {
  16930. needUVs = true;
  16931. defines.push("#define BUMP");
  16932. fallbacks.addFallback(0, "BUMP");
  16933. }
  16934. }
  16935. // Effect
  16936. if (this.useSpecularOverAlpha) {
  16937. defines.push("#define SPECULAROVERALPHA");
  16938. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  16939. }
  16940. if (scene.clipPlane) {
  16941. defines.push("#define CLIPPLANE");
  16942. }
  16943. if (engine.getAlphaTesting()) {
  16944. defines.push("#define ALPHATEST");
  16945. }
  16946. if (this._shouldUseAlphaFromDiffuseTexture()) {
  16947. defines.push("#define ALPHAFROMDIFFUSE");
  16948. }
  16949. // Point size
  16950. if (this.pointsCloud || scene.forcePointsCloud) {
  16951. defines.push("#define POINTSIZE");
  16952. }
  16953. // Fog
  16954. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16955. defines.push("#define FOG");
  16956. fallbacks.addFallback(1, "FOG");
  16957. }
  16958. var shadowsActivated = false;
  16959. var lightIndex = 0;
  16960. if (scene.lightsEnabled) {
  16961. for (var index = 0; index < scene.lights.length; index++) {
  16962. var light = scene.lights[index];
  16963. if (!light.isEnabled()) {
  16964. continue;
  16965. }
  16966. // Excluded check
  16967. if (light._excludedMeshesIds.length > 0) {
  16968. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  16969. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  16970. if (excludedMesh) {
  16971. light.excludedMeshes.push(excludedMesh);
  16972. }
  16973. }
  16974. light._excludedMeshesIds = [];
  16975. }
  16976. // Included check
  16977. if (light._includedOnlyMeshesIds.length > 0) {
  16978. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  16979. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  16980. if (includedOnlyMesh) {
  16981. light.includedOnlyMeshes.push(includedOnlyMesh);
  16982. }
  16983. }
  16984. light._includedOnlyMeshesIds = [];
  16985. }
  16986. if (!light.canAffectMesh(mesh)) {
  16987. continue;
  16988. }
  16989. needNormals = true;
  16990. defines.push("#define LIGHT" + lightIndex);
  16991. if (lightIndex > 0) {
  16992. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  16993. }
  16994. var type;
  16995. if (light instanceof BABYLON.SpotLight) {
  16996. type = "#define SPOTLIGHT" + lightIndex;
  16997. }
  16998. else if (light instanceof BABYLON.HemisphericLight) {
  16999. type = "#define HEMILIGHT" + lightIndex;
  17000. }
  17001. else {
  17002. type = "#define POINTDIRLIGHT" + lightIndex;
  17003. }
  17004. defines.push(type);
  17005. if (lightIndex > 0) {
  17006. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  17007. }
  17008. // Shadows
  17009. if (scene.shadowsEnabled) {
  17010. var shadowGenerator = light.getShadowGenerator();
  17011. if (mesh && mesh.receiveShadows && shadowGenerator) {
  17012. defines.push("#define SHADOW" + lightIndex);
  17013. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  17014. if (!shadowsActivated) {
  17015. defines.push("#define SHADOWS");
  17016. shadowsActivated = true;
  17017. }
  17018. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  17019. defines.push("#define SHADOWVSM" + lightIndex);
  17020. if (lightIndex > 0) {
  17021. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  17022. }
  17023. }
  17024. if (shadowGenerator.usePoissonSampling) {
  17025. defines.push("#define SHADOWPCF" + lightIndex);
  17026. if (lightIndex > 0) {
  17027. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17028. }
  17029. }
  17030. }
  17031. }
  17032. lightIndex++;
  17033. if (lightIndex === maxSimultaneousLights)
  17034. break;
  17035. }
  17036. }
  17037. if (StandardMaterial.FresnelEnabled) {
  17038. // Fresnel
  17039. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17040. var fresnelRank = 1;
  17041. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17042. defines.push("#define DIFFUSEFRESNEL");
  17043. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17044. fresnelRank++;
  17045. }
  17046. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17047. defines.push("#define OPACITYFRESNEL");
  17048. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17049. fresnelRank++;
  17050. }
  17051. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17052. defines.push("#define REFLECTIONFRESNEL");
  17053. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17054. fresnelRank++;
  17055. }
  17056. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17057. defines.push("#define EMISSIVEFRESNEL");
  17058. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17059. fresnelRank++;
  17060. }
  17061. needNormals = true;
  17062. defines.push("#define FRESNEL");
  17063. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17064. }
  17065. }
  17066. // Attribs
  17067. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17068. if (mesh) {
  17069. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17070. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17071. defines.push("#define NORMAL");
  17072. }
  17073. if (needUVs) {
  17074. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17075. attribs.push(BABYLON.VertexBuffer.UVKind);
  17076. defines.push("#define UV1");
  17077. }
  17078. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17079. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17080. defines.push("#define UV2");
  17081. }
  17082. }
  17083. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17084. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17085. defines.push("#define VERTEXCOLOR");
  17086. if (mesh.hasVertexAlpha) {
  17087. defines.push("#define VERTEXALPHA");
  17088. }
  17089. }
  17090. if (mesh.useBones) {
  17091. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17092. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17093. defines.push("#define BONES");
  17094. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17095. defines.push("#define BONES4");
  17096. fallbacks.addFallback(0, "BONES4");
  17097. }
  17098. // Instances
  17099. if (useInstances) {
  17100. defines.push("#define INSTANCES");
  17101. attribs.push("world0");
  17102. attribs.push("world1");
  17103. attribs.push("world2");
  17104. attribs.push("world3");
  17105. }
  17106. }
  17107. // Get correct effect
  17108. var join = defines.join("\n");
  17109. if (this._cachedDefines !== join) {
  17110. this._cachedDefines = join;
  17111. scene.resetCachedMaterial();
  17112. // Legacy browser patch
  17113. var shaderName = "default";
  17114. if (!scene.getEngine().getCaps().standardDerivatives) {
  17115. shaderName = "legacydefault";
  17116. }
  17117. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  17118. }
  17119. if (!this._effect.isReady()) {
  17120. return false;
  17121. }
  17122. this._renderId = scene.getRenderId();
  17123. this._wasPreviouslyReady = true;
  17124. return true;
  17125. };
  17126. StandardMaterial.prototype.unbind = function () {
  17127. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17128. this._effect.setTexture("reflection2DSampler", null);
  17129. }
  17130. };
  17131. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17132. this._effect.setMatrix("world", world);
  17133. };
  17134. StandardMaterial.prototype.bind = function (world, mesh) {
  17135. var scene = this.getScene();
  17136. // Matrices
  17137. this.bindOnlyWorldMatrix(world);
  17138. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17139. // Bones
  17140. if (mesh && mesh.useBones) {
  17141. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17142. }
  17143. if (scene.getCachedMaterial() !== this) {
  17144. if (StandardMaterial.FresnelEnabled) {
  17145. // Fresnel
  17146. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17147. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17148. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17149. }
  17150. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17151. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17152. }
  17153. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17154. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17155. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17156. }
  17157. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17158. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17159. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17160. }
  17161. }
  17162. // Textures
  17163. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17164. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17165. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17166. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17167. }
  17168. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17169. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17170. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17171. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17172. }
  17173. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17174. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17175. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17176. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17177. }
  17178. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17179. if (this.reflectionTexture.isCube) {
  17180. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17181. }
  17182. else {
  17183. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17184. }
  17185. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17186. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17187. }
  17188. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17189. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17190. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17191. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17192. }
  17193. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17194. this._effect.setTexture("specularSampler", this.specularTexture);
  17195. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17196. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17197. }
  17198. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17199. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17200. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17201. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17202. }
  17203. // Clip plane
  17204. if (scene.clipPlane) {
  17205. var clipPlane = scene.clipPlane;
  17206. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17207. }
  17208. // Point size
  17209. if (this.pointsCloud) {
  17210. this._effect.setFloat("pointSize", this.pointSize);
  17211. }
  17212. // Colors
  17213. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17214. // Scaling down color according to emissive
  17215. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17216. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17217. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17218. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17219. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17220. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17221. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17222. }
  17223. // Scaling down color according to emissive
  17224. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17225. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17226. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17227. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17228. if (scene.lightsEnabled) {
  17229. var lightIndex = 0;
  17230. for (var index = 0; index < scene.lights.length; index++) {
  17231. var light = scene.lights[index];
  17232. if (!light.isEnabled()) {
  17233. continue;
  17234. }
  17235. if (!light.canAffectMesh(mesh)) {
  17236. continue;
  17237. }
  17238. if (light instanceof BABYLON.PointLight) {
  17239. // Point Light
  17240. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17241. }
  17242. else if (light instanceof BABYLON.DirectionalLight) {
  17243. // Directional Light
  17244. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17245. }
  17246. else if (light instanceof BABYLON.SpotLight) {
  17247. // Spot Light
  17248. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17249. }
  17250. else if (light instanceof BABYLON.HemisphericLight) {
  17251. // Hemispheric Light
  17252. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17253. }
  17254. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17255. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17256. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17257. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17258. // Shadows
  17259. if (scene.shadowsEnabled) {
  17260. var shadowGenerator = light.getShadowGenerator();
  17261. if (mesh.receiveShadows && shadowGenerator) {
  17262. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17263. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17264. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17265. }
  17266. }
  17267. lightIndex++;
  17268. if (lightIndex === maxSimultaneousLights)
  17269. break;
  17270. }
  17271. }
  17272. // View
  17273. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17274. this._effect.setMatrix("view", scene.getViewMatrix());
  17275. }
  17276. // Fog
  17277. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17278. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17279. this._effect.setColor3("vFogColor", scene.fogColor);
  17280. }
  17281. _super.prototype.bind.call(this, world, mesh);
  17282. };
  17283. StandardMaterial.prototype.getAnimatables = function () {
  17284. var results = [];
  17285. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17286. results.push(this.diffuseTexture);
  17287. }
  17288. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17289. results.push(this.ambientTexture);
  17290. }
  17291. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17292. results.push(this.opacityTexture);
  17293. }
  17294. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17295. results.push(this.reflectionTexture);
  17296. }
  17297. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17298. results.push(this.emissiveTexture);
  17299. }
  17300. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17301. results.push(this.specularTexture);
  17302. }
  17303. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17304. results.push(this.bumpTexture);
  17305. }
  17306. return results;
  17307. };
  17308. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17309. if (this.diffuseTexture) {
  17310. this.diffuseTexture.dispose();
  17311. }
  17312. if (this.ambientTexture) {
  17313. this.ambientTexture.dispose();
  17314. }
  17315. if (this.opacityTexture) {
  17316. this.opacityTexture.dispose();
  17317. }
  17318. if (this.reflectionTexture) {
  17319. this.reflectionTexture.dispose();
  17320. }
  17321. if (this.emissiveTexture) {
  17322. this.emissiveTexture.dispose();
  17323. }
  17324. if (this.specularTexture) {
  17325. this.specularTexture.dispose();
  17326. }
  17327. if (this.bumpTexture) {
  17328. this.bumpTexture.dispose();
  17329. }
  17330. _super.prototype.dispose.call(this, forceDisposeEffect);
  17331. };
  17332. StandardMaterial.prototype.clone = function (name) {
  17333. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17334. // Base material
  17335. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17336. newStandardMaterial.alpha = this.alpha;
  17337. newStandardMaterial.fillMode = this.fillMode;
  17338. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17339. // Standard material
  17340. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17341. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17342. }
  17343. if (this.ambientTexture && this.ambientTexture.clone) {
  17344. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17345. }
  17346. if (this.opacityTexture && this.opacityTexture.clone) {
  17347. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17348. }
  17349. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17350. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17351. }
  17352. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17353. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17354. }
  17355. if (this.specularTexture && this.specularTexture.clone) {
  17356. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17357. }
  17358. if (this.bumpTexture && this.bumpTexture.clone) {
  17359. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17360. }
  17361. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17362. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17363. newStandardMaterial.specularColor = this.specularColor.clone();
  17364. newStandardMaterial.specularPower = this.specularPower;
  17365. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17366. return newStandardMaterial;
  17367. };
  17368. // Statics
  17369. // Flags used to enable or disable a type of texture for all Standard Materials
  17370. StandardMaterial.DiffuseTextureEnabled = true;
  17371. StandardMaterial.AmbientTextureEnabled = true;
  17372. StandardMaterial.OpacityTextureEnabled = true;
  17373. StandardMaterial.ReflectionTextureEnabled = true;
  17374. StandardMaterial.EmissiveTextureEnabled = true;
  17375. StandardMaterial.SpecularTextureEnabled = true;
  17376. StandardMaterial.BumpTextureEnabled = true;
  17377. StandardMaterial.FresnelEnabled = true;
  17378. return StandardMaterial;
  17379. })(BABYLON.Material);
  17380. BABYLON.StandardMaterial = StandardMaterial;
  17381. })(BABYLON || (BABYLON = {}));
  17382. //# sourceMappingURL=babylon.standardMaterial.js.map
  17383. var __extends = this.__extends || function (d, b) {
  17384. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17385. function __() { this.constructor = d; }
  17386. __.prototype = b.prototype;
  17387. d.prototype = new __();
  17388. };
  17389. var BABYLON;
  17390. (function (BABYLON) {
  17391. var MultiMaterial = (function (_super) {
  17392. __extends(MultiMaterial, _super);
  17393. function MultiMaterial(name, scene) {
  17394. _super.call(this, name, scene, true);
  17395. this.subMaterials = new Array();
  17396. scene.multiMaterials.push(this);
  17397. }
  17398. // Properties
  17399. MultiMaterial.prototype.getSubMaterial = function (index) {
  17400. if (index < 0 || index >= this.subMaterials.length) {
  17401. return this.getScene().defaultMaterial;
  17402. }
  17403. return this.subMaterials[index];
  17404. };
  17405. // Methods
  17406. MultiMaterial.prototype.isReady = function (mesh) {
  17407. for (var index = 0; index < this.subMaterials.length; index++) {
  17408. var subMaterial = this.subMaterials[index];
  17409. if (subMaterial) {
  17410. if (!this.subMaterials[index].isReady(mesh)) {
  17411. return false;
  17412. }
  17413. }
  17414. }
  17415. return true;
  17416. };
  17417. MultiMaterial.prototype.clone = function (name) {
  17418. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  17419. for (var index = 0; index < this.subMaterials.length; index++) {
  17420. var subMaterial = this.subMaterials[index];
  17421. newMultiMaterial.subMaterials.push(subMaterial);
  17422. }
  17423. return newMultiMaterial;
  17424. };
  17425. return MultiMaterial;
  17426. })(BABYLON.Material);
  17427. BABYLON.MultiMaterial = MultiMaterial;
  17428. })(BABYLON || (BABYLON = {}));
  17429. //# sourceMappingURL=babylon.multiMaterial.js.map
  17430. var BABYLON;
  17431. (function (BABYLON) {
  17432. var SceneLoader = (function () {
  17433. function SceneLoader() {
  17434. }
  17435. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17436. get: function () {
  17437. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17438. },
  17439. set: function (value) {
  17440. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17441. },
  17442. enumerable: true,
  17443. configurable: true
  17444. });
  17445. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17446. get: function () {
  17447. return SceneLoader._ShowLoadingScreen;
  17448. },
  17449. set: function (value) {
  17450. SceneLoader._ShowLoadingScreen = value;
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17456. var dotPosition = sceneFilename.lastIndexOf(".");
  17457. var queryStringPosition = sceneFilename.indexOf("?");
  17458. if (queryStringPosition === -1) {
  17459. queryStringPosition = sceneFilename.length;
  17460. }
  17461. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17462. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17463. var plugin = this._registeredPlugins[index];
  17464. if (plugin.extensions.indexOf(extension) !== -1) {
  17465. return plugin;
  17466. }
  17467. }
  17468. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17469. };
  17470. // Public functions
  17471. SceneLoader.RegisterPlugin = function (plugin) {
  17472. plugin.extensions = plugin.extensions.toLowerCase();
  17473. SceneLoader._registeredPlugins.push(plugin);
  17474. };
  17475. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17476. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17477. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17478. return;
  17479. }
  17480. var manifestChecked = function (success) {
  17481. scene.database = database;
  17482. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17483. var importMeshFromData = function (data) {
  17484. var meshes = [];
  17485. var particleSystems = [];
  17486. var skeletons = [];
  17487. try {
  17488. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17489. if (onerror) {
  17490. onerror(scene, 'unable to load the scene');
  17491. }
  17492. return;
  17493. }
  17494. }
  17495. catch (e) {
  17496. if (onerror) {
  17497. onerror(scene, e);
  17498. }
  17499. return;
  17500. }
  17501. if (onsuccess) {
  17502. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17503. onsuccess(meshes, particleSystems, skeletons);
  17504. }
  17505. };
  17506. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17507. // Direct load
  17508. importMeshFromData(sceneFilename.substr(5));
  17509. return;
  17510. }
  17511. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17512. importMeshFromData(data);
  17513. }, progressCallBack, database);
  17514. };
  17515. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17516. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17517. };
  17518. /**
  17519. * Load a scene
  17520. * @param rootUrl a string that defines the root url for scene and resources
  17521. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17522. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17523. */
  17524. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17525. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17526. };
  17527. /**
  17528. * Append a scene
  17529. * @param rootUrl a string that defines the root url for scene and resources
  17530. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17531. * @param scene is the instance of BABYLON.Scene to append to
  17532. */
  17533. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17534. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17535. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17536. return;
  17537. }
  17538. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17539. var database;
  17540. if (SceneLoader.ShowLoadingScreen) {
  17541. scene.getEngine().displayLoadingUI();
  17542. }
  17543. var loadSceneFromData = function (data) {
  17544. scene.database = database;
  17545. if (!plugin.load(scene, data, rootUrl)) {
  17546. if (onerror) {
  17547. onerror(scene);
  17548. }
  17549. scene.getEngine().hideLoadingUI();
  17550. return;
  17551. }
  17552. if (onsuccess) {
  17553. onsuccess(scene);
  17554. }
  17555. if (SceneLoader.ShowLoadingScreen) {
  17556. scene.executeWhenReady(function () {
  17557. scene.getEngine().hideLoadingUI();
  17558. });
  17559. }
  17560. };
  17561. var manifestChecked = function (success) {
  17562. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17563. };
  17564. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17565. // Direct load
  17566. loadSceneFromData(sceneFilename.substr(5));
  17567. return;
  17568. }
  17569. if (rootUrl.indexOf("file:") === -1) {
  17570. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17571. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17572. }
  17573. else {
  17574. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17575. }
  17576. };
  17577. // Flags
  17578. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17579. SceneLoader._ShowLoadingScreen = true;
  17580. // Members
  17581. SceneLoader._registeredPlugins = new Array();
  17582. return SceneLoader;
  17583. })();
  17584. BABYLON.SceneLoader = SceneLoader;
  17585. ;
  17586. })(BABYLON || (BABYLON = {}));
  17587. //# sourceMappingURL=babylon.sceneLoader.js.map
  17588. var BABYLON;
  17589. (function (BABYLON) {
  17590. var Internals;
  17591. (function (Internals) {
  17592. var checkColors4 = function (colors, count) {
  17593. // Check if color3 was used
  17594. if (colors.length === count * 3) {
  17595. var colors4 = [];
  17596. for (var index = 0; index < colors.length; index += 3) {
  17597. var newIndex = (index / 3) * 4;
  17598. colors4[newIndex] = colors[index];
  17599. colors4[newIndex + 1] = colors[index + 1];
  17600. colors4[newIndex + 2] = colors[index + 2];
  17601. colors4[newIndex + 3] = 1.0;
  17602. }
  17603. return colors4;
  17604. }
  17605. return colors;
  17606. };
  17607. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17608. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17609. texture.name = parsedTexture.name;
  17610. texture.hasAlpha = parsedTexture.hasAlpha;
  17611. texture.level = parsedTexture.level;
  17612. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17613. return texture;
  17614. };
  17615. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17616. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17617. return null;
  17618. }
  17619. if (parsedTexture.isCube) {
  17620. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17621. }
  17622. var texture;
  17623. if (parsedTexture.mirrorPlane) {
  17624. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17625. texture._waitingRenderList = parsedTexture.renderList;
  17626. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17627. }
  17628. else if (parsedTexture.isRenderTarget) {
  17629. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17630. texture._waitingRenderList = parsedTexture.renderList;
  17631. }
  17632. else {
  17633. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17634. }
  17635. texture.name = parsedTexture.name;
  17636. texture.hasAlpha = parsedTexture.hasAlpha;
  17637. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17638. texture.level = parsedTexture.level;
  17639. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17640. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17641. texture.uOffset = parsedTexture.uOffset;
  17642. texture.vOffset = parsedTexture.vOffset;
  17643. texture.uScale = parsedTexture.uScale;
  17644. texture.vScale = parsedTexture.vScale;
  17645. texture.uAng = parsedTexture.uAng;
  17646. texture.vAng = parsedTexture.vAng;
  17647. texture.wAng = parsedTexture.wAng;
  17648. texture.wrapU = parsedTexture.wrapU;
  17649. texture.wrapV = parsedTexture.wrapV;
  17650. // Animations
  17651. if (parsedTexture.animations) {
  17652. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17653. var parsedAnimation = parsedTexture.animations[animationIndex];
  17654. texture.animations.push(parseAnimation(parsedAnimation));
  17655. }
  17656. }
  17657. return texture;
  17658. };
  17659. var parseSkeleton = function (parsedSkeleton, scene) {
  17660. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17661. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17662. var parsedBone = parsedSkeleton.bones[index];
  17663. var parentBone = null;
  17664. if (parsedBone.parentBoneIndex > -1) {
  17665. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17666. }
  17667. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17668. if (parsedBone.animation) {
  17669. bone.animations.push(parseAnimation(parsedBone.animation));
  17670. }
  17671. }
  17672. return skeleton;
  17673. };
  17674. var parseFresnelParameters = function (parsedFresnelParameters) {
  17675. var fresnelParameters = new BABYLON.FresnelParameters();
  17676. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17677. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17678. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17679. fresnelParameters.bias = parsedFresnelParameters.bias;
  17680. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17681. return fresnelParameters;
  17682. };
  17683. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17684. var material;
  17685. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17686. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17687. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17688. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17689. material.specularPower = parsedMaterial.specularPower;
  17690. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17691. material.alpha = parsedMaterial.alpha;
  17692. material.id = parsedMaterial.id;
  17693. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17694. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17695. material.wireframe = parsedMaterial.wireframe;
  17696. if (parsedMaterial.diffuseTexture) {
  17697. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17698. }
  17699. if (parsedMaterial.diffuseFresnelParameters) {
  17700. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17701. }
  17702. if (parsedMaterial.ambientTexture) {
  17703. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17704. }
  17705. if (parsedMaterial.opacityTexture) {
  17706. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17707. }
  17708. if (parsedMaterial.opacityFresnelParameters) {
  17709. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17710. }
  17711. if (parsedMaterial.reflectionTexture) {
  17712. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17713. }
  17714. if (parsedMaterial.reflectionFresnelParameters) {
  17715. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17716. }
  17717. if (parsedMaterial.emissiveTexture) {
  17718. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17719. }
  17720. if (parsedMaterial.emissiveFresnelParameters) {
  17721. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17722. }
  17723. if (parsedMaterial.specularTexture) {
  17724. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17725. }
  17726. if (parsedMaterial.bumpTexture) {
  17727. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17728. }
  17729. return material;
  17730. };
  17731. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17732. for (var index = 0; index < parsedData.materials.length; index++) {
  17733. var parsedMaterial = parsedData.materials[index];
  17734. if (parsedMaterial.id === id) {
  17735. return parseMaterial(parsedMaterial, scene, rootUrl);
  17736. }
  17737. }
  17738. return null;
  17739. };
  17740. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17741. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17742. multiMaterial.id = parsedMultiMaterial.id;
  17743. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17744. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17745. var subMatId = parsedMultiMaterial.materials[matIndex];
  17746. if (subMatId) {
  17747. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17748. }
  17749. else {
  17750. multiMaterial.subMaterials.push(null);
  17751. }
  17752. }
  17753. return multiMaterial;
  17754. };
  17755. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17756. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17757. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17758. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17759. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17760. var parsedFlare = parsedLensFlareSystem.flares[index];
  17761. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17762. }
  17763. return lensFlareSystem;
  17764. };
  17765. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17766. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17767. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17768. if (parsedParticleSystem.textureName) {
  17769. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17770. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17771. }
  17772. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17773. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17774. particleSystem.minSize = parsedParticleSystem.minSize;
  17775. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17776. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17777. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17778. particleSystem.emitter = emitter;
  17779. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17780. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17781. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17782. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17783. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17784. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17785. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17786. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17787. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17788. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17789. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17790. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17791. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17792. particleSystem.start();
  17793. return particleSystem;
  17794. };
  17795. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17796. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17797. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17798. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17799. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17800. shadowGenerator.getShadowMap().renderList.push(mesh);
  17801. }
  17802. if (parsedShadowGenerator.usePoissonSampling) {
  17803. shadowGenerator.usePoissonSampling = true;
  17804. }
  17805. else if (parsedShadowGenerator.useVarianceShadowMap) {
  17806. shadowGenerator.useVarianceShadowMap = true;
  17807. }
  17808. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  17809. shadowGenerator.useBlurVarianceShadowMap = true;
  17810. if (parsedShadowGenerator.blurScale) {
  17811. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  17812. }
  17813. if (parsedShadowGenerator.blurBoxOffset) {
  17814. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  17815. }
  17816. }
  17817. if (parsedShadowGenerator.bias !== undefined) {
  17818. shadowGenerator.bias = parsedShadowGenerator.bias;
  17819. }
  17820. return shadowGenerator;
  17821. };
  17822. var parseAnimation = function (parsedAnimation) {
  17823. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17824. var dataType = parsedAnimation.dataType;
  17825. var keys = [];
  17826. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17827. var key = parsedAnimation.keys[index];
  17828. var data;
  17829. switch (dataType) {
  17830. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17831. data = key.values[0];
  17832. break;
  17833. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17834. data = BABYLON.Quaternion.FromArray(key.values);
  17835. break;
  17836. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17837. data = BABYLON.Matrix.FromArray(key.values);
  17838. break;
  17839. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17840. default:
  17841. data = BABYLON.Vector3.FromArray(key.values);
  17842. break;
  17843. }
  17844. keys.push({
  17845. frame: key.frame,
  17846. value: data
  17847. });
  17848. }
  17849. animation.setKeys(keys);
  17850. return animation;
  17851. };
  17852. var parseLight = function (parsedLight, scene) {
  17853. var light;
  17854. switch (parsedLight.type) {
  17855. case 0:
  17856. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17857. break;
  17858. case 1:
  17859. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17860. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17861. break;
  17862. case 2:
  17863. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17864. break;
  17865. case 3:
  17866. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17867. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17868. break;
  17869. }
  17870. light.id = parsedLight.id;
  17871. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17872. if (parsedLight.intensity !== undefined) {
  17873. light.intensity = parsedLight.intensity;
  17874. }
  17875. if (parsedLight.range) {
  17876. light.range = parsedLight.range;
  17877. }
  17878. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17879. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17880. if (parsedLight.excludedMeshesIds) {
  17881. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17882. }
  17883. // Parent
  17884. if (parsedLight.parentId) {
  17885. light._waitingParentId = parsedLight.parentId;
  17886. }
  17887. if (parsedLight.includedOnlyMeshesIds) {
  17888. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17889. }
  17890. // Animations
  17891. if (parsedLight.animations) {
  17892. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17893. var parsedAnimation = parsedLight.animations[animationIndex];
  17894. light.animations.push(parseAnimation(parsedAnimation));
  17895. }
  17896. }
  17897. if (parsedLight.autoAnimate) {
  17898. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17899. }
  17900. };
  17901. var parseCamera = function (parsedCamera, scene) {
  17902. var camera;
  17903. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17904. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17905. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17906. var alpha = parsedCamera.alpha;
  17907. var beta = parsedCamera.beta;
  17908. var radius = parsedCamera.radius;
  17909. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17910. var eye_space = parsedCamera.eye_space;
  17911. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17912. }
  17913. else {
  17914. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17915. }
  17916. }
  17917. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17918. eye_space = parsedCamera.eye_space;
  17919. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17920. }
  17921. else if (parsedCamera.type === "DeviceOrientationCamera") {
  17922. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17923. }
  17924. else if (parsedCamera.type === "FollowCamera") {
  17925. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17926. camera.heightOffset = parsedCamera.heightOffset;
  17927. camera.radius = parsedCamera.radius;
  17928. camera.rotationOffset = parsedCamera.rotationOffset;
  17929. if (lockedTargetMesh)
  17930. camera.target = lockedTargetMesh;
  17931. }
  17932. else if (parsedCamera.type === "GamepadCamera") {
  17933. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17934. }
  17935. else if (parsedCamera.type === "OculusCamera") {
  17936. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17937. }
  17938. else if (parsedCamera.type === "OculusGamepadCamera") {
  17939. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17940. }
  17941. else if (parsedCamera.type === "TouchCamera") {
  17942. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17943. }
  17944. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17945. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17946. }
  17947. else if (parsedCamera.type === "WebVRCamera") {
  17948. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17949. }
  17950. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17951. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17952. }
  17953. else {
  17954. // Free Camera is the default value
  17955. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17956. }
  17957. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17958. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17959. camera.lockedTarget = lockedTargetMesh;
  17960. }
  17961. camera.id = parsedCamera.id;
  17962. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17963. // Parent
  17964. if (parsedCamera.parentId) {
  17965. camera._waitingParentId = parsedCamera.parentId;
  17966. }
  17967. // Target
  17968. if (parsedCamera.target) {
  17969. if (camera.setTarget) {
  17970. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17971. }
  17972. else {
  17973. //For ArcRotate
  17974. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  17975. }
  17976. }
  17977. else {
  17978. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17979. }
  17980. camera.fov = parsedCamera.fov;
  17981. camera.minZ = parsedCamera.minZ;
  17982. camera.maxZ = parsedCamera.maxZ;
  17983. camera.speed = parsedCamera.speed;
  17984. camera.inertia = parsedCamera.inertia;
  17985. camera.checkCollisions = parsedCamera.checkCollisions;
  17986. camera.applyGravity = parsedCamera.applyGravity;
  17987. if (parsedCamera.ellipsoid) {
  17988. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17989. }
  17990. // Animations
  17991. if (parsedCamera.animations) {
  17992. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17993. var parsedAnimation = parsedCamera.animations[animationIndex];
  17994. camera.animations.push(parseAnimation(parsedAnimation));
  17995. }
  17996. }
  17997. if (parsedCamera.autoAnimate) {
  17998. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17999. }
  18000. // Layer Mask
  18001. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18002. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18003. }
  18004. else {
  18005. camera.layerMask = 0xFFFFFFFF;
  18006. }
  18007. return camera;
  18008. };
  18009. var parseGeometry = function (parsedGeometry, scene) {
  18010. var id = parsedGeometry.id;
  18011. return scene.getGeometryByID(id);
  18012. };
  18013. var parseBox = function (parsedBox, scene) {
  18014. if (parseGeometry(parsedBox, scene)) {
  18015. return null; // null since geometry could be something else than a box...
  18016. }
  18017. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18018. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18019. scene.pushGeometry(box, true);
  18020. return box;
  18021. };
  18022. var parseSphere = function (parsedSphere, scene) {
  18023. if (parseGeometry(parsedSphere, scene)) {
  18024. return null; // null since geometry could be something else than a sphere...
  18025. }
  18026. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18027. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18028. scene.pushGeometry(sphere, true);
  18029. return sphere;
  18030. };
  18031. var parseCylinder = function (parsedCylinder, scene) {
  18032. if (parseGeometry(parsedCylinder, scene)) {
  18033. return null; // null since geometry could be something else than a cylinder...
  18034. }
  18035. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18036. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18037. scene.pushGeometry(cylinder, true);
  18038. return cylinder;
  18039. };
  18040. var parseTorus = function (parsedTorus, scene) {
  18041. if (parseGeometry(parsedTorus, scene)) {
  18042. return null; // null since geometry could be something else than a torus...
  18043. }
  18044. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18045. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18046. scene.pushGeometry(torus, true);
  18047. return torus;
  18048. };
  18049. var parseGround = function (parsedGround, scene) {
  18050. if (parseGeometry(parsedGround, scene)) {
  18051. return null; // null since geometry could be something else than a ground...
  18052. }
  18053. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18054. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18055. scene.pushGeometry(ground, true);
  18056. return ground;
  18057. };
  18058. var parsePlane = function (parsedPlane, scene) {
  18059. if (parseGeometry(parsedPlane, scene)) {
  18060. return null; // null since geometry could be something else than a plane...
  18061. }
  18062. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18063. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18064. scene.pushGeometry(plane, true);
  18065. return plane;
  18066. };
  18067. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18068. if (parseGeometry(parsedTorusKnot, scene)) {
  18069. return null; // null since geometry could be something else than a torusKnot...
  18070. }
  18071. 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);
  18072. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18073. scene.pushGeometry(torusKnot, true);
  18074. return torusKnot;
  18075. };
  18076. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18077. if (parseGeometry(parsedVertexData, scene)) {
  18078. return null; // null since geometry could be a primitive
  18079. }
  18080. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18081. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18082. if (parsedVertexData.delayLoadingFile) {
  18083. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18084. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18085. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18086. geometry._delayInfo = [];
  18087. if (parsedVertexData.hasUVs) {
  18088. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18089. }
  18090. if (parsedVertexData.hasUVs2) {
  18091. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18092. }
  18093. if (parsedVertexData.hasColors) {
  18094. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18095. }
  18096. if (parsedVertexData.hasMatricesIndices) {
  18097. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18098. }
  18099. if (parsedVertexData.hasMatricesWeights) {
  18100. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18101. }
  18102. geometry._delayLoadingFunction = importVertexData;
  18103. }
  18104. else {
  18105. importVertexData(parsedVertexData, geometry);
  18106. }
  18107. scene.pushGeometry(geometry, true);
  18108. return geometry;
  18109. };
  18110. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18111. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18112. mesh.id = parsedMesh.id;
  18113. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18114. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18115. if (parsedMesh.rotationQuaternion) {
  18116. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18117. }
  18118. else if (parsedMesh.rotation) {
  18119. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18120. }
  18121. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18122. if (parsedMesh.localMatrix) {
  18123. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18124. }
  18125. else if (parsedMesh.pivotMatrix) {
  18126. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18127. }
  18128. mesh.setEnabled(parsedMesh.isEnabled);
  18129. mesh.isVisible = parsedMesh.isVisible;
  18130. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18131. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18132. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18133. if (parsedMesh.applyFog !== undefined) {
  18134. mesh.applyFog = parsedMesh.applyFog;
  18135. }
  18136. if (parsedMesh.pickable !== undefined) {
  18137. mesh.isPickable = parsedMesh.pickable;
  18138. }
  18139. if (parsedMesh.alphaIndex !== undefined) {
  18140. mesh.alphaIndex = parsedMesh.alphaIndex;
  18141. }
  18142. mesh.receiveShadows = parsedMesh.receiveShadows;
  18143. mesh.billboardMode = parsedMesh.billboardMode;
  18144. if (parsedMesh.visibility !== undefined) {
  18145. mesh.visibility = parsedMesh.visibility;
  18146. }
  18147. mesh.checkCollisions = parsedMesh.checkCollisions;
  18148. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18149. // Parent
  18150. if (parsedMesh.parentId) {
  18151. mesh._waitingParentId = parsedMesh.parentId;
  18152. }
  18153. // Actions
  18154. if (parsedMesh.actions !== undefined) {
  18155. mesh._waitingActions = parsedMesh.actions;
  18156. }
  18157. // Geometry
  18158. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18159. if (parsedMesh.delayLoadingFile) {
  18160. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18161. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18162. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18163. if (parsedMesh._binaryInfo) {
  18164. mesh._binaryInfo = parsedMesh._binaryInfo;
  18165. }
  18166. mesh._delayInfo = [];
  18167. if (parsedMesh.hasUVs) {
  18168. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18169. }
  18170. if (parsedMesh.hasUVs2) {
  18171. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18172. }
  18173. if (parsedMesh.hasColors) {
  18174. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18175. }
  18176. if (parsedMesh.hasMatricesIndices) {
  18177. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18178. }
  18179. if (parsedMesh.hasMatricesWeights) {
  18180. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18181. }
  18182. mesh._delayLoadingFunction = importGeometry;
  18183. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18184. mesh._checkDelayState();
  18185. }
  18186. }
  18187. else {
  18188. importGeometry(parsedMesh, mesh);
  18189. }
  18190. // Material
  18191. if (parsedMesh.materialId) {
  18192. mesh.setMaterialByID(parsedMesh.materialId);
  18193. }
  18194. else {
  18195. mesh.material = null;
  18196. }
  18197. // Skeleton
  18198. if (parsedMesh.skeletonId > -1) {
  18199. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18200. }
  18201. // Physics
  18202. if (parsedMesh.physicsImpostor) {
  18203. if (!scene.isPhysicsEnabled()) {
  18204. scene.enablePhysics();
  18205. }
  18206. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18207. }
  18208. // Animations
  18209. if (parsedMesh.animations) {
  18210. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18211. var parsedAnimation = parsedMesh.animations[animationIndex];
  18212. mesh.animations.push(parseAnimation(parsedAnimation));
  18213. }
  18214. }
  18215. if (parsedMesh.autoAnimate) {
  18216. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18217. }
  18218. // Layer Mask
  18219. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18220. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18221. }
  18222. else {
  18223. mesh.layerMask = 0xFFFFFFFF;
  18224. }
  18225. // Instances
  18226. if (parsedMesh.instances) {
  18227. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18228. var parsedInstance = parsedMesh.instances[index];
  18229. var instance = mesh.createInstance(parsedInstance.name);
  18230. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18231. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18232. if (parsedInstance.rotationQuaternion) {
  18233. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18234. }
  18235. else if (parsedInstance.rotation) {
  18236. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18237. }
  18238. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18239. instance.checkCollisions = mesh.checkCollisions;
  18240. if (parsedMesh.animations) {
  18241. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18242. parsedAnimation = parsedMesh.animations[animationIndex];
  18243. instance.animations.push(parseAnimation(parsedAnimation));
  18244. }
  18245. }
  18246. }
  18247. }
  18248. return mesh;
  18249. };
  18250. var parseActions = function (parsedActions, object, scene) {
  18251. var actionManager = new BABYLON.ActionManager(scene);
  18252. if (object === null)
  18253. scene.actionManager = actionManager;
  18254. else
  18255. object.actionManager = actionManager;
  18256. // instanciate a new object
  18257. var instanciate = function (name, params) {
  18258. var newInstance = Object.create(BABYLON[name].prototype);
  18259. newInstance.constructor.apply(newInstance, params);
  18260. return newInstance;
  18261. };
  18262. var parseParameter = function (name, value, target, propertyPath) {
  18263. if (propertyPath === null) {
  18264. // String, boolean or float
  18265. var floatValue = parseFloat(value);
  18266. if (value === "true" || value === "false")
  18267. return value === "true";
  18268. else
  18269. return isNaN(floatValue) ? value : floatValue;
  18270. }
  18271. var effectiveTarget = propertyPath.split(".");
  18272. var values = value.split(",");
  18273. for (var i = 0; i < effectiveTarget.length; i++) {
  18274. target = target[effectiveTarget[i]];
  18275. }
  18276. // Return appropriate value with its type
  18277. if (typeof (target) === "boolean")
  18278. return values[0] === "true";
  18279. if (typeof (target) === "string")
  18280. return values[0];
  18281. // Parameters with multiple values such as Vector3 etc.
  18282. var split = new Array();
  18283. for (var i = 0; i < values.length; i++)
  18284. split.push(parseFloat(values[i]));
  18285. if (target instanceof BABYLON.Vector3)
  18286. return BABYLON.Vector3.FromArray(split);
  18287. if (target instanceof BABYLON.Vector4)
  18288. return BABYLON.Vector4.FromArray(split);
  18289. if (target instanceof BABYLON.Color3)
  18290. return BABYLON.Color3.FromArray(split);
  18291. if (target instanceof BABYLON.Color4)
  18292. return BABYLON.Color4.FromArray(split);
  18293. return parseFloat(values[0]);
  18294. };
  18295. // traverse graph per trigger
  18296. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18297. if (combineArray === void 0) { combineArray = null; }
  18298. if (parsedAction.detached)
  18299. return;
  18300. var parameters = new Array();
  18301. var target = null;
  18302. var propertyPath = null;
  18303. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18304. // Parameters
  18305. if (parsedAction.type === 2)
  18306. parameters.push(actionManager);
  18307. else
  18308. parameters.push(trigger);
  18309. if (combine) {
  18310. var actions = new Array();
  18311. for (var j = 0; j < parsedAction.combine.length; j++) {
  18312. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18313. }
  18314. parameters.push(actions);
  18315. }
  18316. else {
  18317. for (var i = 0; i < parsedAction.properties.length; i++) {
  18318. var value = parsedAction.properties[i].value;
  18319. var name = parsedAction.properties[i].name;
  18320. var targetType = parsedAction.properties[i].targetType;
  18321. if (name === "target")
  18322. if (targetType !== null && targetType === "SceneProperties")
  18323. value = target = scene;
  18324. else
  18325. value = target = scene.getNodeByName(value);
  18326. else if (name === "parent")
  18327. value = scene.getNodeByName(value);
  18328. else if (name === "sound")
  18329. value = scene.getSoundByName(value);
  18330. else if (name !== "propertyPath") {
  18331. if (parsedAction.type === 2 && name === "operator")
  18332. value = BABYLON.ValueCondition[value];
  18333. else
  18334. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18335. }
  18336. else {
  18337. propertyPath = value;
  18338. }
  18339. parameters.push(value);
  18340. }
  18341. }
  18342. if (combineArray === null) {
  18343. parameters.push(condition);
  18344. }
  18345. else {
  18346. parameters.push(null);
  18347. }
  18348. // If interpolate value action
  18349. if (parsedAction.name === "InterpolateValueAction") {
  18350. var param = parameters[parameters.length - 2];
  18351. parameters[parameters.length - 1] = param;
  18352. parameters[parameters.length - 2] = condition;
  18353. }
  18354. // Action or condition(s) and not CombineAction
  18355. var newAction = instanciate(parsedAction.name, parameters);
  18356. if (combineArray === null) {
  18357. if (newAction instanceof BABYLON.Condition) {
  18358. condition = newAction;
  18359. newAction = action;
  18360. }
  18361. else {
  18362. condition = null;
  18363. if (action)
  18364. action.then(newAction);
  18365. else
  18366. actionManager.registerAction(newAction);
  18367. }
  18368. }
  18369. else {
  18370. combineArray.push(newAction);
  18371. }
  18372. for (var i = 0; i < parsedAction.children.length; i++)
  18373. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18374. };
  18375. for (var i = 0; i < parsedActions.children.length; i++) {
  18376. var triggerParams;
  18377. var trigger = parsedActions.children[i];
  18378. if (trigger.properties.length > 0) {
  18379. var param = trigger.properties[0].value;
  18380. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18381. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18382. }
  18383. else
  18384. triggerParams = BABYLON.ActionManager[trigger.name];
  18385. for (var j = 0; j < trigger.children.length; j++) {
  18386. if (!trigger.detached)
  18387. traverse(trigger.children[j], triggerParams, null, null);
  18388. }
  18389. }
  18390. };
  18391. var parseSound = function (parsedSound, scene, rootUrl) {
  18392. var soundName = parsedSound.name;
  18393. var soundUrl = rootUrl + soundName;
  18394. var options = {
  18395. autoplay: parsedSound.autoplay,
  18396. loop: parsedSound.loop,
  18397. volume: parsedSound.volume,
  18398. spatialSound: parsedSound.spatialSound,
  18399. maxDistance: parsedSound.maxDistance,
  18400. rolloffFactor: parsedSound.rolloffFactor,
  18401. refDistance: parsedSound.refDistance,
  18402. distanceModel: parsedSound.distanceModel,
  18403. playbackRate: parsedSound.playbackRate
  18404. };
  18405. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18406. scene._removePendingData(newSound);
  18407. }, options);
  18408. scene._addPendingData(newSound);
  18409. if (parsedSound.position) {
  18410. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18411. newSound.setPosition(soundPosition);
  18412. }
  18413. if (parsedSound.isDirectional) {
  18414. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18415. if (parsedSound.localDirectionToMesh) {
  18416. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18417. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18418. }
  18419. }
  18420. if (parsedSound.connectedMeshId) {
  18421. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18422. if (connectedMesh) {
  18423. newSound.attachToMesh(connectedMesh);
  18424. }
  18425. }
  18426. };
  18427. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18428. names = (names instanceof Array) ? names : [names];
  18429. for (var i in names) {
  18430. if (mesh.name === names[i]) {
  18431. hierarchyIds.push(mesh.id);
  18432. return true;
  18433. }
  18434. }
  18435. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18436. hierarchyIds.push(mesh.id);
  18437. return true;
  18438. }
  18439. return false;
  18440. };
  18441. var importVertexData = function (parsedVertexData, geometry) {
  18442. var vertexData = new BABYLON.VertexData();
  18443. // positions
  18444. var positions = parsedVertexData.positions;
  18445. if (positions) {
  18446. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18447. }
  18448. // normals
  18449. var normals = parsedVertexData.normals;
  18450. if (normals) {
  18451. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18452. }
  18453. // uvs
  18454. var uvs = parsedVertexData.uvs;
  18455. if (uvs) {
  18456. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18457. }
  18458. // uv2s
  18459. var uv2s = parsedVertexData.uv2s;
  18460. if (uv2s) {
  18461. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18462. }
  18463. // colors
  18464. var colors = parsedVertexData.colors;
  18465. if (colors) {
  18466. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18467. }
  18468. // matricesIndices
  18469. var matricesIndices = parsedVertexData.matricesIndices;
  18470. if (matricesIndices) {
  18471. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18472. }
  18473. // matricesWeights
  18474. var matricesWeights = parsedVertexData.matricesWeights;
  18475. if (matricesWeights) {
  18476. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18477. }
  18478. // indices
  18479. var indices = parsedVertexData.indices;
  18480. if (indices) {
  18481. vertexData.indices = indices;
  18482. }
  18483. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18484. };
  18485. var importGeometry = function (parsedGeometry, mesh) {
  18486. var scene = mesh.getScene();
  18487. // Geometry
  18488. var geometryId = parsedGeometry.geometryId;
  18489. if (geometryId) {
  18490. var geometry = scene.getGeometryByID(geometryId);
  18491. if (geometry) {
  18492. geometry.applyToMesh(mesh);
  18493. }
  18494. }
  18495. else if (parsedGeometry instanceof ArrayBuffer) {
  18496. var binaryInfo = mesh._binaryInfo;
  18497. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18498. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18499. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18500. }
  18501. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18502. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18503. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18504. }
  18505. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18506. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18507. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18508. }
  18509. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18510. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18511. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18512. }
  18513. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18514. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18515. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18516. }
  18517. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18518. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18519. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18520. }
  18521. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18522. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18524. }
  18525. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18526. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18527. mesh.setIndices(indicesData);
  18528. }
  18529. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18530. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18531. mesh.subMeshes = [];
  18532. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18533. var materialIndex = subMeshesData[(i * 5) + 0];
  18534. var verticesStart = subMeshesData[(i * 5) + 1];
  18535. var verticesCount = subMeshesData[(i * 5) + 2];
  18536. var indexStart = subMeshesData[(i * 5) + 3];
  18537. var indexCount = subMeshesData[(i * 5) + 4];
  18538. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18539. }
  18540. }
  18541. }
  18542. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18543. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18544. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18545. if (parsedGeometry.uvs) {
  18546. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18547. }
  18548. if (parsedGeometry.uvs2) {
  18549. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18550. }
  18551. if (parsedGeometry.colors) {
  18552. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18553. }
  18554. if (parsedGeometry.matricesIndices) {
  18555. if (!parsedGeometry.matricesIndices._isExpanded) {
  18556. var floatIndices = [];
  18557. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18558. var matricesIndex = parsedGeometry.matricesIndices[i];
  18559. floatIndices.push(matricesIndex & 0x000000FF);
  18560. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18561. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18562. floatIndices.push(matricesIndex >> 24);
  18563. }
  18564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18565. }
  18566. else {
  18567. delete parsedGeometry.matricesIndices._isExpanded;
  18568. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18569. }
  18570. }
  18571. if (parsedGeometry.matricesWeights) {
  18572. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18573. }
  18574. mesh.setIndices(parsedGeometry.indices);
  18575. // SubMeshes
  18576. if (parsedGeometry.subMeshes) {
  18577. mesh.subMeshes = [];
  18578. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18579. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18580. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18581. }
  18582. }
  18583. }
  18584. // Flat shading
  18585. if (mesh._shouldGenerateFlatShading) {
  18586. mesh.convertToFlatShadedMesh();
  18587. delete mesh._shouldGenerateFlatShading;
  18588. }
  18589. // Update
  18590. mesh.computeWorldMatrix(true);
  18591. // Octree
  18592. if (scene._selectionOctree) {
  18593. scene._selectionOctree.addMesh(mesh);
  18594. }
  18595. };
  18596. BABYLON.SceneLoader.RegisterPlugin({
  18597. extensions: ".babylon",
  18598. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18599. var parsedData = JSON.parse(data);
  18600. var loadedSkeletonsIds = [];
  18601. var loadedMaterialsIds = [];
  18602. var hierarchyIds = [];
  18603. for (var index = 0; index < parsedData.meshes.length; index++) {
  18604. var parsedMesh = parsedData.meshes[index];
  18605. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18606. if (meshesNames instanceof Array) {
  18607. // Remove found mesh name from list.
  18608. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18609. }
  18610. // Material ?
  18611. if (parsedMesh.materialId) {
  18612. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18613. if (!materialFound) {
  18614. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18615. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18616. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18617. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18618. var subMatId = parsedMultiMaterial.materials[matIndex];
  18619. loadedMaterialsIds.push(subMatId);
  18620. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18621. }
  18622. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18623. parseMultiMaterial(parsedMultiMaterial, scene);
  18624. materialFound = true;
  18625. break;
  18626. }
  18627. }
  18628. }
  18629. if (!materialFound) {
  18630. loadedMaterialsIds.push(parsedMesh.materialId);
  18631. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18632. }
  18633. }
  18634. // Skeleton ?
  18635. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18636. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18637. if (!skeletonAlreadyLoaded) {
  18638. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18639. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18640. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18641. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18642. loadedSkeletonsIds.push(parsedSkeleton.id);
  18643. }
  18644. }
  18645. }
  18646. }
  18647. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18648. meshes.push(mesh);
  18649. }
  18650. }
  18651. for (index = 0; index < scene.meshes.length; index++) {
  18652. var currentMesh = scene.meshes[index];
  18653. if (currentMesh._waitingParentId) {
  18654. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18655. currentMesh._waitingParentId = undefined;
  18656. }
  18657. }
  18658. // Particles
  18659. if (parsedData.particleSystems) {
  18660. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18661. var parsedParticleSystem = parsedData.particleSystems[index];
  18662. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18663. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18664. }
  18665. }
  18666. }
  18667. return true;
  18668. },
  18669. load: function (scene, data, rootUrl) {
  18670. var parsedData = JSON.parse(data);
  18671. // Scene
  18672. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18673. scene.autoClear = parsedData.autoClear;
  18674. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18675. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18676. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18677. // Fog
  18678. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18679. scene.fogMode = parsedData.fogMode;
  18680. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18681. scene.fogStart = parsedData.fogStart;
  18682. scene.fogEnd = parsedData.fogEnd;
  18683. scene.fogDensity = parsedData.fogDensity;
  18684. }
  18685. for (var index = 0; index < parsedData.lights.length; index++) {
  18686. var parsedLight = parsedData.lights[index];
  18687. parseLight(parsedLight, scene);
  18688. }
  18689. // Materials
  18690. if (parsedData.materials) {
  18691. for (index = 0; index < parsedData.materials.length; index++) {
  18692. var parsedMaterial = parsedData.materials[index];
  18693. parseMaterial(parsedMaterial, scene, rootUrl);
  18694. }
  18695. }
  18696. if (parsedData.multiMaterials) {
  18697. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18698. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18699. parseMultiMaterial(parsedMultiMaterial, scene);
  18700. }
  18701. }
  18702. // Skeletons
  18703. if (parsedData.skeletons) {
  18704. for (index = 0; index < parsedData.skeletons.length; index++) {
  18705. var parsedSkeleton = parsedData.skeletons[index];
  18706. parseSkeleton(parsedSkeleton, scene);
  18707. }
  18708. }
  18709. // Geometries
  18710. var geometries = parsedData.geometries;
  18711. if (geometries) {
  18712. // Boxes
  18713. var boxes = geometries.boxes;
  18714. if (boxes) {
  18715. for (index = 0; index < boxes.length; index++) {
  18716. var parsedBox = boxes[index];
  18717. parseBox(parsedBox, scene);
  18718. }
  18719. }
  18720. // Spheres
  18721. var spheres = geometries.spheres;
  18722. if (spheres) {
  18723. for (index = 0; index < spheres.length; index++) {
  18724. var parsedSphere = spheres[index];
  18725. parseSphere(parsedSphere, scene);
  18726. }
  18727. }
  18728. // Cylinders
  18729. var cylinders = geometries.cylinders;
  18730. if (cylinders) {
  18731. for (index = 0; index < cylinders.length; index++) {
  18732. var parsedCylinder = cylinders[index];
  18733. parseCylinder(parsedCylinder, scene);
  18734. }
  18735. }
  18736. // Toruses
  18737. var toruses = geometries.toruses;
  18738. if (toruses) {
  18739. for (index = 0; index < toruses.length; index++) {
  18740. var parsedTorus = toruses[index];
  18741. parseTorus(parsedTorus, scene);
  18742. }
  18743. }
  18744. // Grounds
  18745. var grounds = geometries.grounds;
  18746. if (grounds) {
  18747. for (index = 0; index < grounds.length; index++) {
  18748. var parsedGround = grounds[index];
  18749. parseGround(parsedGround, scene);
  18750. }
  18751. }
  18752. // Planes
  18753. var planes = geometries.planes;
  18754. if (planes) {
  18755. for (index = 0; index < planes.length; index++) {
  18756. var parsedPlane = planes[index];
  18757. parsePlane(parsedPlane, scene);
  18758. }
  18759. }
  18760. // TorusKnots
  18761. var torusKnots = geometries.torusKnots;
  18762. if (torusKnots) {
  18763. for (index = 0; index < torusKnots.length; index++) {
  18764. var parsedTorusKnot = torusKnots[index];
  18765. parseTorusKnot(parsedTorusKnot, scene);
  18766. }
  18767. }
  18768. // VertexData
  18769. var vertexData = geometries.vertexData;
  18770. if (vertexData) {
  18771. for (index = 0; index < vertexData.length; index++) {
  18772. var parsedVertexData = vertexData[index];
  18773. parseVertexData(parsedVertexData, scene, rootUrl);
  18774. }
  18775. }
  18776. }
  18777. for (index = 0; index < parsedData.meshes.length; index++) {
  18778. var parsedMesh = parsedData.meshes[index];
  18779. parseMesh(parsedMesh, scene, rootUrl);
  18780. }
  18781. for (index = 0; index < parsedData.cameras.length; index++) {
  18782. var parsedCamera = parsedData.cameras[index];
  18783. parseCamera(parsedCamera, scene);
  18784. }
  18785. if (parsedData.activeCameraID) {
  18786. scene.setActiveCameraByID(parsedData.activeCameraID);
  18787. }
  18788. for (index = 0; index < scene.cameras.length; index++) {
  18789. var camera = scene.cameras[index];
  18790. if (camera._waitingParentId) {
  18791. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18792. camera._waitingParentId = undefined;
  18793. }
  18794. }
  18795. for (index = 0; index < scene.lights.length; index++) {
  18796. var light = scene.lights[index];
  18797. if (light._waitingParentId) {
  18798. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18799. light._waitingParentId = undefined;
  18800. }
  18801. }
  18802. // Sounds
  18803. if (parsedData.sounds) {
  18804. for (index = 0; index < parsedData.sounds.length; index++) {
  18805. var parsedSound = parsedData.sounds[index];
  18806. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  18807. parseSound(parsedSound, scene, rootUrl);
  18808. }
  18809. else {
  18810. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  18811. }
  18812. }
  18813. }
  18814. for (index = 0; index < scene.meshes.length; index++) {
  18815. var mesh = scene.meshes[index];
  18816. if (mesh._waitingParentId) {
  18817. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18818. mesh._waitingParentId = undefined;
  18819. }
  18820. if (mesh._waitingActions) {
  18821. parseActions(mesh._waitingActions, mesh, scene);
  18822. mesh._waitingActions = undefined;
  18823. }
  18824. }
  18825. // Particles Systems
  18826. if (parsedData.particleSystems) {
  18827. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18828. var parsedParticleSystem = parsedData.particleSystems[index];
  18829. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18830. }
  18831. }
  18832. // Lens flares
  18833. if (parsedData.lensFlareSystems) {
  18834. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18835. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18836. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18837. }
  18838. }
  18839. // Shadows
  18840. if (parsedData.shadowGenerators) {
  18841. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18842. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18843. parseShadowGenerator(parsedShadowGenerator, scene);
  18844. }
  18845. }
  18846. // Actions (scene)
  18847. if (parsedData.actions) {
  18848. parseActions(parsedData.actions, null, scene);
  18849. }
  18850. // Finish
  18851. return true;
  18852. }
  18853. });
  18854. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18855. })(BABYLON || (BABYLON = {}));
  18856. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18857. var BABYLON;
  18858. (function (BABYLON) {
  18859. var SpriteManager = (function () {
  18860. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  18861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18862. this.name = name;
  18863. this.cellSize = cellSize;
  18864. this.sprites = new Array();
  18865. this.renderingGroupId = 0;
  18866. this.fogEnabled = true;
  18867. this._vertexDeclaration = [4, 4, 4, 4];
  18868. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  18869. this._capacity = capacity;
  18870. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  18871. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18872. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18873. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  18874. this._scene = scene;
  18875. this._scene.spriteManagers.push(this);
  18876. // VBO
  18877. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  18878. var indices = [];
  18879. var index = 0;
  18880. for (var count = 0; count < capacity; count++) {
  18881. indices.push(index);
  18882. indices.push(index + 1);
  18883. indices.push(index + 2);
  18884. indices.push(index);
  18885. indices.push(index + 2);
  18886. indices.push(index + 3);
  18887. index += 4;
  18888. }
  18889. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18890. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  18891. // Effects
  18892. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  18893. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  18894. }
  18895. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  18896. var arrayOffset = index * 16;
  18897. if (offsetX === 0)
  18898. offsetX = this._epsilon;
  18899. else if (offsetX === 1)
  18900. offsetX = 1 - this._epsilon;
  18901. if (offsetY === 0)
  18902. offsetY = this._epsilon;
  18903. else if (offsetY === 1)
  18904. offsetY = 1 - this._epsilon;
  18905. this._vertices[arrayOffset] = sprite.position.x;
  18906. this._vertices[arrayOffset + 1] = sprite.position.y;
  18907. this._vertices[arrayOffset + 2] = sprite.position.z;
  18908. this._vertices[arrayOffset + 3] = sprite.angle;
  18909. this._vertices[arrayOffset + 4] = sprite.width;
  18910. this._vertices[arrayOffset + 5] = sprite.height;
  18911. this._vertices[arrayOffset + 6] = offsetX;
  18912. this._vertices[arrayOffset + 7] = offsetY;
  18913. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  18914. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  18915. var offset = (sprite.cellIndex / rowSize) >> 0;
  18916. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  18917. this._vertices[arrayOffset + 11] = offset;
  18918. // Color
  18919. this._vertices[arrayOffset + 12] = sprite.color.r;
  18920. this._vertices[arrayOffset + 13] = sprite.color.g;
  18921. this._vertices[arrayOffset + 14] = sprite.color.b;
  18922. this._vertices[arrayOffset + 15] = sprite.color.a;
  18923. };
  18924. SpriteManager.prototype.render = function () {
  18925. // Check
  18926. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  18927. return;
  18928. var engine = this._scene.getEngine();
  18929. var baseSize = this._spriteTexture.getBaseSize();
  18930. // Sprites
  18931. var deltaTime = engine.getDeltaTime();
  18932. var max = Math.min(this._capacity, this.sprites.length);
  18933. var rowSize = baseSize.width / this.cellSize;
  18934. var offset = 0;
  18935. for (var index = 0; index < max; index++) {
  18936. var sprite = this.sprites[index];
  18937. if (!sprite) {
  18938. continue;
  18939. }
  18940. sprite._animate(deltaTime);
  18941. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  18942. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  18943. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  18944. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  18945. }
  18946. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  18947. // Render
  18948. var effect = this._effectBase;
  18949. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18950. effect = this._effectFog;
  18951. }
  18952. engine.enableEffect(effect);
  18953. var viewMatrix = this._scene.getViewMatrix();
  18954. effect.setTexture("diffuseSampler", this._spriteTexture);
  18955. effect.setMatrix("view", viewMatrix);
  18956. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  18957. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  18958. // Fog
  18959. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18960. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  18961. effect.setColor3("vFogColor", this._scene.fogColor);
  18962. }
  18963. // VBOs
  18964. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  18965. // Draw order
  18966. engine.setDepthFunctionToLessOrEqual();
  18967. effect.setBool("alphaTest", true);
  18968. engine.setColorWrite(false);
  18969. engine.draw(true, 0, max * 6);
  18970. engine.setColorWrite(true);
  18971. effect.setBool("alphaTest", false);
  18972. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18973. engine.draw(true, 0, max * 6);
  18974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18975. };
  18976. SpriteManager.prototype.dispose = function () {
  18977. if (this._vertexBuffer) {
  18978. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18979. this._vertexBuffer = null;
  18980. }
  18981. if (this._indexBuffer) {
  18982. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18983. this._indexBuffer = null;
  18984. }
  18985. if (this._spriteTexture) {
  18986. this._spriteTexture.dispose();
  18987. this._spriteTexture = null;
  18988. }
  18989. // Remove from scene
  18990. var index = this._scene.spriteManagers.indexOf(this);
  18991. this._scene.spriteManagers.splice(index, 1);
  18992. // Callback
  18993. if (this.onDispose) {
  18994. this.onDispose();
  18995. }
  18996. };
  18997. return SpriteManager;
  18998. })();
  18999. BABYLON.SpriteManager = SpriteManager;
  19000. })(BABYLON || (BABYLON = {}));
  19001. //# sourceMappingURL=babylon.spriteManager.js.map
  19002. var BABYLON;
  19003. (function (BABYLON) {
  19004. var Sprite = (function () {
  19005. function Sprite(name, manager) {
  19006. this.name = name;
  19007. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19008. this.width = 1.0;
  19009. this.height = 1.0;
  19010. this.angle = 0;
  19011. this.cellIndex = 0;
  19012. this.invertU = 0;
  19013. this.invertV = 0;
  19014. this.animations = new Array();
  19015. this._animationStarted = false;
  19016. this._loopAnimation = false;
  19017. this._fromIndex = 0;
  19018. this._toIndex = 0;
  19019. this._delay = 0;
  19020. this._direction = 1;
  19021. this._frameCount = 0;
  19022. this._time = 0;
  19023. this._manager = manager;
  19024. this._manager.sprites.push(this);
  19025. this.position = BABYLON.Vector3.Zero();
  19026. }
  19027. Object.defineProperty(Sprite.prototype, "size", {
  19028. get: function () {
  19029. return this.width;
  19030. },
  19031. set: function (value) {
  19032. this.width = value;
  19033. this.height = value;
  19034. },
  19035. enumerable: true,
  19036. configurable: true
  19037. });
  19038. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19039. this._fromIndex = from;
  19040. this._toIndex = to;
  19041. this._loopAnimation = loop;
  19042. this._delay = delay;
  19043. this._animationStarted = true;
  19044. this._direction = from < to ? 1 : -1;
  19045. this.cellIndex = from;
  19046. this._time = 0;
  19047. };
  19048. Sprite.prototype.stopAnimation = function () {
  19049. this._animationStarted = false;
  19050. };
  19051. Sprite.prototype._animate = function (deltaTime) {
  19052. if (!this._animationStarted)
  19053. return;
  19054. this._time += deltaTime;
  19055. if (this._time > this._delay) {
  19056. this._time = this._time % this._delay;
  19057. this.cellIndex += this._direction;
  19058. if (this.cellIndex == this._toIndex) {
  19059. if (this._loopAnimation) {
  19060. this.cellIndex = this._fromIndex;
  19061. }
  19062. else {
  19063. this._animationStarted = false;
  19064. if (this.disposeWhenFinishedAnimating) {
  19065. this.dispose();
  19066. }
  19067. }
  19068. }
  19069. }
  19070. };
  19071. Sprite.prototype.dispose = function () {
  19072. for (var i = 0; i < this._manager.sprites.length; i++) {
  19073. if (this._manager.sprites[i] == this) {
  19074. this._manager.sprites.splice(i, 1);
  19075. }
  19076. }
  19077. };
  19078. return Sprite;
  19079. })();
  19080. BABYLON.Sprite = Sprite;
  19081. })(BABYLON || (BABYLON = {}));
  19082. //# sourceMappingURL=babylon.sprite.js.map
  19083. var BABYLON;
  19084. (function (BABYLON) {
  19085. var Layer = (function () {
  19086. function Layer(name, imgUrl, scene, isBackground, color) {
  19087. this.name = name;
  19088. this._vertexDeclaration = [2];
  19089. this._vertexStrideSize = 2 * 4;
  19090. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19091. this.isBackground = isBackground === undefined ? true : isBackground;
  19092. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19093. this._scene = scene;
  19094. this._scene.layers.push(this);
  19095. // VBO
  19096. var vertices = [];
  19097. vertices.push(1, 1);
  19098. vertices.push(-1, 1);
  19099. vertices.push(-1, -1);
  19100. vertices.push(1, -1);
  19101. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19102. // Indices
  19103. var indices = [];
  19104. indices.push(0);
  19105. indices.push(1);
  19106. indices.push(2);
  19107. indices.push(0);
  19108. indices.push(2);
  19109. indices.push(3);
  19110. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19111. // Effects
  19112. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19113. }
  19114. Layer.prototype.render = function () {
  19115. // Check
  19116. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19117. return;
  19118. var engine = this._scene.getEngine();
  19119. // Render
  19120. engine.enableEffect(this._effect);
  19121. engine.setState(false);
  19122. // Texture
  19123. this._effect.setTexture("textureSampler", this.texture);
  19124. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19125. // Color
  19126. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19127. // VBOs
  19128. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19129. // Draw order
  19130. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19131. engine.draw(true, 0, 6);
  19132. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19133. };
  19134. Layer.prototype.dispose = function () {
  19135. if (this._vertexBuffer) {
  19136. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19137. this._vertexBuffer = null;
  19138. }
  19139. if (this._indexBuffer) {
  19140. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19141. this._indexBuffer = null;
  19142. }
  19143. if (this.texture) {
  19144. this.texture.dispose();
  19145. this.texture = null;
  19146. }
  19147. // Remove from scene
  19148. var index = this._scene.layers.indexOf(this);
  19149. this._scene.layers.splice(index, 1);
  19150. // Callback
  19151. if (this.onDispose) {
  19152. this.onDispose();
  19153. }
  19154. };
  19155. return Layer;
  19156. })();
  19157. BABYLON.Layer = Layer;
  19158. })(BABYLON || (BABYLON = {}));
  19159. //# sourceMappingURL=babylon.layer.js.map
  19160. var BABYLON;
  19161. (function (BABYLON) {
  19162. var Particle = (function () {
  19163. function Particle() {
  19164. this.position = BABYLON.Vector3.Zero();
  19165. this.direction = BABYLON.Vector3.Zero();
  19166. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19167. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19168. this.lifeTime = 1.0;
  19169. this.age = 0;
  19170. this.size = 0;
  19171. this.angle = 0;
  19172. this.angularSpeed = 0;
  19173. }
  19174. Particle.prototype.copyTo = function (other) {
  19175. other.position.copyFrom(this.position);
  19176. other.direction.copyFrom(this.direction);
  19177. other.color.copyFrom(this.color);
  19178. other.colorStep.copyFrom(this.colorStep);
  19179. other.lifeTime = this.lifeTime;
  19180. other.age = this.age;
  19181. other.size = this.size;
  19182. other.angle = this.angle;
  19183. other.angularSpeed = this.angularSpeed;
  19184. };
  19185. return Particle;
  19186. })();
  19187. BABYLON.Particle = Particle;
  19188. })(BABYLON || (BABYLON = {}));
  19189. //# sourceMappingURL=babylon.particle.js.map
  19190. var BABYLON;
  19191. (function (BABYLON) {
  19192. var randomNumber = function (min, max) {
  19193. if (min === max) {
  19194. return (min);
  19195. }
  19196. var random = Math.random();
  19197. return ((random * (max - min)) + min);
  19198. };
  19199. var ParticleSystem = (function () {
  19200. function ParticleSystem(name, capacity, scene, customEffect) {
  19201. var _this = this;
  19202. this.name = name;
  19203. this.renderingGroupId = 0;
  19204. this.emitter = null;
  19205. this.emitRate = 10;
  19206. this.manualEmitCount = -1;
  19207. this.updateSpeed = 0.01;
  19208. this.targetStopDuration = 0;
  19209. this.disposeOnStop = false;
  19210. this.minEmitPower = 1;
  19211. this.maxEmitPower = 1;
  19212. this.minLifeTime = 1;
  19213. this.maxLifeTime = 1;
  19214. this.minSize = 1;
  19215. this.maxSize = 1;
  19216. this.minAngularSpeed = 0;
  19217. this.maxAngularSpeed = 0;
  19218. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19219. this.forceDepthWrite = false;
  19220. this.gravity = BABYLON.Vector3.Zero();
  19221. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19222. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19223. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19224. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19225. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19226. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19227. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19228. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19229. this.particles = new Array();
  19230. this._vertexDeclaration = [3, 4, 4];
  19231. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19232. this._stockParticles = new Array();
  19233. this._newPartsExcess = 0;
  19234. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19235. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19236. this._scaledDirection = BABYLON.Vector3.Zero();
  19237. this._scaledGravity = BABYLON.Vector3.Zero();
  19238. this._currentRenderId = -1;
  19239. this._started = false;
  19240. this._stopped = false;
  19241. this._actualFrame = 0;
  19242. this.id = name;
  19243. this._capacity = capacity;
  19244. this._scene = scene;
  19245. this._customEffect = customEffect;
  19246. scene.particleSystems.push(this);
  19247. // VBO
  19248. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19249. var indices = [];
  19250. var index = 0;
  19251. for (var count = 0; count < capacity; count++) {
  19252. indices.push(index);
  19253. indices.push(index + 1);
  19254. indices.push(index + 2);
  19255. indices.push(index);
  19256. indices.push(index + 2);
  19257. indices.push(index + 3);
  19258. index += 4;
  19259. }
  19260. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19261. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19262. // Default behaviors
  19263. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19264. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19265. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19266. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19267. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19268. };
  19269. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19270. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19271. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19272. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19274. };
  19275. this.updateFunction = function (particles) {
  19276. for (var index = 0; index < particles.length; index++) {
  19277. var particle = particles[index];
  19278. particle.age += _this._scaledUpdateSpeed;
  19279. if (particle.age >= particle.lifeTime) {
  19280. _this.recycleParticle(particle);
  19281. index--;
  19282. continue;
  19283. }
  19284. else {
  19285. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19286. particle.color.addInPlace(_this._scaledColorStep);
  19287. if (particle.color.a < 0)
  19288. particle.color.a = 0;
  19289. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19290. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19291. particle.position.addInPlace(_this._scaledDirection);
  19292. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19293. particle.direction.addInPlace(_this._scaledGravity);
  19294. }
  19295. }
  19296. };
  19297. }
  19298. ParticleSystem.prototype.recycleParticle = function (particle) {
  19299. var lastParticle = this.particles.pop();
  19300. if (lastParticle !== particle) {
  19301. lastParticle.copyTo(particle);
  19302. this._stockParticles.push(lastParticle);
  19303. }
  19304. };
  19305. ParticleSystem.prototype.getCapacity = function () {
  19306. return this._capacity;
  19307. };
  19308. ParticleSystem.prototype.isAlive = function () {
  19309. return this._alive;
  19310. };
  19311. ParticleSystem.prototype.isStarted = function () {
  19312. return this._started;
  19313. };
  19314. ParticleSystem.prototype.start = function () {
  19315. this._started = true;
  19316. this._stopped = false;
  19317. this._actualFrame = 0;
  19318. };
  19319. ParticleSystem.prototype.stop = function () {
  19320. this._stopped = true;
  19321. };
  19322. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19323. var offset = index * 11;
  19324. this._vertices[offset] = particle.position.x;
  19325. this._vertices[offset + 1] = particle.position.y;
  19326. this._vertices[offset + 2] = particle.position.z;
  19327. this._vertices[offset + 3] = particle.color.r;
  19328. this._vertices[offset + 4] = particle.color.g;
  19329. this._vertices[offset + 5] = particle.color.b;
  19330. this._vertices[offset + 6] = particle.color.a;
  19331. this._vertices[offset + 7] = particle.angle;
  19332. this._vertices[offset + 8] = particle.size;
  19333. this._vertices[offset + 9] = offsetX;
  19334. this._vertices[offset + 10] = offsetY;
  19335. };
  19336. ParticleSystem.prototype._update = function (newParticles) {
  19337. // Update current
  19338. this._alive = this.particles.length > 0;
  19339. this.updateFunction(this.particles);
  19340. // Add new ones
  19341. var worldMatrix;
  19342. if (this.emitter.position) {
  19343. worldMatrix = this.emitter.getWorldMatrix();
  19344. }
  19345. else {
  19346. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19347. }
  19348. for (var index = 0; index < newParticles; index++) {
  19349. if (this.particles.length === this._capacity) {
  19350. break;
  19351. }
  19352. if (this._stockParticles.length !== 0) {
  19353. var particle = this._stockParticles.pop();
  19354. particle.age = 0;
  19355. }
  19356. else {
  19357. particle = new BABYLON.Particle();
  19358. }
  19359. this.particles.push(particle);
  19360. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19361. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19362. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19363. particle.size = randomNumber(this.minSize, this.maxSize);
  19364. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19365. this.startPositionFunction(worldMatrix, particle.position);
  19366. var step = randomNumber(0, 1.0);
  19367. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19368. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19369. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19370. }
  19371. };
  19372. ParticleSystem.prototype._getEffect = function () {
  19373. if (this._customEffect) {
  19374. return this._customEffect;
  19375. }
  19376. ;
  19377. var defines = [];
  19378. if (this._scene.clipPlane) {
  19379. defines.push("#define CLIPPLANE");
  19380. }
  19381. // Effect
  19382. var join = defines.join("\n");
  19383. if (this._cachedDefines !== join) {
  19384. this._cachedDefines = join;
  19385. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19386. }
  19387. return this._effect;
  19388. };
  19389. ParticleSystem.prototype.animate = function () {
  19390. if (!this._started)
  19391. return;
  19392. var effect = this._getEffect();
  19393. // Check
  19394. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19395. return;
  19396. if (this._currentRenderId === this._scene.getRenderId()) {
  19397. return;
  19398. }
  19399. this._currentRenderId = this._scene.getRenderId();
  19400. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19401. // determine the number of particles we need to create
  19402. var emitCout;
  19403. if (this.manualEmitCount > -1) {
  19404. emitCout = this.manualEmitCount;
  19405. this.manualEmitCount = 0;
  19406. }
  19407. else {
  19408. emitCout = this.emitRate;
  19409. }
  19410. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19411. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19412. if (this._newPartsExcess > 1.0) {
  19413. newParticles += this._newPartsExcess >> 0;
  19414. this._newPartsExcess -= this._newPartsExcess >> 0;
  19415. }
  19416. this._alive = false;
  19417. if (!this._stopped) {
  19418. this._actualFrame += this._scaledUpdateSpeed;
  19419. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19420. this.stop();
  19421. }
  19422. else {
  19423. newParticles = 0;
  19424. }
  19425. this._update(newParticles);
  19426. // Stopped?
  19427. if (this._stopped) {
  19428. if (!this._alive) {
  19429. this._started = false;
  19430. if (this.disposeOnStop) {
  19431. this._scene._toBeDisposed.push(this);
  19432. }
  19433. }
  19434. }
  19435. // Update VBO
  19436. var offset = 0;
  19437. for (var index = 0; index < this.particles.length; index++) {
  19438. var particle = this.particles[index];
  19439. this._appendParticleVertex(offset++, particle, 0, 0);
  19440. this._appendParticleVertex(offset++, particle, 1, 0);
  19441. this._appendParticleVertex(offset++, particle, 1, 1);
  19442. this._appendParticleVertex(offset++, particle, 0, 1);
  19443. }
  19444. var engine = this._scene.getEngine();
  19445. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19446. };
  19447. ParticleSystem.prototype.render = function () {
  19448. var effect = this._getEffect();
  19449. // Check
  19450. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19451. return 0;
  19452. var engine = this._scene.getEngine();
  19453. // Render
  19454. engine.enableEffect(effect);
  19455. engine.setState(false);
  19456. var viewMatrix = this._scene.getViewMatrix();
  19457. effect.setTexture("diffuseSampler", this.particleTexture);
  19458. effect.setMatrix("view", viewMatrix);
  19459. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19460. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19461. if (this._scene.clipPlane) {
  19462. var clipPlane = this._scene.clipPlane;
  19463. var invView = viewMatrix.clone();
  19464. invView.invert();
  19465. effect.setMatrix("invView", invView);
  19466. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19467. }
  19468. // VBOs
  19469. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19470. // Draw order
  19471. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19472. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19473. }
  19474. else {
  19475. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19476. }
  19477. if (this.forceDepthWrite) {
  19478. engine.setDepthWrite(true);
  19479. }
  19480. engine.draw(true, 0, this.particles.length * 6);
  19481. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19482. return this.particles.length;
  19483. };
  19484. ParticleSystem.prototype.dispose = function () {
  19485. if (this._vertexBuffer) {
  19486. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19487. this._vertexBuffer = null;
  19488. }
  19489. if (this._indexBuffer) {
  19490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19491. this._indexBuffer = null;
  19492. }
  19493. if (this.particleTexture) {
  19494. this.particleTexture.dispose();
  19495. this.particleTexture = null;
  19496. }
  19497. // Remove from scene
  19498. var index = this._scene.particleSystems.indexOf(this);
  19499. this._scene.particleSystems.splice(index, 1);
  19500. // Callback
  19501. if (this.onDispose) {
  19502. this.onDispose();
  19503. }
  19504. };
  19505. // Clone
  19506. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19507. var result = new ParticleSystem(name, this._capacity, this._scene);
  19508. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19509. if (newEmitter === undefined) {
  19510. newEmitter = this.emitter;
  19511. }
  19512. result.emitter = newEmitter;
  19513. if (this.particleTexture) {
  19514. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19515. }
  19516. result.start();
  19517. return result;
  19518. };
  19519. // Statics
  19520. ParticleSystem.BLENDMODE_ONEONE = 0;
  19521. ParticleSystem.BLENDMODE_STANDARD = 1;
  19522. return ParticleSystem;
  19523. })();
  19524. BABYLON.ParticleSystem = ParticleSystem;
  19525. })(BABYLON || (BABYLON = {}));
  19526. //# sourceMappingURL=babylon.particleSystem.js.map
  19527. var BABYLON;
  19528. (function (BABYLON) {
  19529. var Animation = (function () {
  19530. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19531. this.name = name;
  19532. this.targetProperty = targetProperty;
  19533. this.framePerSecond = framePerSecond;
  19534. this.dataType = dataType;
  19535. this.loopMode = loopMode;
  19536. this._offsetsCache = {};
  19537. this._highLimitsCache = {};
  19538. this._stopped = false;
  19539. this.targetPropertyPath = targetProperty.split(".");
  19540. this.dataType = dataType;
  19541. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19542. }
  19543. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19544. var dataType = undefined;
  19545. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19546. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19547. }
  19548. else if (from instanceof BABYLON.Quaternion) {
  19549. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19550. }
  19551. else if (from instanceof BABYLON.Vector3) {
  19552. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19553. }
  19554. else if (from instanceof BABYLON.Vector2) {
  19555. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19556. }
  19557. else if (from instanceof BABYLON.Color3) {
  19558. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19559. }
  19560. if (dataType == undefined) {
  19561. return null;
  19562. }
  19563. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19564. var keys = [];
  19565. keys.push({ frame: 0, value: from });
  19566. keys.push({ frame: totalFrame, value: to });
  19567. animation.setKeys(keys);
  19568. mesh.animations.push(animation);
  19569. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19570. };
  19571. // Methods
  19572. Animation.prototype.isStopped = function () {
  19573. return this._stopped;
  19574. };
  19575. Animation.prototype.getKeys = function () {
  19576. return this._keys;
  19577. };
  19578. Animation.prototype.getEasingFunction = function () {
  19579. return this._easingFunction;
  19580. };
  19581. Animation.prototype.setEasingFunction = function (easingFunction) {
  19582. this._easingFunction = easingFunction;
  19583. };
  19584. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19585. return startValue + (endValue - startValue) * gradient;
  19586. };
  19587. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19588. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19589. };
  19590. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19591. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19592. };
  19593. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19594. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19595. };
  19596. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19597. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19598. };
  19599. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19600. var startScale = new BABYLON.Vector3(0, 0, 0);
  19601. var startRotation = new BABYLON.Quaternion();
  19602. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19603. startValue.decompose(startScale, startRotation, startTranslation);
  19604. var endScale = new BABYLON.Vector3(0, 0, 0);
  19605. var endRotation = new BABYLON.Quaternion();
  19606. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19607. endValue.decompose(endScale, endRotation, endTranslation);
  19608. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  19609. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  19610. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  19611. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  19612. return result;
  19613. };
  19614. Animation.prototype.clone = function () {
  19615. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  19616. clone.setKeys(this._keys);
  19617. return clone;
  19618. };
  19619. Animation.prototype.setKeys = function (values) {
  19620. this._keys = values.slice(0);
  19621. this._offsetsCache = {};
  19622. this._highLimitsCache = {};
  19623. };
  19624. Animation.prototype._getKeyValue = function (value) {
  19625. if (typeof value === "function") {
  19626. return value();
  19627. }
  19628. return value;
  19629. };
  19630. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  19631. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  19632. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  19633. }
  19634. this.currentFrame = currentFrame;
  19635. // Try to get a hash to find the right key
  19636. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  19637. if (this._keys[startKey].frame >= currentFrame) {
  19638. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  19639. startKey--;
  19640. }
  19641. }
  19642. for (var key = startKey; key < this._keys.length; key++) {
  19643. if (this._keys[key + 1].frame >= currentFrame) {
  19644. var startValue = this._getKeyValue(this._keys[key].value);
  19645. var endValue = this._getKeyValue(this._keys[key + 1].value);
  19646. // gradient : percent of currentFrame between the frame inf and the frame sup
  19647. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  19648. // check for easingFunction and correction of gradient
  19649. if (this._easingFunction != null) {
  19650. gradient = this._easingFunction.ease(gradient);
  19651. }
  19652. switch (this.dataType) {
  19653. case Animation.ANIMATIONTYPE_FLOAT:
  19654. switch (loopMode) {
  19655. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19656. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19657. return this.floatInterpolateFunction(startValue, endValue, gradient);
  19658. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19659. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  19660. }
  19661. break;
  19662. case Animation.ANIMATIONTYPE_QUATERNION:
  19663. var quaternion = null;
  19664. switch (loopMode) {
  19665. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19666. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19667. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  19668. break;
  19669. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19670. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19671. break;
  19672. }
  19673. return quaternion;
  19674. case Animation.ANIMATIONTYPE_VECTOR3:
  19675. switch (loopMode) {
  19676. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19677. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19678. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  19679. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19680. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19681. }
  19682. case Animation.ANIMATIONTYPE_VECTOR2:
  19683. switch (loopMode) {
  19684. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19685. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19686. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  19687. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19688. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19689. }
  19690. case Animation.ANIMATIONTYPE_COLOR3:
  19691. switch (loopMode) {
  19692. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19693. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19694. return this.color3InterpolateFunction(startValue, endValue, gradient);
  19695. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19696. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19697. }
  19698. case Animation.ANIMATIONTYPE_MATRIX:
  19699. switch (loopMode) {
  19700. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19701. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19702. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19703. return startValue;
  19704. }
  19705. default:
  19706. break;
  19707. }
  19708. break;
  19709. }
  19710. }
  19711. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  19712. };
  19713. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  19714. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  19715. this._stopped = true;
  19716. return false;
  19717. }
  19718. var returnValue = true;
  19719. // Adding a start key at frame 0 if missing
  19720. if (this._keys[0].frame !== 0) {
  19721. var newKey = { frame: 0, value: this._keys[0].value };
  19722. this._keys.splice(0, 0, newKey);
  19723. }
  19724. // Check limits
  19725. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  19726. from = this._keys[0].frame;
  19727. }
  19728. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  19729. to = this._keys[this._keys.length - 1].frame;
  19730. }
  19731. // Compute ratio
  19732. var range = to - from;
  19733. var offsetValue;
  19734. // ratio represents the frame delta between from and to
  19735. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  19736. var highLimitValue = 0;
  19737. if (ratio > range && !loop) {
  19738. returnValue = false;
  19739. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  19740. }
  19741. else {
  19742. // Get max value if required
  19743. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  19744. var keyOffset = to.toString() + from.toString();
  19745. if (!this._offsetsCache[keyOffset]) {
  19746. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19747. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19748. switch (this.dataType) {
  19749. case Animation.ANIMATIONTYPE_FLOAT:
  19750. this._offsetsCache[keyOffset] = toValue - fromValue;
  19751. break;
  19752. case Animation.ANIMATIONTYPE_QUATERNION:
  19753. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19754. break;
  19755. case Animation.ANIMATIONTYPE_VECTOR3:
  19756. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19757. case Animation.ANIMATIONTYPE_VECTOR2:
  19758. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19759. case Animation.ANIMATIONTYPE_COLOR3:
  19760. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19761. default:
  19762. break;
  19763. }
  19764. this._highLimitsCache[keyOffset] = toValue;
  19765. }
  19766. highLimitValue = this._highLimitsCache[keyOffset];
  19767. offsetValue = this._offsetsCache[keyOffset];
  19768. }
  19769. }
  19770. if (offsetValue === undefined) {
  19771. switch (this.dataType) {
  19772. case Animation.ANIMATIONTYPE_FLOAT:
  19773. offsetValue = 0;
  19774. break;
  19775. case Animation.ANIMATIONTYPE_QUATERNION:
  19776. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  19777. break;
  19778. case Animation.ANIMATIONTYPE_VECTOR3:
  19779. offsetValue = BABYLON.Vector3.Zero();
  19780. break;
  19781. case Animation.ANIMATIONTYPE_VECTOR2:
  19782. offsetValue = BABYLON.Vector2.Zero();
  19783. break;
  19784. case Animation.ANIMATIONTYPE_COLOR3:
  19785. offsetValue = BABYLON.Color3.Black();
  19786. }
  19787. }
  19788. // Compute value
  19789. var repeatCount = (ratio / range) >> 0;
  19790. var currentFrame = returnValue ? from + ratio % range : to;
  19791. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  19792. // Set value
  19793. if (this.targetPropertyPath.length > 1) {
  19794. var property = this._target[this.targetPropertyPath[0]];
  19795. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  19796. property = property[this.targetPropertyPath[index]];
  19797. }
  19798. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  19799. }
  19800. else {
  19801. this._target[this.targetPropertyPath[0]] = currentValue;
  19802. }
  19803. if (this._target.markAsDirty) {
  19804. this._target.markAsDirty(this.targetProperty);
  19805. }
  19806. if (!returnValue) {
  19807. this._stopped = true;
  19808. }
  19809. return returnValue;
  19810. };
  19811. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  19812. get: function () {
  19813. return Animation._ANIMATIONTYPE_FLOAT;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  19819. get: function () {
  19820. return Animation._ANIMATIONTYPE_VECTOR3;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  19826. get: function () {
  19827. return Animation._ANIMATIONTYPE_VECTOR2;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  19833. get: function () {
  19834. return Animation._ANIMATIONTYPE_QUATERNION;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  19840. get: function () {
  19841. return Animation._ANIMATIONTYPE_MATRIX;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  19847. get: function () {
  19848. return Animation._ANIMATIONTYPE_COLOR3;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  19854. get: function () {
  19855. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  19861. get: function () {
  19862. return Animation._ANIMATIONLOOPMODE_CYCLE;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  19868. get: function () {
  19869. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. // Statics
  19875. Animation._ANIMATIONTYPE_FLOAT = 0;
  19876. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  19877. Animation._ANIMATIONTYPE_QUATERNION = 2;
  19878. Animation._ANIMATIONTYPE_MATRIX = 3;
  19879. Animation._ANIMATIONTYPE_COLOR3 = 4;
  19880. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  19881. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  19882. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  19883. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  19884. return Animation;
  19885. })();
  19886. BABYLON.Animation = Animation;
  19887. })(BABYLON || (BABYLON = {}));
  19888. //# sourceMappingURL=babylon.animation.js.map
  19889. var BABYLON;
  19890. (function (BABYLON) {
  19891. var Animatable = (function () {
  19892. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  19893. if (fromFrame === void 0) { fromFrame = 0; }
  19894. if (toFrame === void 0) { toFrame = 100; }
  19895. if (loopAnimation === void 0) { loopAnimation = false; }
  19896. if (speedRatio === void 0) { speedRatio = 1.0; }
  19897. this.target = target;
  19898. this.fromFrame = fromFrame;
  19899. this.toFrame = toFrame;
  19900. this.loopAnimation = loopAnimation;
  19901. this.speedRatio = speedRatio;
  19902. this.onAnimationEnd = onAnimationEnd;
  19903. this._animations = new Array();
  19904. this._paused = false;
  19905. this.animationStarted = false;
  19906. if (animations) {
  19907. this.appendAnimations(target, animations);
  19908. }
  19909. this._scene = scene;
  19910. scene._activeAnimatables.push(this);
  19911. }
  19912. // Methods
  19913. Animatable.prototype.appendAnimations = function (target, animations) {
  19914. for (var index = 0; index < animations.length; index++) {
  19915. var animation = animations[index];
  19916. animation._target = target;
  19917. this._animations.push(animation);
  19918. }
  19919. };
  19920. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  19921. var animations = this._animations;
  19922. for (var index = 0; index < animations.length; index++) {
  19923. if (animations[index].targetProperty === property) {
  19924. return animations[index];
  19925. }
  19926. }
  19927. return null;
  19928. };
  19929. Animatable.prototype.pause = function () {
  19930. if (this._paused) {
  19931. return;
  19932. }
  19933. this._paused = true;
  19934. };
  19935. Animatable.prototype.restart = function () {
  19936. this._paused = false;
  19937. };
  19938. Animatable.prototype.stop = function () {
  19939. var index = this._scene._activeAnimatables.indexOf(this);
  19940. if (index > -1) {
  19941. this._scene._activeAnimatables.splice(index, 1);
  19942. }
  19943. if (this.onAnimationEnd) {
  19944. this.onAnimationEnd();
  19945. }
  19946. };
  19947. Animatable.prototype._animate = function (delay) {
  19948. if (this._paused) {
  19949. if (!this._pausedDelay) {
  19950. this._pausedDelay = delay;
  19951. }
  19952. return true;
  19953. }
  19954. if (!this._localDelayOffset) {
  19955. this._localDelayOffset = delay;
  19956. }
  19957. else if (this._pausedDelay) {
  19958. this._localDelayOffset += delay - this._pausedDelay;
  19959. this._pausedDelay = null;
  19960. }
  19961. // Animating
  19962. var running = false;
  19963. var animations = this._animations;
  19964. for (var index = 0; index < animations.length; index++) {
  19965. var animation = animations[index];
  19966. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  19967. running = running || isRunning;
  19968. }
  19969. if (!running) {
  19970. // Remove from active animatables
  19971. index = this._scene._activeAnimatables.indexOf(this);
  19972. this._scene._activeAnimatables.splice(index, 1);
  19973. }
  19974. if (!running && this.onAnimationEnd) {
  19975. this.onAnimationEnd();
  19976. }
  19977. return running;
  19978. };
  19979. return Animatable;
  19980. })();
  19981. BABYLON.Animatable = Animatable;
  19982. })(BABYLON || (BABYLON = {}));
  19983. //# sourceMappingURL=babylon.animatable.js.map
  19984. var __extends = this.__extends || function (d, b) {
  19985. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19986. function __() { this.constructor = d; }
  19987. __.prototype = b.prototype;
  19988. d.prototype = new __();
  19989. };
  19990. var BABYLON;
  19991. (function (BABYLON) {
  19992. var EasingFunction = (function () {
  19993. function EasingFunction() {
  19994. // Properties
  19995. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  19996. }
  19997. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  19998. get: function () {
  19999. return EasingFunction._EASINGMODE_EASEIN;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  20005. get: function () {
  20006. return EasingFunction._EASINGMODE_EASEOUT;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  20012. get: function () {
  20013. return EasingFunction._EASINGMODE_EASEINOUT;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. EasingFunction.prototype.setEasingMode = function (easingMode) {
  20019. var n = Math.min(Math.max(easingMode, 0), 2);
  20020. this._easingMode = n;
  20021. };
  20022. EasingFunction.prototype.getEasingMode = function () {
  20023. return this._easingMode;
  20024. };
  20025. EasingFunction.prototype.easeInCore = function (gradient) {
  20026. throw new Error('You must implement this method');
  20027. };
  20028. EasingFunction.prototype.ease = function (gradient) {
  20029. switch (this._easingMode) {
  20030. case EasingFunction.EASINGMODE_EASEIN:
  20031. return this.easeInCore(gradient);
  20032. case EasingFunction.EASINGMODE_EASEOUT:
  20033. return (1 - this.easeInCore(1 - gradient));
  20034. }
  20035. if (gradient >= 0.5) {
  20036. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20037. }
  20038. return (this.easeInCore(gradient * 2) * 0.5);
  20039. };
  20040. //Statics
  20041. EasingFunction._EASINGMODE_EASEIN = 0;
  20042. EasingFunction._EASINGMODE_EASEOUT = 1;
  20043. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20044. return EasingFunction;
  20045. })();
  20046. BABYLON.EasingFunction = EasingFunction;
  20047. var CircleEase = (function (_super) {
  20048. __extends(CircleEase, _super);
  20049. function CircleEase() {
  20050. _super.apply(this, arguments);
  20051. }
  20052. CircleEase.prototype.easeInCore = function (gradient) {
  20053. gradient = Math.max(0, Math.min(1, gradient));
  20054. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20055. };
  20056. return CircleEase;
  20057. })(EasingFunction);
  20058. BABYLON.CircleEase = CircleEase;
  20059. var BackEase = (function (_super) {
  20060. __extends(BackEase, _super);
  20061. function BackEase(amplitude) {
  20062. if (amplitude === void 0) { amplitude = 1; }
  20063. _super.call(this);
  20064. this.amplitude = amplitude;
  20065. }
  20066. BackEase.prototype.easeInCore = function (gradient) {
  20067. var num = Math.max(0, this.amplitude);
  20068. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20069. };
  20070. return BackEase;
  20071. })(EasingFunction);
  20072. BABYLON.BackEase = BackEase;
  20073. var BounceEase = (function (_super) {
  20074. __extends(BounceEase, _super);
  20075. function BounceEase(bounces, bounciness) {
  20076. if (bounces === void 0) { bounces = 3; }
  20077. if (bounciness === void 0) { bounciness = 2; }
  20078. _super.call(this);
  20079. this.bounces = bounces;
  20080. this.bounciness = bounciness;
  20081. }
  20082. BounceEase.prototype.easeInCore = function (gradient) {
  20083. var y = Math.max(0.0, this.bounces);
  20084. var bounciness = this.bounciness;
  20085. if (bounciness <= 1.0) {
  20086. bounciness = 1.001;
  20087. }
  20088. var num9 = Math.pow(bounciness, y);
  20089. var num5 = 1.0 - bounciness;
  20090. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20091. var num15 = gradient * num4;
  20092. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20093. var num3 = Math.floor(num65);
  20094. var num13 = num3 + 1.0;
  20095. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20096. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20097. var num7 = (num8 + num12) * 0.5;
  20098. var num6 = gradient - num7;
  20099. var num2 = num7 - num8;
  20100. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20101. };
  20102. return BounceEase;
  20103. })(EasingFunction);
  20104. BABYLON.BounceEase = BounceEase;
  20105. var CubicEase = (function (_super) {
  20106. __extends(CubicEase, _super);
  20107. function CubicEase() {
  20108. _super.apply(this, arguments);
  20109. }
  20110. CubicEase.prototype.easeInCore = function (gradient) {
  20111. return (gradient * gradient * gradient);
  20112. };
  20113. return CubicEase;
  20114. })(EasingFunction);
  20115. BABYLON.CubicEase = CubicEase;
  20116. var ElasticEase = (function (_super) {
  20117. __extends(ElasticEase, _super);
  20118. function ElasticEase(oscillations, springiness) {
  20119. if (oscillations === void 0) { oscillations = 3; }
  20120. if (springiness === void 0) { springiness = 3; }
  20121. _super.call(this);
  20122. this.oscillations = oscillations;
  20123. this.springiness = springiness;
  20124. }
  20125. ElasticEase.prototype.easeInCore = function (gradient) {
  20126. var num2;
  20127. var num3 = Math.max(0.0, this.oscillations);
  20128. var num = Math.max(0.0, this.springiness);
  20129. if (num == 0) {
  20130. num2 = gradient;
  20131. }
  20132. else {
  20133. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20134. }
  20135. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20136. };
  20137. return ElasticEase;
  20138. })(EasingFunction);
  20139. BABYLON.ElasticEase = ElasticEase;
  20140. var ExponentialEase = (function (_super) {
  20141. __extends(ExponentialEase, _super);
  20142. function ExponentialEase(exponent) {
  20143. if (exponent === void 0) { exponent = 2; }
  20144. _super.call(this);
  20145. this.exponent = exponent;
  20146. }
  20147. ExponentialEase.prototype.easeInCore = function (gradient) {
  20148. if (this.exponent <= 0) {
  20149. return gradient;
  20150. }
  20151. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20152. };
  20153. return ExponentialEase;
  20154. })(EasingFunction);
  20155. BABYLON.ExponentialEase = ExponentialEase;
  20156. var PowerEase = (function (_super) {
  20157. __extends(PowerEase, _super);
  20158. function PowerEase(power) {
  20159. if (power === void 0) { power = 2; }
  20160. _super.call(this);
  20161. this.power = power;
  20162. }
  20163. PowerEase.prototype.easeInCore = function (gradient) {
  20164. var y = Math.max(0.0, this.power);
  20165. return Math.pow(gradient, y);
  20166. };
  20167. return PowerEase;
  20168. })(EasingFunction);
  20169. BABYLON.PowerEase = PowerEase;
  20170. var QuadraticEase = (function (_super) {
  20171. __extends(QuadraticEase, _super);
  20172. function QuadraticEase() {
  20173. _super.apply(this, arguments);
  20174. }
  20175. QuadraticEase.prototype.easeInCore = function (gradient) {
  20176. return (gradient * gradient);
  20177. };
  20178. return QuadraticEase;
  20179. })(EasingFunction);
  20180. BABYLON.QuadraticEase = QuadraticEase;
  20181. var QuarticEase = (function (_super) {
  20182. __extends(QuarticEase, _super);
  20183. function QuarticEase() {
  20184. _super.apply(this, arguments);
  20185. }
  20186. QuarticEase.prototype.easeInCore = function (gradient) {
  20187. return (gradient * gradient * gradient * gradient);
  20188. };
  20189. return QuarticEase;
  20190. })(EasingFunction);
  20191. BABYLON.QuarticEase = QuarticEase;
  20192. var QuinticEase = (function (_super) {
  20193. __extends(QuinticEase, _super);
  20194. function QuinticEase() {
  20195. _super.apply(this, arguments);
  20196. }
  20197. QuinticEase.prototype.easeInCore = function (gradient) {
  20198. return (gradient * gradient * gradient * gradient * gradient);
  20199. };
  20200. return QuinticEase;
  20201. })(EasingFunction);
  20202. BABYLON.QuinticEase = QuinticEase;
  20203. var SineEase = (function (_super) {
  20204. __extends(SineEase, _super);
  20205. function SineEase() {
  20206. _super.apply(this, arguments);
  20207. }
  20208. SineEase.prototype.easeInCore = function (gradient) {
  20209. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20210. };
  20211. return SineEase;
  20212. })(EasingFunction);
  20213. BABYLON.SineEase = SineEase;
  20214. var BezierCurveEase = (function (_super) {
  20215. __extends(BezierCurveEase, _super);
  20216. function BezierCurveEase(x1, y1, x2, y2) {
  20217. if (x1 === void 0) { x1 = 0; }
  20218. if (y1 === void 0) { y1 = 0; }
  20219. if (x2 === void 0) { x2 = 1; }
  20220. if (y2 === void 0) { y2 = 1; }
  20221. _super.call(this);
  20222. this.x1 = x1;
  20223. this.y1 = y1;
  20224. this.x2 = x2;
  20225. this.y2 = y2;
  20226. }
  20227. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20228. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20229. };
  20230. return BezierCurveEase;
  20231. })(EasingFunction);
  20232. BABYLON.BezierCurveEase = BezierCurveEase;
  20233. })(BABYLON || (BABYLON = {}));
  20234. //# sourceMappingURL=babylon.easing.js.map
  20235. var BABYLON;
  20236. (function (BABYLON) {
  20237. var Octree = (function () {
  20238. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20239. if (maxDepth === void 0) { maxDepth = 2; }
  20240. this.maxDepth = maxDepth;
  20241. this.dynamicContent = new Array();
  20242. this._maxBlockCapacity = maxBlockCapacity || 64;
  20243. this._selectionContent = new BABYLON.SmartArray(1024);
  20244. this._creationFunc = creationFunc;
  20245. }
  20246. // Methods
  20247. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20248. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20249. };
  20250. Octree.prototype.addMesh = function (entry) {
  20251. for (var index = 0; index < this.blocks.length; index++) {
  20252. var block = this.blocks[index];
  20253. block.addEntry(entry);
  20254. }
  20255. };
  20256. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20257. this._selectionContent.reset();
  20258. for (var index = 0; index < this.blocks.length; index++) {
  20259. var block = this.blocks[index];
  20260. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20261. }
  20262. if (allowDuplicate) {
  20263. this._selectionContent.concat(this.dynamicContent);
  20264. }
  20265. else {
  20266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20267. }
  20268. return this._selectionContent;
  20269. };
  20270. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20271. this._selectionContent.reset();
  20272. for (var index = 0; index < this.blocks.length; index++) {
  20273. var block = this.blocks[index];
  20274. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20275. }
  20276. if (allowDuplicate) {
  20277. this._selectionContent.concat(this.dynamicContent);
  20278. }
  20279. else {
  20280. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20281. }
  20282. return this._selectionContent;
  20283. };
  20284. Octree.prototype.intersectsRay = function (ray) {
  20285. this._selectionContent.reset();
  20286. for (var index = 0; index < this.blocks.length; index++) {
  20287. var block = this.blocks[index];
  20288. block.intersectsRay(ray, this._selectionContent);
  20289. }
  20290. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20291. return this._selectionContent;
  20292. };
  20293. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20294. target.blocks = new Array();
  20295. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20296. for (var x = 0; x < 2; x++) {
  20297. for (var y = 0; y < 2; y++) {
  20298. for (var z = 0; z < 2; z++) {
  20299. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20300. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20301. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20302. block.addEntries(entries);
  20303. target.blocks.push(block);
  20304. }
  20305. }
  20306. }
  20307. };
  20308. Octree.CreationFuncForMeshes = function (entry, block) {
  20309. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20310. block.entries.push(entry);
  20311. }
  20312. };
  20313. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20314. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20315. block.entries.push(entry);
  20316. }
  20317. };
  20318. return Octree;
  20319. })();
  20320. BABYLON.Octree = Octree;
  20321. })(BABYLON || (BABYLON = {}));
  20322. //# sourceMappingURL=babylon.octree.js.map
  20323. var BABYLON;
  20324. (function (BABYLON) {
  20325. var OctreeBlock = (function () {
  20326. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20327. this.entries = new Array();
  20328. this._boundingVectors = new Array();
  20329. this._capacity = capacity;
  20330. this._depth = depth;
  20331. this._maxDepth = maxDepth;
  20332. this._creationFunc = creationFunc;
  20333. this._minPoint = minPoint;
  20334. this._maxPoint = maxPoint;
  20335. this._boundingVectors.push(minPoint.clone());
  20336. this._boundingVectors.push(maxPoint.clone());
  20337. this._boundingVectors.push(minPoint.clone());
  20338. this._boundingVectors[2].x = maxPoint.x;
  20339. this._boundingVectors.push(minPoint.clone());
  20340. this._boundingVectors[3].y = maxPoint.y;
  20341. this._boundingVectors.push(minPoint.clone());
  20342. this._boundingVectors[4].z = maxPoint.z;
  20343. this._boundingVectors.push(maxPoint.clone());
  20344. this._boundingVectors[5].z = minPoint.z;
  20345. this._boundingVectors.push(maxPoint.clone());
  20346. this._boundingVectors[6].x = minPoint.x;
  20347. this._boundingVectors.push(maxPoint.clone());
  20348. this._boundingVectors[7].y = minPoint.y;
  20349. }
  20350. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20351. // Property
  20352. get: function () {
  20353. return this._capacity;
  20354. },
  20355. enumerable: true,
  20356. configurable: true
  20357. });
  20358. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20359. get: function () {
  20360. return this._minPoint;
  20361. },
  20362. enumerable: true,
  20363. configurable: true
  20364. });
  20365. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20366. get: function () {
  20367. return this._maxPoint;
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. // Methods
  20373. OctreeBlock.prototype.addEntry = function (entry) {
  20374. if (this.blocks) {
  20375. for (var index = 0; index < this.blocks.length; index++) {
  20376. var block = this.blocks[index];
  20377. block.addEntry(entry);
  20378. }
  20379. return;
  20380. }
  20381. this._creationFunc(entry, this);
  20382. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20383. this.createInnerBlocks();
  20384. }
  20385. };
  20386. OctreeBlock.prototype.addEntries = function (entries) {
  20387. for (var index = 0; index < entries.length; index++) {
  20388. var mesh = entries[index];
  20389. this.addEntry(mesh);
  20390. }
  20391. };
  20392. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20393. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20394. if (this.blocks) {
  20395. for (var index = 0; index < this.blocks.length; index++) {
  20396. var block = this.blocks[index];
  20397. block.select(frustumPlanes, selection, allowDuplicate);
  20398. }
  20399. return;
  20400. }
  20401. if (allowDuplicate) {
  20402. selection.concat(this.entries);
  20403. }
  20404. else {
  20405. selection.concatWithNoDuplicate(this.entries);
  20406. }
  20407. }
  20408. };
  20409. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20410. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20411. if (this.blocks) {
  20412. for (var index = 0; index < this.blocks.length; index++) {
  20413. var block = this.blocks[index];
  20414. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20415. }
  20416. return;
  20417. }
  20418. if (allowDuplicate) {
  20419. selection.concat(this.entries);
  20420. }
  20421. else {
  20422. selection.concatWithNoDuplicate(this.entries);
  20423. }
  20424. }
  20425. };
  20426. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20427. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20428. if (this.blocks) {
  20429. for (var index = 0; index < this.blocks.length; index++) {
  20430. var block = this.blocks[index];
  20431. block.intersectsRay(ray, selection);
  20432. }
  20433. return;
  20434. }
  20435. selection.concatWithNoDuplicate(this.entries);
  20436. }
  20437. };
  20438. OctreeBlock.prototype.createInnerBlocks = function () {
  20439. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20440. };
  20441. return OctreeBlock;
  20442. })();
  20443. BABYLON.OctreeBlock = OctreeBlock;
  20444. })(BABYLON || (BABYLON = {}));
  20445. //# sourceMappingURL=babylon.octreeBlock.js.map
  20446. var BABYLON;
  20447. (function (BABYLON) {
  20448. var Bone = (function () {
  20449. function Bone(name, skeleton, parentBone, matrix) {
  20450. this.name = name;
  20451. this.children = new Array();
  20452. this.animations = new Array();
  20453. this._worldTransform = new BABYLON.Matrix();
  20454. this._absoluteTransform = new BABYLON.Matrix();
  20455. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20456. this._skeleton = skeleton;
  20457. this._matrix = matrix;
  20458. this._baseMatrix = matrix;
  20459. skeleton.bones.push(this);
  20460. if (parentBone) {
  20461. this._parent = parentBone;
  20462. parentBone.children.push(this);
  20463. }
  20464. else {
  20465. this._parent = null;
  20466. }
  20467. this._updateDifferenceMatrix();
  20468. }
  20469. // Members
  20470. Bone.prototype.getParent = function () {
  20471. return this._parent;
  20472. };
  20473. Bone.prototype.getLocalMatrix = function () {
  20474. return this._matrix;
  20475. };
  20476. Bone.prototype.getBaseMatrix = function () {
  20477. return this._baseMatrix;
  20478. };
  20479. Bone.prototype.getWorldMatrix = function () {
  20480. return this._worldTransform;
  20481. };
  20482. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20483. return this._invertedAbsoluteTransform;
  20484. };
  20485. Bone.prototype.getAbsoluteMatrix = function () {
  20486. var matrix = this._matrix.clone();
  20487. var parent = this._parent;
  20488. while (parent) {
  20489. matrix = matrix.multiply(parent.getLocalMatrix());
  20490. parent = parent.getParent();
  20491. }
  20492. return matrix;
  20493. };
  20494. // Methods
  20495. Bone.prototype.updateMatrix = function (matrix) {
  20496. this._matrix = matrix;
  20497. this._skeleton._markAsDirty();
  20498. this._updateDifferenceMatrix();
  20499. };
  20500. Bone.prototype._updateDifferenceMatrix = function () {
  20501. if (this._parent) {
  20502. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20503. }
  20504. else {
  20505. this._absoluteTransform.copyFrom(this._matrix);
  20506. }
  20507. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20508. for (var index = 0; index < this.children.length; index++) {
  20509. this.children[index]._updateDifferenceMatrix();
  20510. }
  20511. };
  20512. Bone.prototype.markAsDirty = function () {
  20513. this._skeleton._markAsDirty();
  20514. };
  20515. return Bone;
  20516. })();
  20517. BABYLON.Bone = Bone;
  20518. })(BABYLON || (BABYLON = {}));
  20519. //# sourceMappingURL=babylon.bone.js.map
  20520. var BABYLON;
  20521. (function (BABYLON) {
  20522. var Skeleton = (function () {
  20523. function Skeleton(name, id, scene) {
  20524. this.name = name;
  20525. this.id = id;
  20526. this.bones = new Array();
  20527. this._isDirty = true;
  20528. this._identity = BABYLON.Matrix.Identity();
  20529. this.bones = [];
  20530. this._scene = scene;
  20531. scene.skeletons.push(this);
  20532. this.prepare();
  20533. //make sure it will recalculate the matrix next time prepare is called.
  20534. this._isDirty = true;
  20535. }
  20536. // Members
  20537. Skeleton.prototype.getTransformMatrices = function () {
  20538. return this._transformMatrices;
  20539. };
  20540. // Methods
  20541. Skeleton.prototype._markAsDirty = function () {
  20542. this._isDirty = true;
  20543. };
  20544. Skeleton.prototype.prepare = function () {
  20545. if (!this._isDirty) {
  20546. return;
  20547. }
  20548. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20549. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20550. }
  20551. for (var index = 0; index < this.bones.length; index++) {
  20552. var bone = this.bones[index];
  20553. var parentBone = bone.getParent();
  20554. if (parentBone) {
  20555. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20556. }
  20557. else {
  20558. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20559. }
  20560. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20561. }
  20562. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20563. this._isDirty = false;
  20564. this._scene._activeBones += this.bones.length;
  20565. };
  20566. Skeleton.prototype.getAnimatables = function () {
  20567. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20568. this._animatables = [];
  20569. for (var index = 0; index < this.bones.length; index++) {
  20570. this._animatables.push(this.bones[index]);
  20571. }
  20572. }
  20573. return this._animatables;
  20574. };
  20575. Skeleton.prototype.clone = function (name, id) {
  20576. var result = new Skeleton(name, id || name, this._scene);
  20577. for (var index = 0; index < this.bones.length; index++) {
  20578. var source = this.bones[index];
  20579. var parentBone = null;
  20580. if (source.getParent()) {
  20581. var parentIndex = this.bones.indexOf(source.getParent());
  20582. parentBone = result.bones[parentIndex];
  20583. }
  20584. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20585. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20586. }
  20587. return result;
  20588. };
  20589. return Skeleton;
  20590. })();
  20591. BABYLON.Skeleton = Skeleton;
  20592. })(BABYLON || (BABYLON = {}));
  20593. //# sourceMappingURL=babylon.skeleton.js.map
  20594. var BABYLON;
  20595. (function (BABYLON) {
  20596. var PostProcess = (function () {
  20597. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20599. this.name = name;
  20600. this.width = -1;
  20601. this.height = -1;
  20602. this._reusable = false;
  20603. this._textures = new BABYLON.SmartArray(2);
  20604. this._currentRenderTextureInd = 0;
  20605. if (camera != null) {
  20606. this._camera = camera;
  20607. this._scene = camera.getScene();
  20608. camera.attachPostProcess(this);
  20609. this._engine = this._scene.getEngine();
  20610. }
  20611. else {
  20612. this._engine = engine;
  20613. }
  20614. this._renderRatio = ratio;
  20615. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  20616. this._reusable = reusable || false;
  20617. samplers = samplers || [];
  20618. samplers.push("textureSampler");
  20619. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  20620. }
  20621. PostProcess.prototype.isReusable = function () {
  20622. return this._reusable;
  20623. };
  20624. PostProcess.prototype.activate = function (camera, sourceTexture) {
  20625. camera = camera || this._camera;
  20626. var scene = camera.getScene();
  20627. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  20628. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  20629. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  20630. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  20631. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  20632. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  20633. if (this._textures.length > 0) {
  20634. for (var i = 0; i < this._textures.length; i++) {
  20635. this._engine._releaseTexture(this._textures.data[i]);
  20636. }
  20637. this._textures.reset();
  20638. }
  20639. this.width = desiredWidth;
  20640. this.height = desiredHeight;
  20641. 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 }));
  20642. if (this._reusable) {
  20643. 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 }));
  20644. }
  20645. if (this.onSizeChanged) {
  20646. this.onSizeChanged();
  20647. }
  20648. }
  20649. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  20650. if (this.onActivate) {
  20651. this.onActivate(camera);
  20652. }
  20653. // Clear
  20654. if (this.clearColor) {
  20655. this._engine.clear(this.clearColor, true, true);
  20656. }
  20657. else {
  20658. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  20659. }
  20660. if (this._reusable) {
  20661. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  20662. }
  20663. };
  20664. PostProcess.prototype.apply = function () {
  20665. // Check
  20666. if (!this._effect.isReady())
  20667. return null;
  20668. // States
  20669. this._engine.enableEffect(this._effect);
  20670. this._engine.setState(false);
  20671. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20672. this._engine.setDepthBuffer(false);
  20673. this._engine.setDepthWrite(false);
  20674. // Texture
  20675. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  20676. // Parameters
  20677. if (this.onApply) {
  20678. this.onApply(this._effect);
  20679. }
  20680. return this._effect;
  20681. };
  20682. PostProcess.prototype.dispose = function (camera) {
  20683. camera = camera || this._camera;
  20684. if (this._textures.length > 0) {
  20685. for (var i = 0; i < this._textures.length; i++) {
  20686. this._engine._releaseTexture(this._textures.data[i]);
  20687. }
  20688. this._textures.reset();
  20689. }
  20690. if (!camera) {
  20691. return;
  20692. }
  20693. camera.detachPostProcess(this);
  20694. var index = camera._postProcesses.indexOf(this);
  20695. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  20696. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  20697. }
  20698. };
  20699. return PostProcess;
  20700. })();
  20701. BABYLON.PostProcess = PostProcess;
  20702. })(BABYLON || (BABYLON = {}));
  20703. //# sourceMappingURL=babylon.postProcess.js.map
  20704. var BABYLON;
  20705. (function (BABYLON) {
  20706. var PostProcessManager = (function () {
  20707. function PostProcessManager(scene) {
  20708. this._vertexDeclaration = [2];
  20709. this._vertexStrideSize = 2 * 4;
  20710. this._scene = scene;
  20711. }
  20712. PostProcessManager.prototype._prepareBuffers = function () {
  20713. if (this._vertexBuffer) {
  20714. return;
  20715. }
  20716. // VBO
  20717. var vertices = [];
  20718. vertices.push(1, 1);
  20719. vertices.push(-1, 1);
  20720. vertices.push(-1, -1);
  20721. vertices.push(1, -1);
  20722. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  20723. // Indices
  20724. var indices = [];
  20725. indices.push(0);
  20726. indices.push(1);
  20727. indices.push(2);
  20728. indices.push(0);
  20729. indices.push(2);
  20730. indices.push(3);
  20731. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  20732. };
  20733. // Methods
  20734. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  20735. var postProcesses = this._scene.activeCamera._postProcesses;
  20736. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20737. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20738. return false;
  20739. }
  20740. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  20741. return true;
  20742. };
  20743. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  20744. var engine = this._scene.getEngine();
  20745. for (var index = 0; index < postProcesses.length; index++) {
  20746. if (index < postProcesses.length - 1) {
  20747. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20748. }
  20749. else {
  20750. if (targetTexture) {
  20751. engine.bindFramebuffer(targetTexture);
  20752. }
  20753. else {
  20754. engine.restoreDefaultFramebuffer();
  20755. }
  20756. }
  20757. var pp = postProcesses[index];
  20758. var effect = pp.apply();
  20759. if (effect) {
  20760. if (pp.onBeforeRender) {
  20761. pp.onBeforeRender(effect);
  20762. }
  20763. // VBOs
  20764. this._prepareBuffers();
  20765. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20766. // Draw order
  20767. engine.draw(true, 0, 6);
  20768. }
  20769. }
  20770. // Restore depth buffer
  20771. engine.setDepthBuffer(true);
  20772. engine.setDepthWrite(true);
  20773. };
  20774. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  20775. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20776. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20777. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20778. return;
  20779. }
  20780. var engine = this._scene.getEngine();
  20781. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  20782. if (index < postProcessesTakenIndices.length - 1) {
  20783. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  20784. }
  20785. else {
  20786. if (targetTexture) {
  20787. engine.bindFramebuffer(targetTexture);
  20788. }
  20789. else {
  20790. engine.restoreDefaultFramebuffer();
  20791. }
  20792. }
  20793. if (doNotPresent) {
  20794. break;
  20795. }
  20796. var pp = postProcesses[postProcessesTakenIndices[index]];
  20797. var effect = pp.apply();
  20798. if (effect) {
  20799. if (pp.onBeforeRender) {
  20800. pp.onBeforeRender(effect);
  20801. }
  20802. // VBOs
  20803. this._prepareBuffers();
  20804. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20805. // Draw order
  20806. engine.draw(true, 0, 6);
  20807. }
  20808. }
  20809. // Restore depth buffer
  20810. engine.setDepthBuffer(true);
  20811. engine.setDepthWrite(true);
  20812. };
  20813. PostProcessManager.prototype.dispose = function () {
  20814. if (this._vertexBuffer) {
  20815. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20816. this._vertexBuffer = null;
  20817. }
  20818. if (this._indexBuffer) {
  20819. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20820. this._indexBuffer = null;
  20821. }
  20822. };
  20823. return PostProcessManager;
  20824. })();
  20825. BABYLON.PostProcessManager = PostProcessManager;
  20826. })(BABYLON || (BABYLON = {}));
  20827. //# sourceMappingURL=babylon.postProcessManager.js.map
  20828. var __extends = this.__extends || function (d, b) {
  20829. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20830. function __() { this.constructor = d; }
  20831. __.prototype = b.prototype;
  20832. d.prototype = new __();
  20833. };
  20834. var BABYLON;
  20835. (function (BABYLON) {
  20836. var PassPostProcess = (function (_super) {
  20837. __extends(PassPostProcess, _super);
  20838. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20839. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  20840. }
  20841. return PassPostProcess;
  20842. })(BABYLON.PostProcess);
  20843. BABYLON.PassPostProcess = PassPostProcess;
  20844. })(BABYLON || (BABYLON = {}));
  20845. //# sourceMappingURL=babylon.passPostProcess.js.map
  20846. var __extends = this.__extends || function (d, b) {
  20847. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20848. function __() { this.constructor = d; }
  20849. __.prototype = b.prototype;
  20850. d.prototype = new __();
  20851. };
  20852. var BABYLON;
  20853. (function (BABYLON) {
  20854. var BlurPostProcess = (function (_super) {
  20855. __extends(BlurPostProcess, _super);
  20856. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  20857. var _this = this;
  20858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  20859. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  20860. this.direction = direction;
  20861. this.blurWidth = blurWidth;
  20862. this.onApply = function (effect) {
  20863. effect.setFloat2("screenSize", _this.width, _this.height);
  20864. effect.setVector2("direction", _this.direction);
  20865. effect.setFloat("blurWidth", _this.blurWidth);
  20866. };
  20867. }
  20868. return BlurPostProcess;
  20869. })(BABYLON.PostProcess);
  20870. BABYLON.BlurPostProcess = BlurPostProcess;
  20871. })(BABYLON || (BABYLON = {}));
  20872. //# sourceMappingURL=babylon.blurPostProcess.js.map
  20873. var __extends = this.__extends || function (d, b) {
  20874. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20875. function __() { this.constructor = d; }
  20876. __.prototype = b.prototype;
  20877. d.prototype = new __();
  20878. };
  20879. var BABYLON;
  20880. (function (BABYLON) {
  20881. var RefractionPostProcess = (function (_super) {
  20882. __extends(RefractionPostProcess, _super);
  20883. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  20884. var _this = this;
  20885. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  20886. this.color = color;
  20887. this.depth = depth;
  20888. this.colorLevel = colorLevel;
  20889. this.onActivate = function (cam) {
  20890. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  20891. };
  20892. this.onApply = function (effect) {
  20893. effect.setColor3("baseColor", _this.color);
  20894. effect.setFloat("depth", _this.depth);
  20895. effect.setFloat("colorLevel", _this.colorLevel);
  20896. effect.setTexture("refractionSampler", _this._refRexture);
  20897. };
  20898. }
  20899. // Methods
  20900. RefractionPostProcess.prototype.dispose = function (camera) {
  20901. if (this._refRexture) {
  20902. this._refRexture.dispose();
  20903. }
  20904. _super.prototype.dispose.call(this, camera);
  20905. };
  20906. return RefractionPostProcess;
  20907. })(BABYLON.PostProcess);
  20908. BABYLON.RefractionPostProcess = RefractionPostProcess;
  20909. })(BABYLON || (BABYLON = {}));
  20910. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  20911. var __extends = this.__extends || function (d, b) {
  20912. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20913. function __() { this.constructor = d; }
  20914. __.prototype = b.prototype;
  20915. d.prototype = new __();
  20916. };
  20917. var BABYLON;
  20918. (function (BABYLON) {
  20919. var BlackAndWhitePostProcess = (function (_super) {
  20920. __extends(BlackAndWhitePostProcess, _super);
  20921. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20922. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  20923. }
  20924. return BlackAndWhitePostProcess;
  20925. })(BABYLON.PostProcess);
  20926. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  20927. })(BABYLON || (BABYLON = {}));
  20928. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  20929. var __extends = this.__extends || function (d, b) {
  20930. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20931. function __() { this.constructor = d; }
  20932. __.prototype = b.prototype;
  20933. d.prototype = new __();
  20934. };
  20935. var BABYLON;
  20936. (function (BABYLON) {
  20937. var ConvolutionPostProcess = (function (_super) {
  20938. __extends(ConvolutionPostProcess, _super);
  20939. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  20940. var _this = this;
  20941. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  20942. this.kernel = kernel;
  20943. this.onApply = function (effect) {
  20944. effect.setFloat2("screenSize", _this.width, _this.height);
  20945. effect.setArray("kernel", _this.kernel);
  20946. };
  20947. }
  20948. // Statics
  20949. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  20950. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  20951. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  20952. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  20953. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  20954. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  20955. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  20956. return ConvolutionPostProcess;
  20957. })(BABYLON.PostProcess);
  20958. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  20959. })(BABYLON || (BABYLON = {}));
  20960. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  20961. var __extends = this.__extends || function (d, b) {
  20962. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20963. function __() { this.constructor = d; }
  20964. __.prototype = b.prototype;
  20965. d.prototype = new __();
  20966. };
  20967. var BABYLON;
  20968. (function (BABYLON) {
  20969. var FilterPostProcess = (function (_super) {
  20970. __extends(FilterPostProcess, _super);
  20971. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  20972. var _this = this;
  20973. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  20974. this.kernelMatrix = kernelMatrix;
  20975. this.onApply = function (effect) {
  20976. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  20977. };
  20978. }
  20979. return FilterPostProcess;
  20980. })(BABYLON.PostProcess);
  20981. BABYLON.FilterPostProcess = FilterPostProcess;
  20982. })(BABYLON || (BABYLON = {}));
  20983. //# sourceMappingURL=babylon.filterPostProcess.js.map
  20984. var __extends = this.__extends || function (d, b) {
  20985. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20986. function __() { this.constructor = d; }
  20987. __.prototype = b.prototype;
  20988. d.prototype = new __();
  20989. };
  20990. var BABYLON;
  20991. (function (BABYLON) {
  20992. var FxaaPostProcess = (function (_super) {
  20993. __extends(FxaaPostProcess, _super);
  20994. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20995. var _this = this;
  20996. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  20997. this.onSizeChanged = function () {
  20998. _this.texelWidth = 1.0 / _this.width;
  20999. _this.texelHeight = 1.0 / _this.height;
  21000. };
  21001. this.onApply = function (effect) {
  21002. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  21003. };
  21004. }
  21005. return FxaaPostProcess;
  21006. })(BABYLON.PostProcess);
  21007. BABYLON.FxaaPostProcess = FxaaPostProcess;
  21008. })(BABYLON || (BABYLON = {}));
  21009. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  21010. var BABYLON;
  21011. (function (BABYLON) {
  21012. var LensFlare = (function () {
  21013. function LensFlare(size, position, color, imgUrl, system) {
  21014. this.size = size;
  21015. this.position = position;
  21016. this.dispose = function () {
  21017. if (this.texture) {
  21018. this.texture.dispose();
  21019. }
  21020. // Remove from scene
  21021. var index = this._system.lensFlares.indexOf(this);
  21022. this._system.lensFlares.splice(index, 1);
  21023. };
  21024. this.color = color || new BABYLON.Color3(1, 1, 1);
  21025. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  21026. this._system = system;
  21027. system.lensFlares.push(this);
  21028. }
  21029. return LensFlare;
  21030. })();
  21031. BABYLON.LensFlare = LensFlare;
  21032. })(BABYLON || (BABYLON = {}));
  21033. //# sourceMappingURL=babylon.lensFlare.js.map
  21034. var BABYLON;
  21035. (function (BABYLON) {
  21036. var LensFlareSystem = (function () {
  21037. function LensFlareSystem(name, emitter, scene) {
  21038. this.name = name;
  21039. this.lensFlares = new Array();
  21040. this.borderLimit = 300;
  21041. this._vertexDeclaration = [2];
  21042. this._vertexStrideSize = 2 * 4;
  21043. this._isEnabled = true;
  21044. this._scene = scene;
  21045. this._emitter = emitter;
  21046. scene.lensFlareSystems.push(this);
  21047. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21048. // VBO
  21049. var vertices = [];
  21050. vertices.push(1, 1);
  21051. vertices.push(-1, 1);
  21052. vertices.push(-1, -1);
  21053. vertices.push(1, -1);
  21054. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21055. // Indices
  21056. var indices = [];
  21057. indices.push(0);
  21058. indices.push(1);
  21059. indices.push(2);
  21060. indices.push(0);
  21061. indices.push(2);
  21062. indices.push(3);
  21063. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21064. // Effects
  21065. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21066. }
  21067. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21068. get: function () {
  21069. return this._isEnabled;
  21070. },
  21071. set: function (value) {
  21072. this._isEnabled = value;
  21073. },
  21074. enumerable: true,
  21075. configurable: true
  21076. });
  21077. LensFlareSystem.prototype.getScene = function () {
  21078. return this._scene;
  21079. };
  21080. LensFlareSystem.prototype.getEmitter = function () {
  21081. return this._emitter;
  21082. };
  21083. LensFlareSystem.prototype.getEmitterPosition = function () {
  21084. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21085. };
  21086. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21087. var position = this.getEmitterPosition();
  21088. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21089. this._positionX = position.x;
  21090. this._positionY = position.y;
  21091. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21092. if (position.z > 0) {
  21093. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21094. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21095. return true;
  21096. }
  21097. }
  21098. return false;
  21099. };
  21100. LensFlareSystem.prototype._isVisible = function () {
  21101. if (!this._isEnabled) {
  21102. return false;
  21103. }
  21104. var emitterPosition = this.getEmitterPosition();
  21105. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21106. var distance = direction.length();
  21107. direction.normalize();
  21108. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21109. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21110. return !pickInfo.hit || pickInfo.distance > distance;
  21111. };
  21112. LensFlareSystem.prototype.render = function () {
  21113. if (!this._effect.isReady())
  21114. return false;
  21115. var engine = this._scene.getEngine();
  21116. var viewport = this._scene.activeCamera.viewport;
  21117. var globalViewport = viewport.toGlobal(engine);
  21118. // Position
  21119. if (!this.computeEffectivePosition(globalViewport)) {
  21120. return false;
  21121. }
  21122. // Visibility
  21123. if (!this._isVisible()) {
  21124. return false;
  21125. }
  21126. // Intensity
  21127. var awayX;
  21128. var awayY;
  21129. if (this._positionX < this.borderLimit + globalViewport.x) {
  21130. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21131. }
  21132. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21133. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21134. }
  21135. else {
  21136. awayX = 0;
  21137. }
  21138. if (this._positionY < this.borderLimit + globalViewport.y) {
  21139. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21140. }
  21141. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21142. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21143. }
  21144. else {
  21145. awayY = 0;
  21146. }
  21147. var away = (awayX > awayY) ? awayX : awayY;
  21148. if (away > this.borderLimit) {
  21149. away = this.borderLimit;
  21150. }
  21151. var intensity = 1.0 - (away / this.borderLimit);
  21152. if (intensity < 0) {
  21153. return false;
  21154. }
  21155. if (intensity > 1.0) {
  21156. intensity = 1.0;
  21157. }
  21158. // Position
  21159. var centerX = globalViewport.x + globalViewport.width / 2;
  21160. var centerY = globalViewport.y + globalViewport.height / 2;
  21161. var distX = centerX - this._positionX;
  21162. var distY = centerY - this._positionY;
  21163. // Effects
  21164. engine.enableEffect(this._effect);
  21165. engine.setState(false);
  21166. engine.setDepthBuffer(false);
  21167. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21168. // VBOs
  21169. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21170. for (var index = 0; index < this.lensFlares.length; index++) {
  21171. var flare = this.lensFlares[index];
  21172. var x = centerX - (distX * flare.position);
  21173. var y = centerY - (distY * flare.position);
  21174. var cw = flare.size;
  21175. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21176. var cx = 2 * (x / globalViewport.width) - 1.0;
  21177. var cy = 1.0 - 2 * (y / globalViewport.height);
  21178. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21179. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21180. // Texture
  21181. this._effect.setTexture("textureSampler", flare.texture);
  21182. // Color
  21183. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21184. // Draw order
  21185. engine.draw(true, 0, 6);
  21186. }
  21187. engine.setDepthBuffer(true);
  21188. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21189. return true;
  21190. };
  21191. LensFlareSystem.prototype.dispose = function () {
  21192. if (this._vertexBuffer) {
  21193. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21194. this._vertexBuffer = null;
  21195. }
  21196. if (this._indexBuffer) {
  21197. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21198. this._indexBuffer = null;
  21199. }
  21200. while (this.lensFlares.length) {
  21201. this.lensFlares[0].dispose();
  21202. }
  21203. // Remove from scene
  21204. var index = this._scene.lensFlareSystems.indexOf(this);
  21205. this._scene.lensFlareSystems.splice(index, 1);
  21206. };
  21207. return LensFlareSystem;
  21208. })();
  21209. BABYLON.LensFlareSystem = LensFlareSystem;
  21210. })(BABYLON || (BABYLON = {}));
  21211. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var CannonJSPlugin = (function () {
  21215. function CannonJSPlugin() {
  21216. this._registeredMeshes = [];
  21217. this._physicsMaterials = [];
  21218. this.updateBodyPosition = function (mesh) {
  21219. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21220. var registeredMesh = this._registeredMeshes[index];
  21221. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21222. var body = registeredMesh.body;
  21223. var center = mesh.getBoundingInfo().boundingBox.center;
  21224. body.position.set(center.x, center.z, center.y);
  21225. body.quaternion.x = mesh.rotationQuaternion.x;
  21226. body.quaternion.z = mesh.rotationQuaternion.y;
  21227. body.quaternion.y = mesh.rotationQuaternion.z;
  21228. body.quaternion.w = -mesh.rotationQuaternion.w;
  21229. return;
  21230. }
  21231. }
  21232. };
  21233. }
  21234. CannonJSPlugin.prototype.initialize = function (iterations) {
  21235. if (iterations === void 0) { iterations = 10; }
  21236. this._world = new CANNON.World();
  21237. this._world.broadphase = new CANNON.NaiveBroadphase();
  21238. this._world.solver.iterations = iterations;
  21239. };
  21240. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21241. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21242. };
  21243. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21244. this._world.step(delta);
  21245. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21246. var registeredMesh = this._registeredMeshes[index];
  21247. if (registeredMesh.isChild) {
  21248. continue;
  21249. }
  21250. // Body position
  21251. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21252. var deltaPos = registeredMesh.delta;
  21253. if (deltaPos) {
  21254. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21255. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21256. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21257. }
  21258. else {
  21259. registeredMesh.mesh.position.x = bodyX;
  21260. registeredMesh.mesh.position.y = bodyZ;
  21261. registeredMesh.mesh.position.z = bodyY;
  21262. }
  21263. if (!registeredMesh.mesh.rotationQuaternion) {
  21264. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21265. }
  21266. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21267. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21268. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21269. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21270. }
  21271. };
  21272. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21273. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21274. };
  21275. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21276. this.unregisterMesh(mesh);
  21277. mesh.computeWorldMatrix(true);
  21278. switch (impostor) {
  21279. case BABYLON.PhysicsEngine.SphereImpostor:
  21280. var bbox = mesh.getBoundingInfo().boundingBox;
  21281. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21282. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21283. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21284. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21285. case BABYLON.PhysicsEngine.BoxImpostor:
  21286. bbox = mesh.getBoundingInfo().boundingBox;
  21287. var min = bbox.minimumWorld;
  21288. var max = bbox.maximumWorld;
  21289. var box = max.subtract(min).scale(0.5);
  21290. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21291. case BABYLON.PhysicsEngine.PlaneImpostor:
  21292. return this._createPlane(mesh, options);
  21293. case BABYLON.PhysicsEngine.MeshImpostor:
  21294. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21295. var rawFaces = mesh.getIndices();
  21296. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21297. }
  21298. return null;
  21299. };
  21300. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21301. var shape = new CANNON.Sphere(radius);
  21302. if (!options) {
  21303. return shape;
  21304. }
  21305. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21306. };
  21307. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21308. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21309. if (!options) {
  21310. return shape;
  21311. }
  21312. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21313. };
  21314. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21315. var shape = new CANNON.Plane();
  21316. if (!options) {
  21317. return shape;
  21318. }
  21319. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21320. };
  21321. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21322. var verts = [], faces = [];
  21323. mesh.computeWorldMatrix(true);
  21324. for (var i = 0; i < rawVerts.length; i += 3) {
  21325. var transformed = BABYLON.Vector3.Zero();
  21326. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21327. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21328. }
  21329. for (var j = 0; j < rawFaces.length; j += 3) {
  21330. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21331. }
  21332. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21333. if (!options) {
  21334. return shape;
  21335. }
  21336. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21337. };
  21338. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21339. var index;
  21340. var mat;
  21341. for (index = 0; index < this._physicsMaterials.length; index++) {
  21342. mat = this._physicsMaterials[index];
  21343. if (mat.friction === friction && mat.restitution === restitution) {
  21344. return mat;
  21345. }
  21346. }
  21347. var currentMat = new CANNON.Material();
  21348. currentMat.friction = friction;
  21349. currentMat.restitution = restitution;
  21350. this._physicsMaterials.push(currentMat);
  21351. for (index = 0; index < this._physicsMaterials.length; index++) {
  21352. mat = this._physicsMaterials[index];
  21353. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21354. contactMaterial.contactEquationStiffness = 1e10;
  21355. contactMaterial.contactEquationRegularizationTime = 10;
  21356. this._world.addContactMaterial(contactMaterial);
  21357. }
  21358. return currentMat;
  21359. };
  21360. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21361. var initialRotation = null;
  21362. if (mesh.rotationQuaternion) {
  21363. initialRotation = mesh.rotationQuaternion.clone();
  21364. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21365. }
  21366. // The delta between the mesh position and the mesh bounding box center
  21367. var bbox = mesh.getBoundingInfo().boundingBox;
  21368. var deltaPosition = mesh.position.subtract(bbox.center);
  21369. var material = this._addMaterial(friction, restitution);
  21370. var body = new CANNON.RigidBody(mass, shape, material);
  21371. if (initialRotation) {
  21372. body.quaternion.x = initialRotation.x;
  21373. body.quaternion.z = initialRotation.y;
  21374. body.quaternion.y = initialRotation.z;
  21375. body.quaternion.w = -initialRotation.w;
  21376. }
  21377. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21378. this._world.add(body);
  21379. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21380. return body;
  21381. };
  21382. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21383. var compoundShape = new CANNON.Compound();
  21384. for (var index = 0; index < parts.length; index++) {
  21385. var mesh = parts[index].mesh;
  21386. var shape = this.registerMesh(mesh, parts[index].impostor);
  21387. if (index == 0) {
  21388. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21389. }
  21390. else {
  21391. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21392. }
  21393. }
  21394. var initialMesh = parts[0].mesh;
  21395. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21396. body.parts = parts;
  21397. return body;
  21398. };
  21399. CannonJSPlugin.prototype._unbindBody = function (body) {
  21400. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21401. var registeredMesh = this._registeredMeshes[index];
  21402. if (registeredMesh.body === body) {
  21403. registeredMesh.body = null;
  21404. registeredMesh.delta = 0;
  21405. }
  21406. }
  21407. };
  21408. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21409. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21410. var registeredMesh = this._registeredMeshes[index];
  21411. if (registeredMesh.mesh === mesh) {
  21412. // Remove body
  21413. if (registeredMesh.body) {
  21414. this._world.remove(registeredMesh.body);
  21415. this._unbindBody(registeredMesh.body);
  21416. }
  21417. this._registeredMeshes.splice(index, 1);
  21418. return;
  21419. }
  21420. }
  21421. };
  21422. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21423. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21424. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21425. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21426. var registeredMesh = this._registeredMeshes[index];
  21427. if (registeredMesh.mesh === mesh) {
  21428. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21429. return;
  21430. }
  21431. }
  21432. };
  21433. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21434. var body1 = null, body2 = null;
  21435. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21436. var registeredMesh = this._registeredMeshes[index];
  21437. if (registeredMesh.mesh === mesh1) {
  21438. body1 = registeredMesh.body;
  21439. }
  21440. else if (registeredMesh.mesh === mesh2) {
  21441. body2 = registeredMesh.body;
  21442. }
  21443. }
  21444. if (!body1 || !body2) {
  21445. return false;
  21446. }
  21447. 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));
  21448. this._world.addConstraint(constraint);
  21449. return true;
  21450. };
  21451. CannonJSPlugin.prototype.dispose = function () {
  21452. while (this._registeredMeshes.length) {
  21453. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21454. }
  21455. };
  21456. CannonJSPlugin.prototype.isSupported = function () {
  21457. return window.CANNON !== undefined;
  21458. };
  21459. return CannonJSPlugin;
  21460. })();
  21461. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21462. })(BABYLON || (BABYLON = {}));
  21463. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21464. var BABYLON;
  21465. (function (BABYLON) {
  21466. var OimoJSPlugin = (function () {
  21467. function OimoJSPlugin() {
  21468. this._registeredMeshes = [];
  21469. /**
  21470. * Update the body position according to the mesh position
  21471. * @param mesh
  21472. */
  21473. this.updateBodyPosition = function (mesh) {
  21474. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21475. var registeredMesh = this._registeredMeshes[index];
  21476. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21477. var body = registeredMesh.body.body;
  21478. mesh.computeWorldMatrix(true);
  21479. var center = mesh.getBoundingInfo().boundingBox.center;
  21480. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  21481. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  21482. body.sleeping = false;
  21483. return;
  21484. }
  21485. // Case where the parent has been updated
  21486. if (registeredMesh.mesh.parent === mesh) {
  21487. mesh.computeWorldMatrix(true);
  21488. registeredMesh.mesh.computeWorldMatrix(true);
  21489. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21490. var absoluteRotation = mesh.rotation;
  21491. body = registeredMesh.body.body;
  21492. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  21493. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  21494. body.sleeping = false;
  21495. return;
  21496. }
  21497. }
  21498. };
  21499. }
  21500. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21501. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21502. };
  21503. OimoJSPlugin.prototype.initialize = function (iterations) {
  21504. this._world = new OIMO.World();
  21505. this._world.clear();
  21506. };
  21507. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21508. this._world.gravity = gravity;
  21509. };
  21510. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21511. var body = null;
  21512. this.unregisterMesh(mesh);
  21513. mesh.computeWorldMatrix(true);
  21514. var initialRotation = null;
  21515. if (mesh.rotationQuaternion) {
  21516. initialRotation = mesh.rotationQuaternion.clone();
  21517. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21518. mesh.computeWorldMatrix(true);
  21519. }
  21520. var bbox = mesh.getBoundingInfo().boundingBox;
  21521. // The delta between the mesh position and the mesh bounding box center
  21522. var deltaPosition = mesh.position.subtract(bbox.center);
  21523. // Transform delta position with the rotation
  21524. if (initialRotation) {
  21525. var m = new BABYLON.Matrix();
  21526. initialRotation.toRotationMatrix(m);
  21527. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21528. }
  21529. switch (impostor) {
  21530. case BABYLON.PhysicsEngine.SphereImpostor:
  21531. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21532. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21533. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21534. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21535. body = new OIMO.Body({
  21536. type: 'sphere',
  21537. size: [size],
  21538. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21539. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21540. move: options.mass != 0,
  21541. config: [options.mass, options.friction, options.restitution],
  21542. world: this._world
  21543. });
  21544. break;
  21545. case BABYLON.PhysicsEngine.PlaneImpostor:
  21546. case BABYLON.PhysicsEngine.CylinderImpostor:
  21547. case BABYLON.PhysicsEngine.BoxImpostor:
  21548. var min = bbox.minimumWorld;
  21549. var max = bbox.maximumWorld;
  21550. var box = max.subtract(min);
  21551. var sizeX = this._checkWithEpsilon(box.x);
  21552. var sizeY = this._checkWithEpsilon(box.y);
  21553. var sizeZ = this._checkWithEpsilon(box.z);
  21554. body = new OIMO.Body({
  21555. type: 'box',
  21556. size: [sizeX, sizeY, sizeZ],
  21557. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21558. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21559. move: options.mass != 0,
  21560. config: [options.mass, options.friction, options.restitution],
  21561. world: this._world
  21562. });
  21563. break;
  21564. }
  21565. //If quaternion was set as the rotation of the object
  21566. if (initialRotation) {
  21567. //We have to access the rigid body's properties to set the quaternion.
  21568. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21569. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21570. //update the internal rotation matrix
  21571. body.body.syncShapes();
  21572. }
  21573. this._registeredMeshes.push({
  21574. mesh: mesh,
  21575. body: body,
  21576. delta: deltaPosition
  21577. });
  21578. return body;
  21579. };
  21580. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21581. var types = [], sizes = [], positions = [], rotations = [];
  21582. var initialMesh = parts[0].mesh;
  21583. for (var index = 0; index < parts.length; index++) {
  21584. var part = parts[index];
  21585. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  21586. types.push(bodyParameters.type);
  21587. sizes.push.apply(sizes, bodyParameters.size);
  21588. positions.push.apply(positions, bodyParameters.pos);
  21589. rotations.push.apply(rotations, bodyParameters.rot);
  21590. }
  21591. var body = new OIMO.Body({
  21592. type: types,
  21593. size: sizes,
  21594. pos: positions,
  21595. rot: rotations,
  21596. move: options.mass != 0,
  21597. config: [options.mass, options.friction, options.restitution],
  21598. world: this._world
  21599. });
  21600. this._registeredMeshes.push({
  21601. mesh: initialMesh,
  21602. body: body
  21603. });
  21604. return body;
  21605. };
  21606. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  21607. var bodyParameters = null;
  21608. var mesh = part.mesh;
  21609. // We need the bounding box/sphere info to compute the physics body
  21610. mesh.computeWorldMatrix();
  21611. switch (part.impostor) {
  21612. case BABYLON.PhysicsEngine.SphereImpostor:
  21613. var bbox = mesh.getBoundingInfo().boundingBox;
  21614. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21615. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21616. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21617. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21618. bodyParameters = {
  21619. type: 'sphere',
  21620. /* bug with oimo : sphere needs 3 sizes in this case */
  21621. size: [size, -1, -1],
  21622. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  21623. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21624. };
  21625. break;
  21626. case BABYLON.PhysicsEngine.PlaneImpostor:
  21627. case BABYLON.PhysicsEngine.BoxImpostor:
  21628. bbox = mesh.getBoundingInfo().boundingBox;
  21629. var min = bbox.minimumWorld;
  21630. var max = bbox.maximumWorld;
  21631. var box = max.subtract(min);
  21632. var sizeX = this._checkWithEpsilon(box.x);
  21633. var sizeY = this._checkWithEpsilon(box.y);
  21634. var sizeZ = this._checkWithEpsilon(box.z);
  21635. var relativePosition = mesh.position;
  21636. bodyParameters = {
  21637. type: 'box',
  21638. size: [sizeX, sizeY, sizeZ],
  21639. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  21640. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21641. };
  21642. break;
  21643. }
  21644. return bodyParameters;
  21645. };
  21646. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  21647. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21648. var registeredMesh = this._registeredMeshes[index];
  21649. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21650. if (registeredMesh.body) {
  21651. this._world.removeRigidBody(registeredMesh.body.body);
  21652. this._unbindBody(registeredMesh.body);
  21653. }
  21654. this._registeredMeshes.splice(index, 1);
  21655. return;
  21656. }
  21657. }
  21658. };
  21659. OimoJSPlugin.prototype._unbindBody = function (body) {
  21660. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21661. var registeredMesh = this._registeredMeshes[index];
  21662. if (registeredMesh.body === body) {
  21663. registeredMesh.body = null;
  21664. }
  21665. }
  21666. };
  21667. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21668. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21669. var registeredMesh = this._registeredMeshes[index];
  21670. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21671. // Get object mass to have a behaviour similar to cannon.js
  21672. var mass = registeredMesh.body.body.massInfo.mass;
  21673. // The force is scaled with the mass of object
  21674. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  21675. return;
  21676. }
  21677. }
  21678. };
  21679. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21680. var body1 = null, body2 = null;
  21681. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21682. var registeredMesh = this._registeredMeshes[index];
  21683. if (registeredMesh.mesh === mesh1) {
  21684. body1 = registeredMesh.body.body;
  21685. }
  21686. else if (registeredMesh.mesh === mesh2) {
  21687. body2 = registeredMesh.body.body;
  21688. }
  21689. }
  21690. if (!body1 || !body2) {
  21691. return false;
  21692. }
  21693. if (!options) {
  21694. options = {};
  21695. }
  21696. new OIMO.Link({
  21697. type: options.type,
  21698. body1: body1,
  21699. body2: body2,
  21700. min: options.min,
  21701. max: options.max,
  21702. axe1: options.axe1,
  21703. axe2: options.axe2,
  21704. pos1: [pivot1.x, pivot1.y, pivot1.z],
  21705. pos2: [pivot2.x, pivot2.y, pivot2.z],
  21706. collision: options.collision,
  21707. spring: options.spring,
  21708. world: this._world
  21709. });
  21710. return true;
  21711. };
  21712. OimoJSPlugin.prototype.dispose = function () {
  21713. this._world.clear();
  21714. while (this._registeredMeshes.length) {
  21715. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21716. }
  21717. };
  21718. OimoJSPlugin.prototype.isSupported = function () {
  21719. return OIMO !== undefined;
  21720. };
  21721. OimoJSPlugin.prototype._getLastShape = function (body) {
  21722. var lastShape = body.shapes;
  21723. while (lastShape.next) {
  21724. lastShape = lastShape.next;
  21725. }
  21726. return lastShape;
  21727. };
  21728. OimoJSPlugin.prototype.runOneStep = function (time) {
  21729. this._world.step();
  21730. // Update the position of all registered meshes
  21731. var i = this._registeredMeshes.length;
  21732. var m;
  21733. while (i--) {
  21734. var body = this._registeredMeshes[i].body.body;
  21735. var mesh = this._registeredMeshes[i].mesh;
  21736. var delta = this._registeredMeshes[i].delta;
  21737. if (!body.sleeping) {
  21738. if (body.shapes.next) {
  21739. var parentShape = this._getLastShape(body);
  21740. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  21741. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  21742. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  21743. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  21744. if (!mesh.rotationQuaternion) {
  21745. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21746. }
  21747. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  21748. mesh.computeWorldMatrix();
  21749. }
  21750. else {
  21751. m = body.getMatrix();
  21752. mtx = BABYLON.Matrix.FromArray(m);
  21753. // Body position
  21754. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  21755. if (!delta) {
  21756. mesh.position.x = bodyX;
  21757. mesh.position.y = bodyY;
  21758. mesh.position.z = bodyZ;
  21759. }
  21760. else {
  21761. mesh.position.x = bodyX + delta.x;
  21762. mesh.position.y = bodyY + delta.y;
  21763. mesh.position.z = bodyZ + delta.z;
  21764. }
  21765. if (!mesh.rotationQuaternion) {
  21766. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21767. }
  21768. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  21769. mesh.computeWorldMatrix();
  21770. }
  21771. }
  21772. }
  21773. };
  21774. return OimoJSPlugin;
  21775. })();
  21776. BABYLON.OimoJSPlugin = OimoJSPlugin;
  21777. })(BABYLON || (BABYLON = {}));
  21778. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  21779. var BABYLON;
  21780. (function (BABYLON) {
  21781. var PhysicsEngine = (function () {
  21782. function PhysicsEngine(plugin) {
  21783. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  21784. }
  21785. PhysicsEngine.prototype._initialize = function (gravity) {
  21786. this._currentPlugin.initialize();
  21787. this._setGravity(gravity);
  21788. };
  21789. PhysicsEngine.prototype._runOneStep = function (delta) {
  21790. if (delta > 0.1) {
  21791. delta = 0.1;
  21792. }
  21793. else if (delta <= 0) {
  21794. delta = 1.0 / 60.0;
  21795. }
  21796. this._currentPlugin.runOneStep(delta);
  21797. };
  21798. PhysicsEngine.prototype._setGravity = function (gravity) {
  21799. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  21800. this._currentPlugin.setGravity(this.gravity);
  21801. };
  21802. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  21803. return this._currentPlugin.registerMesh(mesh, impostor, options);
  21804. };
  21805. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  21806. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  21807. };
  21808. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  21809. this._currentPlugin.unregisterMesh(mesh);
  21810. };
  21811. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  21812. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  21813. };
  21814. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21815. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  21816. };
  21817. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  21818. this._currentPlugin.updateBodyPosition(mesh);
  21819. };
  21820. PhysicsEngine.prototype.dispose = function () {
  21821. this._currentPlugin.dispose();
  21822. };
  21823. PhysicsEngine.prototype.isSupported = function () {
  21824. return this._currentPlugin.isSupported();
  21825. };
  21826. // Statics
  21827. PhysicsEngine.NoImpostor = 0;
  21828. PhysicsEngine.SphereImpostor = 1;
  21829. PhysicsEngine.BoxImpostor = 2;
  21830. PhysicsEngine.PlaneImpostor = 3;
  21831. PhysicsEngine.MeshImpostor = 4;
  21832. PhysicsEngine.CapsuleImpostor = 5;
  21833. PhysicsEngine.ConeImpostor = 6;
  21834. PhysicsEngine.CylinderImpostor = 7;
  21835. PhysicsEngine.ConvexHullImpostor = 8;
  21836. PhysicsEngine.Epsilon = 0.001;
  21837. return PhysicsEngine;
  21838. })();
  21839. BABYLON.PhysicsEngine = PhysicsEngine;
  21840. })(BABYLON || (BABYLON = {}));
  21841. //# sourceMappingURL=babylon.physicsEngine.js.map
  21842. var BABYLON;
  21843. (function (BABYLON) {
  21844. var serializeLight = function (light) {
  21845. var serializationObject = {};
  21846. serializationObject.name = light.name;
  21847. serializationObject.id = light.id;
  21848. serializationObject.tags = BABYLON.Tags.GetTags(light);
  21849. if (light instanceof BABYLON.PointLight) {
  21850. serializationObject.type = 0;
  21851. serializationObject.position = light.position.asArray();
  21852. }
  21853. else if (light instanceof BABYLON.DirectionalLight) {
  21854. serializationObject.type = 1;
  21855. var directionalLight = light;
  21856. serializationObject.position = directionalLight.position.asArray();
  21857. serializationObject.direction = directionalLight.direction.asArray();
  21858. }
  21859. else if (light instanceof BABYLON.SpotLight) {
  21860. serializationObject.type = 2;
  21861. var spotLight = light;
  21862. serializationObject.position = spotLight.position.asArray();
  21863. serializationObject.direction = spotLight.position.asArray();
  21864. serializationObject.angle = spotLight.angle;
  21865. serializationObject.exponent = spotLight.exponent;
  21866. }
  21867. else if (light instanceof BABYLON.HemisphericLight) {
  21868. serializationObject.type = 3;
  21869. var hemisphericLight = light;
  21870. serializationObject.direction = hemisphericLight.direction.asArray();
  21871. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  21872. }
  21873. if (light.intensity) {
  21874. serializationObject.intensity = light.intensity;
  21875. }
  21876. serializationObject.range = light.range;
  21877. serializationObject.diffuse = light.diffuse.asArray();
  21878. serializationObject.specular = light.specular.asArray();
  21879. return serializationObject;
  21880. };
  21881. var serializeFresnelParameter = function (fresnelParameter) {
  21882. var serializationObject = {};
  21883. serializationObject.isEnabled = fresnelParameter.isEnabled;
  21884. serializationObject.leftColor = fresnelParameter.leftColor;
  21885. serializationObject.rightColor = fresnelParameter.rightColor;
  21886. serializationObject.bias = fresnelParameter.bias;
  21887. serializationObject.power = fresnelParameter.power;
  21888. return serializationObject;
  21889. };
  21890. var appendAnimations = function (source, destination) {
  21891. if (source.animations) {
  21892. destination.animations = [];
  21893. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21894. var animation = source.animations[animationIndex];
  21895. destination.animations.push(serializeAnimation(animation));
  21896. }
  21897. }
  21898. };
  21899. var serializeCamera = function (camera) {
  21900. var serializationObject = {};
  21901. serializationObject.name = camera.name;
  21902. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  21903. serializationObject.id = camera.id;
  21904. serializationObject.position = camera.position.asArray();
  21905. // Parent
  21906. if (camera.parent) {
  21907. serializationObject.parentId = camera.parent.id;
  21908. }
  21909. serializationObject.fov = camera.fov;
  21910. serializationObject.minZ = camera.minZ;
  21911. serializationObject.maxZ = camera.maxZ;
  21912. serializationObject.inertia = camera.inertia;
  21913. //setting the type
  21914. if (camera instanceof BABYLON.FreeCamera) {
  21915. serializationObject.type = "FreeCamera";
  21916. }
  21917. else if (camera instanceof BABYLON.ArcRotateCamera) {
  21918. serializationObject.type = "ArcRotateCamera";
  21919. }
  21920. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21921. serializationObject.type = "AnaglyphArcRotateCamera";
  21922. }
  21923. else if (camera instanceof BABYLON.GamepadCamera) {
  21924. serializationObject.type = "GamepadCamera";
  21925. }
  21926. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  21927. serializationObject.type = "AnaglyphFreeCamera";
  21928. }
  21929. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  21930. serializationObject.type = "DeviceOrientationCamera";
  21931. }
  21932. else if (camera instanceof BABYLON.FollowCamera) {
  21933. serializationObject.type = "FollowCamera";
  21934. }
  21935. else if (camera instanceof BABYLON.OculusCamera) {
  21936. serializationObject.type = "OculusCamera";
  21937. }
  21938. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  21939. serializationObject.type = "OculusGamepadCamera";
  21940. }
  21941. else if (camera instanceof BABYLON.TouchCamera) {
  21942. serializationObject.type = "TouchCamera";
  21943. }
  21944. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  21945. serializationObject.type = "VirtualJoysticksCamera";
  21946. }
  21947. else if (camera instanceof BABYLON.WebVRCamera) {
  21948. serializationObject.type = "WebVRCamera";
  21949. }
  21950. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  21951. serializationObject.type = "VRDeviceOrientationCamera";
  21952. }
  21953. //special properties of specific cameras
  21954. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21955. var arcCamera = camera;
  21956. serializationObject.alpha = arcCamera.alpha;
  21957. serializationObject.beta = arcCamera.beta;
  21958. serializationObject.radius = arcCamera.radius;
  21959. if (arcCamera.target && arcCamera.target.id) {
  21960. serializationObject.lockedTargetId = arcCamera.target.id;
  21961. }
  21962. }
  21963. else if (camera instanceof BABYLON.FollowCamera) {
  21964. var followCam = camera;
  21965. serializationObject.radius = followCam.radius;
  21966. serializationObject.heightOffset = followCam.heightOffset;
  21967. serializationObject.rotationOffset = followCam.rotationOffset;
  21968. }
  21969. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21970. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  21971. if (camera['_eyeSpace'] !== undefined) {
  21972. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  21973. }
  21974. }
  21975. //general properties that not all cameras have. The [] is due to typescript's type safety
  21976. if (camera['speed'] !== undefined) {
  21977. serializationObject.speed = camera['speed'];
  21978. }
  21979. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  21980. serializationObject.target = camera['target'].asArray();
  21981. }
  21982. // Target
  21983. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  21984. serializationObject.rotation = camera['rotation'].asArray();
  21985. }
  21986. // Locked target
  21987. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  21988. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  21989. }
  21990. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  21991. serializationObject.applyGravity = camera['applyGravity'] || false;
  21992. if (camera['ellipsoid']) {
  21993. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  21994. }
  21995. // Animations
  21996. appendAnimations(camera, serializationObject);
  21997. // Layer mask
  21998. serializationObject.layerMask = camera.layerMask;
  21999. return serializationObject;
  22000. };
  22001. var serializeAnimation = function (animation) {
  22002. var serializationObject = {};
  22003. serializationObject.name = animation.name;
  22004. serializationObject.property = animation.targetProperty;
  22005. serializationObject.framePerSecond = animation.framePerSecond;
  22006. serializationObject.dataType = animation.dataType;
  22007. serializationObject.loopBehavior = animation.loopMode;
  22008. var dataType = animation.dataType;
  22009. serializationObject.keys = [];
  22010. var keys = animation.getKeys();
  22011. for (var index = 0; index < keys.length; index++) {
  22012. var animationKey = keys[index];
  22013. var key = {};
  22014. key.frame = animationKey.frame;
  22015. switch (dataType) {
  22016. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  22017. key.values = [animationKey.value];
  22018. break;
  22019. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  22020. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  22021. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  22022. key.values = animationKey.value.asArray();
  22023. break;
  22024. }
  22025. serializationObject.keys.push(key);
  22026. }
  22027. return serializationObject;
  22028. };
  22029. var serializeMultiMaterial = function (material) {
  22030. var serializationObject = {};
  22031. serializationObject.name = material.name;
  22032. serializationObject.id = material.id;
  22033. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22034. serializationObject.materials = [];
  22035. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22036. var subMat = material.subMaterials[matIndex];
  22037. if (subMat) {
  22038. serializationObject.materials.push(subMat.id);
  22039. }
  22040. else {
  22041. serializationObject.materials.push(null);
  22042. }
  22043. }
  22044. return serializationObject;
  22045. };
  22046. var serializeMaterial = function (material) {
  22047. var serializationObject = {};
  22048. serializationObject.name = material.name;
  22049. serializationObject.ambient = material.ambientColor.asArray();
  22050. serializationObject.diffuse = material.diffuseColor.asArray();
  22051. serializationObject.specular = material.specularColor.asArray();
  22052. serializationObject.specularPower = material.specularPower;
  22053. serializationObject.emissive = material.emissiveColor.asArray();
  22054. serializationObject.alpha = material.alpha;
  22055. serializationObject.id = material.id;
  22056. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22057. serializationObject.backFaceCulling = material.backFaceCulling;
  22058. if (material.diffuseTexture) {
  22059. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22060. }
  22061. if (material.diffuseFresnelParameters) {
  22062. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22063. }
  22064. if (material.ambientTexture) {
  22065. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22066. }
  22067. if (material.opacityTexture) {
  22068. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22069. }
  22070. if (material.opacityFresnelParameters) {
  22071. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22072. }
  22073. if (material.reflectionTexture) {
  22074. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22075. }
  22076. if (material.reflectionFresnelParameters) {
  22077. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22078. }
  22079. if (material.emissiveTexture) {
  22080. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22081. }
  22082. if (material.emissiveFresnelParameters) {
  22083. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22084. }
  22085. if (material.specularTexture) {
  22086. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22087. }
  22088. if (material.bumpTexture) {
  22089. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22090. }
  22091. return serializationObject;
  22092. };
  22093. var serializeTexture = function (texture) {
  22094. var serializationObject = {};
  22095. if (!texture.name) {
  22096. return null;
  22097. }
  22098. if (texture instanceof BABYLON.CubeTexture) {
  22099. serializationObject.name = texture.name;
  22100. serializationObject.hasAlpha = texture.hasAlpha;
  22101. serializationObject.level = texture.level;
  22102. serializationObject.coordinatesMode = texture.coordinatesMode;
  22103. return serializationObject;
  22104. }
  22105. if (texture instanceof BABYLON.MirrorTexture) {
  22106. var mirrorTexture = texture;
  22107. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22108. serializationObject.renderList = [];
  22109. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22110. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22111. }
  22112. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22113. }
  22114. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22115. var renderTargetTexture = texture;
  22116. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22117. serializationObject.renderList = [];
  22118. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22119. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22120. }
  22121. }
  22122. var regularTexture = texture;
  22123. serializationObject.name = texture.name;
  22124. serializationObject.hasAlpha = texture.hasAlpha;
  22125. serializationObject.level = texture.level;
  22126. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22127. serializationObject.coordinatesMode = texture.coordinatesMode;
  22128. serializationObject.uOffset = regularTexture.uOffset;
  22129. serializationObject.vOffset = regularTexture.vOffset;
  22130. serializationObject.uScale = regularTexture.uScale;
  22131. serializationObject.vScale = regularTexture.vScale;
  22132. serializationObject.uAng = regularTexture.uAng;
  22133. serializationObject.vAng = regularTexture.vAng;
  22134. serializationObject.wAng = regularTexture.wAng;
  22135. serializationObject.wrapU = texture.wrapU;
  22136. serializationObject.wrapV = texture.wrapV;
  22137. // Animations
  22138. appendAnimations(texture, serializationObject);
  22139. return serializationObject;
  22140. };
  22141. var serializeSkeleton = function (skeleton) {
  22142. var serializationObject = {};
  22143. serializationObject.name = skeleton.name;
  22144. serializationObject.id = skeleton.id;
  22145. serializationObject.bones = [];
  22146. for (var index = 0; index < skeleton.bones.length; index++) {
  22147. var bone = skeleton.bones[index];
  22148. var serializedBone = {
  22149. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22150. name: bone.name,
  22151. matrix: bone.getLocalMatrix().toArray()
  22152. };
  22153. serializationObject.bones.push(serializedBone);
  22154. if (bone.animations && bone.animations.length > 0) {
  22155. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22156. }
  22157. }
  22158. return serializationObject;
  22159. };
  22160. var serializeParticleSystem = function (particleSystem) {
  22161. var serializationObject = {};
  22162. serializationObject.emitterId = particleSystem.emitter.id;
  22163. serializationObject.capacity = particleSystem.getCapacity();
  22164. if (particleSystem.particleTexture) {
  22165. serializationObject.textureName = particleSystem.particleTexture.name;
  22166. }
  22167. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22168. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22169. serializationObject.minSize = particleSystem.minSize;
  22170. serializationObject.maxSize = particleSystem.maxSize;
  22171. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22172. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22173. serializationObject.emitRate = particleSystem.emitRate;
  22174. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22175. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22176. serializationObject.gravity = particleSystem.gravity.asArray();
  22177. serializationObject.direction1 = particleSystem.direction1.asArray();
  22178. serializationObject.direction2 = particleSystem.direction2.asArray();
  22179. serializationObject.color1 = particleSystem.color1.asArray();
  22180. serializationObject.color2 = particleSystem.color2.asArray();
  22181. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22182. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22183. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22184. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22185. serializationObject.blendMode = particleSystem.blendMode;
  22186. return serializationObject;
  22187. };
  22188. var serializeLensFlareSystem = function (lensFlareSystem) {
  22189. var serializationObject = {};
  22190. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22191. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22192. serializationObject.flares = [];
  22193. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22194. var flare = lensFlareSystem.lensFlares[index];
  22195. serializationObject.flares.push({
  22196. size: flare.size,
  22197. position: flare.position,
  22198. color: flare.color.asArray(),
  22199. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22200. });
  22201. }
  22202. return serializationObject;
  22203. };
  22204. var serializeShadowGenerator = function (light) {
  22205. var serializationObject = {};
  22206. var shadowGenerator = light.getShadowGenerator();
  22207. serializationObject.lightId = light.id;
  22208. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22209. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22210. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22211. serializationObject.renderList = [];
  22212. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22213. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22214. serializationObject.renderList.push(mesh.id);
  22215. }
  22216. return serializationObject;
  22217. };
  22218. var serializedGeometries = [];
  22219. var serializeGeometry = function (geometry, serializationGeometries) {
  22220. if (serializedGeometries[geometry.id]) {
  22221. return;
  22222. }
  22223. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22224. serializationGeometries.boxes.push(serializeBox(geometry));
  22225. }
  22226. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22227. serializationGeometries.spheres.push(serializeSphere(geometry));
  22228. }
  22229. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22230. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22231. }
  22232. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22233. serializationGeometries.toruses.push(serializeTorus(geometry));
  22234. }
  22235. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22236. serializationGeometries.grounds.push(serializeGround(geometry));
  22237. }
  22238. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22239. serializationGeometries.planes.push(serializePlane(geometry));
  22240. }
  22241. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22242. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22243. }
  22244. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22245. throw new Error("Unknow primitive type");
  22246. }
  22247. else {
  22248. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22249. }
  22250. serializedGeometries[geometry.id] = true;
  22251. };
  22252. var serializeGeometryBase = function (geometry) {
  22253. var serializationObject = {};
  22254. serializationObject.id = geometry.id;
  22255. if (BABYLON.Tags.HasTags(geometry)) {
  22256. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22257. }
  22258. return serializationObject;
  22259. };
  22260. var serializeVertexData = function (vertexData) {
  22261. var serializationObject = serializeGeometryBase(vertexData);
  22262. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22263. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22264. }
  22265. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22266. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22267. }
  22268. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22269. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22270. }
  22271. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22272. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22273. }
  22274. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22275. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22276. }
  22277. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22278. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22279. serializationObject.matricesIndices._isExpanded = true;
  22280. }
  22281. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22282. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22283. }
  22284. serializationObject.indices = vertexData.getIndices();
  22285. return serializationObject;
  22286. };
  22287. var serializePrimitive = function (primitive) {
  22288. var serializationObject = serializeGeometryBase(primitive);
  22289. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22290. return serializationObject;
  22291. };
  22292. var serializeBox = function (box) {
  22293. var serializationObject = serializePrimitive(box);
  22294. serializationObject.size = box.size;
  22295. return serializationObject;
  22296. };
  22297. var serializeSphere = function (sphere) {
  22298. var serializationObject = serializePrimitive(sphere);
  22299. serializationObject.segments = sphere.segments;
  22300. serializationObject.diameter = sphere.diameter;
  22301. return serializationObject;
  22302. };
  22303. var serializeCylinder = function (cylinder) {
  22304. var serializationObject = serializePrimitive(cylinder);
  22305. serializationObject.height = cylinder.height;
  22306. serializationObject.diameterTop = cylinder.diameterTop;
  22307. serializationObject.diameterBottom = cylinder.diameterBottom;
  22308. serializationObject.tessellation = cylinder.tessellation;
  22309. return serializationObject;
  22310. };
  22311. var serializeTorus = function (torus) {
  22312. var serializationObject = serializePrimitive(torus);
  22313. serializationObject.diameter = torus.diameter;
  22314. serializationObject.thickness = torus.thickness;
  22315. serializationObject.tessellation = torus.tessellation;
  22316. return serializationObject;
  22317. };
  22318. var serializeGround = function (ground) {
  22319. var serializationObject = serializePrimitive(ground);
  22320. serializationObject.width = ground.width;
  22321. serializationObject.height = ground.height;
  22322. serializationObject.subdivisions = ground.subdivisions;
  22323. return serializationObject;
  22324. };
  22325. var serializePlane = function (plane) {
  22326. var serializationObject = serializePrimitive(plane);
  22327. serializationObject.size = plane.size;
  22328. return serializationObject;
  22329. };
  22330. var serializeTorusKnot = function (torusKnot) {
  22331. var serializationObject = serializePrimitive(torusKnot);
  22332. serializationObject.radius = torusKnot.radius;
  22333. serializationObject.tube = torusKnot.tube;
  22334. serializationObject.radialSegments = torusKnot.radialSegments;
  22335. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22336. serializationObject.p = torusKnot.p;
  22337. serializationObject.q = torusKnot.q;
  22338. return serializationObject;
  22339. };
  22340. var serializeMesh = function (mesh, serializationScene) {
  22341. var serializationObject = {};
  22342. serializationObject.name = mesh.name;
  22343. serializationObject.id = mesh.id;
  22344. if (BABYLON.Tags.HasTags(mesh)) {
  22345. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22346. }
  22347. serializationObject.position = mesh.position.asArray();
  22348. if (mesh.rotationQuaternion) {
  22349. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22350. }
  22351. else if (mesh.rotation) {
  22352. serializationObject.rotation = mesh.rotation.asArray();
  22353. }
  22354. serializationObject.scaling = mesh.scaling.asArray();
  22355. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22356. serializationObject.isEnabled = mesh.isEnabled();
  22357. serializationObject.isVisible = mesh.isVisible;
  22358. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22359. serializationObject.pickable = mesh.isPickable;
  22360. serializationObject.receiveShadows = mesh.receiveShadows;
  22361. serializationObject.billboardMode = mesh.billboardMode;
  22362. serializationObject.visibility = mesh.visibility;
  22363. serializationObject.checkCollisions = mesh.checkCollisions;
  22364. // Parent
  22365. if (mesh.parent) {
  22366. serializationObject.parentId = mesh.parent.id;
  22367. }
  22368. // Geometry
  22369. var geometry = mesh._geometry;
  22370. if (geometry) {
  22371. var geometryId = geometry.id;
  22372. serializationObject.geometryId = geometryId;
  22373. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22374. // 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
  22375. serializeGeometry(geometry, serializationScene.geometries);
  22376. }
  22377. // SubMeshes
  22378. serializationObject.subMeshes = [];
  22379. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22380. var subMesh = mesh.subMeshes[subIndex];
  22381. serializationObject.subMeshes.push({
  22382. materialIndex: subMesh.materialIndex,
  22383. verticesStart: subMesh.verticesStart,
  22384. verticesCount: subMesh.verticesCount,
  22385. indexStart: subMesh.indexStart,
  22386. indexCount: subMesh.indexCount
  22387. });
  22388. }
  22389. }
  22390. // Material
  22391. if (mesh.material) {
  22392. serializationObject.materialId = mesh.material.id;
  22393. }
  22394. else {
  22395. mesh.material = null;
  22396. }
  22397. // Skeleton
  22398. if (mesh.skeleton) {
  22399. serializationObject.skeletonId = mesh.skeleton.id;
  22400. }
  22401. // Physics
  22402. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22403. serializationObject.physicsMass = mesh.getPhysicsMass();
  22404. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22405. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22406. switch (mesh.getPhysicsImpostor()) {
  22407. case BABYLON.PhysicsEngine.BoxImpostor:
  22408. serializationObject.physicsImpostor = 1;
  22409. break;
  22410. case BABYLON.PhysicsEngine.SphereImpostor:
  22411. serializationObject.physicsImpostor = 2;
  22412. break;
  22413. }
  22414. }
  22415. // Instances
  22416. serializationObject.instances = [];
  22417. for (var index = 0; index < mesh.instances.length; index++) {
  22418. var instance = mesh.instances[index];
  22419. var serializationInstance = {
  22420. name: instance.name,
  22421. position: instance.position,
  22422. rotation: instance.rotation,
  22423. rotationQuaternion: instance.rotationQuaternion,
  22424. scaling: instance.scaling
  22425. };
  22426. serializationObject.instances.push(serializationInstance);
  22427. // Animations
  22428. appendAnimations(instance, serializationInstance);
  22429. }
  22430. // Animations
  22431. appendAnimations(mesh, serializationObject);
  22432. // Layer mask
  22433. serializationObject.layerMask = mesh.layerMask;
  22434. return serializationObject;
  22435. };
  22436. var SceneSerializer = (function () {
  22437. function SceneSerializer() {
  22438. }
  22439. SceneSerializer.Serialize = function (scene) {
  22440. var serializationObject = {};
  22441. // Scene
  22442. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22443. serializationObject.autoClear = scene.autoClear;
  22444. serializationObject.clearColor = scene.clearColor.asArray();
  22445. serializationObject.ambientColor = scene.ambientColor.asArray();
  22446. serializationObject.gravity = scene.gravity.asArray();
  22447. // Fog
  22448. if (scene.fogMode && scene.fogMode !== 0) {
  22449. serializationObject.fogMode = scene.fogMode;
  22450. serializationObject.fogColor = scene.fogColor.asArray();
  22451. serializationObject.fogStart = scene.fogStart;
  22452. serializationObject.fogEnd = scene.fogEnd;
  22453. serializationObject.fogDensity = scene.fogDensity;
  22454. }
  22455. // Lights
  22456. serializationObject.lights = [];
  22457. for (var index = 0; index < scene.lights.length; index++) {
  22458. var light = scene.lights[index];
  22459. serializationObject.lights.push(serializeLight(light));
  22460. }
  22461. // Cameras
  22462. serializationObject.cameras = [];
  22463. for (index = 0; index < scene.cameras.length; index++) {
  22464. var camera = scene.cameras[index];
  22465. serializationObject.cameras.push(serializeCamera(camera));
  22466. }
  22467. if (scene.activeCamera) {
  22468. serializationObject.activeCameraID = scene.activeCamera.id;
  22469. }
  22470. // Materials
  22471. serializationObject.materials = [];
  22472. serializationObject.multiMaterials = [];
  22473. for (index = 0; index < scene.materials.length; index++) {
  22474. var material = scene.materials[index];
  22475. if (material instanceof BABYLON.StandardMaterial) {
  22476. serializationObject.materials.push(serializeMaterial(material));
  22477. }
  22478. else if (material instanceof BABYLON.MultiMaterial) {
  22479. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22480. }
  22481. }
  22482. // Skeletons
  22483. serializationObject.skeletons = [];
  22484. for (index = 0; index < scene.skeletons.length; index++) {
  22485. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22486. }
  22487. // Geometries
  22488. serializationObject.geometries = {};
  22489. serializationObject.geometries.boxes = [];
  22490. serializationObject.geometries.spheres = [];
  22491. serializationObject.geometries.cylinders = [];
  22492. serializationObject.geometries.toruses = [];
  22493. serializationObject.geometries.grounds = [];
  22494. serializationObject.geometries.planes = [];
  22495. serializationObject.geometries.torusKnots = [];
  22496. serializationObject.geometries.vertexData = [];
  22497. serializedGeometries = [];
  22498. var geometries = scene.getGeometries();
  22499. for (index = 0; index < geometries.length; index++) {
  22500. var geometry = geometries[index];
  22501. if (geometry.isReady()) {
  22502. serializeGeometry(geometry, serializationObject.geometries);
  22503. }
  22504. }
  22505. // Meshes
  22506. serializationObject.meshes = [];
  22507. for (index = 0; index < scene.meshes.length; index++) {
  22508. var abstractMesh = scene.meshes[index];
  22509. if (abstractMesh instanceof BABYLON.Mesh) {
  22510. var mesh = abstractMesh;
  22511. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22512. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22513. }
  22514. }
  22515. }
  22516. // Particles Systems
  22517. serializationObject.particleSystems = [];
  22518. for (index = 0; index < scene.particleSystems.length; index++) {
  22519. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22520. }
  22521. // Lens flares
  22522. serializationObject.lensFlareSystems = [];
  22523. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22524. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22525. }
  22526. // Shadows
  22527. serializationObject.shadowGenerators = [];
  22528. for (index = 0; index < scene.lights.length; index++) {
  22529. light = scene.lights[index];
  22530. if (light.getShadowGenerator()) {
  22531. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22532. }
  22533. }
  22534. return serializationObject;
  22535. };
  22536. return SceneSerializer;
  22537. })();
  22538. BABYLON.SceneSerializer = SceneSerializer;
  22539. })(BABYLON || (BABYLON = {}));
  22540. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22541. var BABYLON;
  22542. (function (BABYLON) {
  22543. // Unique ID when we import meshes from Babylon to CSG
  22544. var currentCSGMeshId = 0;
  22545. // # class Vertex
  22546. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22547. // one to provide additional features like texture coordinates and vertex
  22548. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22549. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22550. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22551. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22552. // is not used anywhere else.
  22553. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22554. var Vertex = (function () {
  22555. function Vertex(pos, normal, uv) {
  22556. this.pos = pos;
  22557. this.normal = normal;
  22558. this.uv = uv;
  22559. }
  22560. Vertex.prototype.clone = function () {
  22561. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22562. };
  22563. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22564. // orientation of a polygon is flipped.
  22565. Vertex.prototype.flip = function () {
  22566. this.normal = this.normal.scale(-1);
  22567. };
  22568. // Create a new vertex between this vertex and `other` by linearly
  22569. // interpolating all properties using a parameter of `t`. Subclasses should
  22570. // override this to interpolate additional properties.
  22571. Vertex.prototype.interpolate = function (other, t) {
  22572. 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));
  22573. };
  22574. return Vertex;
  22575. })();
  22576. // # class Plane
  22577. // Represents a plane in 3D space.
  22578. var Plane = (function () {
  22579. function Plane(normal, w) {
  22580. this.normal = normal;
  22581. this.w = w;
  22582. }
  22583. Plane.FromPoints = function (a, b, c) {
  22584. var v0 = c.subtract(a);
  22585. var v1 = b.subtract(a);
  22586. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22587. return null;
  22588. }
  22589. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  22590. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  22591. };
  22592. Plane.prototype.clone = function () {
  22593. return new Plane(this.normal.clone(), this.w);
  22594. };
  22595. Plane.prototype.flip = function () {
  22596. this.normal.scaleInPlace(-1);
  22597. this.w = -this.w;
  22598. };
  22599. // Split `polygon` by this plane if needed, then put the polygon or polygon
  22600. // fragments in the appropriate lists. Coplanar polygons go into either
  22601. // `coplanarFront` or `coplanarBack` depending on their orientation with
  22602. // respect to this plane. Polygons in front or in back of this plane go into
  22603. // either `front` or `back`.
  22604. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  22605. var COPLANAR = 0;
  22606. var FRONT = 1;
  22607. var BACK = 2;
  22608. var SPANNING = 3;
  22609. // Classify each point as well as the entire polygon into one of the above
  22610. // four classes.
  22611. var polygonType = 0;
  22612. var types = [];
  22613. for (var i = 0; i < polygon.vertices.length; i++) {
  22614. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  22615. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  22616. polygonType |= type;
  22617. types.push(type);
  22618. }
  22619. switch (polygonType) {
  22620. case COPLANAR:
  22621. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  22622. break;
  22623. case FRONT:
  22624. front.push(polygon);
  22625. break;
  22626. case BACK:
  22627. back.push(polygon);
  22628. break;
  22629. case SPANNING:
  22630. var f = [], b = [];
  22631. for (i = 0; i < polygon.vertices.length; i++) {
  22632. var j = (i + 1) % polygon.vertices.length;
  22633. var ti = types[i], tj = types[j];
  22634. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  22635. if (ti != BACK)
  22636. f.push(vi);
  22637. if (ti != FRONT)
  22638. b.push(ti != BACK ? vi.clone() : vi);
  22639. if ((ti | tj) == SPANNING) {
  22640. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  22641. var v = vi.interpolate(vj, t);
  22642. f.push(v);
  22643. b.push(v.clone());
  22644. }
  22645. }
  22646. if (f.length >= 3) {
  22647. var poly = new Polygon(f, polygon.shared);
  22648. if (poly.plane)
  22649. front.push(poly);
  22650. }
  22651. if (b.length >= 3) {
  22652. poly = new Polygon(b, polygon.shared);
  22653. if (poly.plane)
  22654. back.push(poly);
  22655. }
  22656. break;
  22657. }
  22658. };
  22659. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  22660. // point is on the plane.
  22661. Plane.EPSILON = 1e-5;
  22662. return Plane;
  22663. })();
  22664. // # class Polygon
  22665. // Represents a convex polygon. The vertices used to initialize a polygon must
  22666. // be coplanar and form a convex loop.
  22667. //
  22668. // Each convex polygon has a `shared` property, which is shared between all
  22669. // polygons that are clones of each other or were split from the same polygon.
  22670. // This can be used to define per-polygon properties (such as surface color).
  22671. var Polygon = (function () {
  22672. function Polygon(vertices, shared) {
  22673. this.vertices = vertices;
  22674. this.shared = shared;
  22675. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  22676. }
  22677. Polygon.prototype.clone = function () {
  22678. var vertices = this.vertices.map(function (v) { return v.clone(); });
  22679. return new Polygon(vertices, this.shared);
  22680. };
  22681. Polygon.prototype.flip = function () {
  22682. this.vertices.reverse().map(function (v) {
  22683. v.flip();
  22684. });
  22685. this.plane.flip();
  22686. };
  22687. return Polygon;
  22688. })();
  22689. // # class Node
  22690. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  22691. // by picking a polygon to split along. That polygon (and all other coplanar
  22692. // polygons) are added directly to that node and the other polygons are added to
  22693. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  22694. // no distinction between internal and leaf nodes.
  22695. var Node = (function () {
  22696. function Node(polygons) {
  22697. this.plane = null;
  22698. this.front = null;
  22699. this.back = null;
  22700. this.polygons = [];
  22701. if (polygons) {
  22702. this.build(polygons);
  22703. }
  22704. }
  22705. Node.prototype.clone = function () {
  22706. var node = new Node();
  22707. node.plane = this.plane && this.plane.clone();
  22708. node.front = this.front && this.front.clone();
  22709. node.back = this.back && this.back.clone();
  22710. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  22711. return node;
  22712. };
  22713. // Convert solid space to empty space and empty space to solid space.
  22714. Node.prototype.invert = function () {
  22715. for (var i = 0; i < this.polygons.length; i++) {
  22716. this.polygons[i].flip();
  22717. }
  22718. if (this.plane) {
  22719. this.plane.flip();
  22720. }
  22721. if (this.front) {
  22722. this.front.invert();
  22723. }
  22724. if (this.back) {
  22725. this.back.invert();
  22726. }
  22727. var temp = this.front;
  22728. this.front = this.back;
  22729. this.back = temp;
  22730. };
  22731. // Recursively remove all polygons in `polygons` that are inside this BSP
  22732. // tree.
  22733. Node.prototype.clipPolygons = function (polygons) {
  22734. if (!this.plane)
  22735. return polygons.slice();
  22736. var front = [], back = [];
  22737. for (var i = 0; i < polygons.length; i++) {
  22738. this.plane.splitPolygon(polygons[i], front, back, front, back);
  22739. }
  22740. if (this.front) {
  22741. front = this.front.clipPolygons(front);
  22742. }
  22743. if (this.back) {
  22744. back = this.back.clipPolygons(back);
  22745. }
  22746. else {
  22747. back = [];
  22748. }
  22749. return front.concat(back);
  22750. };
  22751. // Remove all polygons in this BSP tree that are inside the other BSP tree
  22752. // `bsp`.
  22753. Node.prototype.clipTo = function (bsp) {
  22754. this.polygons = bsp.clipPolygons(this.polygons);
  22755. if (this.front)
  22756. this.front.clipTo(bsp);
  22757. if (this.back)
  22758. this.back.clipTo(bsp);
  22759. };
  22760. // Return a list of all polygons in this BSP tree.
  22761. Node.prototype.allPolygons = function () {
  22762. var polygons = this.polygons.slice();
  22763. if (this.front)
  22764. polygons = polygons.concat(this.front.allPolygons());
  22765. if (this.back)
  22766. polygons = polygons.concat(this.back.allPolygons());
  22767. return polygons;
  22768. };
  22769. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  22770. // new polygons are filtered down to the bottom of the tree and become new
  22771. // nodes there. Each set of polygons is partitioned using the first polygon
  22772. // (no heuristic is used to pick a good split).
  22773. Node.prototype.build = function (polygons) {
  22774. if (!polygons.length)
  22775. return;
  22776. if (!this.plane)
  22777. this.plane = polygons[0].plane.clone();
  22778. var front = [], back = [];
  22779. for (var i = 0; i < polygons.length; i++) {
  22780. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  22781. }
  22782. if (front.length) {
  22783. if (!this.front)
  22784. this.front = new Node();
  22785. this.front.build(front);
  22786. }
  22787. if (back.length) {
  22788. if (!this.back)
  22789. this.back = new Node();
  22790. this.back.build(back);
  22791. }
  22792. };
  22793. return Node;
  22794. })();
  22795. var CSG = (function () {
  22796. function CSG() {
  22797. this.polygons = new Array();
  22798. }
  22799. // Convert BABYLON.Mesh to BABYLON.CSG
  22800. CSG.FromMesh = function (mesh) {
  22801. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  22802. if (mesh instanceof BABYLON.Mesh) {
  22803. mesh.computeWorldMatrix(true);
  22804. var matrix = mesh.getWorldMatrix();
  22805. var meshPosition = mesh.position.clone();
  22806. var meshRotation = mesh.rotation.clone();
  22807. var meshScaling = mesh.scaling.clone();
  22808. }
  22809. else {
  22810. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  22811. }
  22812. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22813. var subMeshes = mesh.subMeshes;
  22814. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  22815. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  22816. vertices = [];
  22817. for (var j = 0; j < 3; j++) {
  22818. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  22819. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  22820. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  22821. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  22822. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  22823. vertex = new Vertex(position, normal, uv);
  22824. vertices.push(vertex);
  22825. }
  22826. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  22827. // To handle the case of degenerated triangle
  22828. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  22829. if (polygon.plane)
  22830. polygons.push(polygon);
  22831. }
  22832. }
  22833. var csg = CSG.FromPolygons(polygons);
  22834. csg.matrix = matrix;
  22835. csg.position = meshPosition;
  22836. csg.rotation = meshRotation;
  22837. csg.scaling = meshScaling;
  22838. currentCSGMeshId++;
  22839. return csg;
  22840. };
  22841. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  22842. CSG.FromPolygons = function (polygons) {
  22843. var csg = new BABYLON.CSG();
  22844. csg.polygons = polygons;
  22845. return csg;
  22846. };
  22847. CSG.prototype.clone = function () {
  22848. var csg = new BABYLON.CSG();
  22849. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  22850. csg.copyTransformAttributes(this);
  22851. return csg;
  22852. };
  22853. CSG.prototype.toPolygons = function () {
  22854. return this.polygons;
  22855. };
  22856. CSG.prototype.union = function (csg) {
  22857. var a = new Node(this.clone().polygons);
  22858. var b = new Node(csg.clone().polygons);
  22859. a.clipTo(b);
  22860. b.clipTo(a);
  22861. b.invert();
  22862. b.clipTo(a);
  22863. b.invert();
  22864. a.build(b.allPolygons());
  22865. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22866. };
  22867. CSG.prototype.unionInPlace = function (csg) {
  22868. var a = new Node(this.polygons);
  22869. var b = new Node(csg.polygons);
  22870. a.clipTo(b);
  22871. b.clipTo(a);
  22872. b.invert();
  22873. b.clipTo(a);
  22874. b.invert();
  22875. a.build(b.allPolygons());
  22876. this.polygons = a.allPolygons();
  22877. };
  22878. CSG.prototype.subtract = function (csg) {
  22879. var a = new Node(this.clone().polygons);
  22880. var b = new Node(csg.clone().polygons);
  22881. a.invert();
  22882. a.clipTo(b);
  22883. b.clipTo(a);
  22884. b.invert();
  22885. b.clipTo(a);
  22886. b.invert();
  22887. a.build(b.allPolygons());
  22888. a.invert();
  22889. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22890. };
  22891. CSG.prototype.subtractInPlace = function (csg) {
  22892. var a = new Node(this.polygons);
  22893. var b = new Node(csg.polygons);
  22894. a.invert();
  22895. a.clipTo(b);
  22896. b.clipTo(a);
  22897. b.invert();
  22898. b.clipTo(a);
  22899. b.invert();
  22900. a.build(b.allPolygons());
  22901. a.invert();
  22902. this.polygons = a.allPolygons();
  22903. };
  22904. CSG.prototype.intersect = function (csg) {
  22905. var a = new Node(this.clone().polygons);
  22906. var b = new Node(csg.clone().polygons);
  22907. a.invert();
  22908. b.clipTo(a);
  22909. b.invert();
  22910. a.clipTo(b);
  22911. b.clipTo(a);
  22912. a.build(b.allPolygons());
  22913. a.invert();
  22914. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22915. };
  22916. CSG.prototype.intersectInPlace = function (csg) {
  22917. var a = new Node(this.polygons);
  22918. var b = new Node(csg.polygons);
  22919. a.invert();
  22920. b.clipTo(a);
  22921. b.invert();
  22922. a.clipTo(b);
  22923. b.clipTo(a);
  22924. a.build(b.allPolygons());
  22925. a.invert();
  22926. this.polygons = a.allPolygons();
  22927. };
  22928. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  22929. // not modified.
  22930. CSG.prototype.inverse = function () {
  22931. var csg = this.clone();
  22932. csg.inverseInPlace();
  22933. return csg;
  22934. };
  22935. CSG.prototype.inverseInPlace = function () {
  22936. this.polygons.map(function (p) {
  22937. p.flip();
  22938. });
  22939. };
  22940. // This is used to keep meshes transformations so they can be restored
  22941. // when we build back a Babylon Mesh
  22942. // NB : All CSG operations are performed in world coordinates
  22943. CSG.prototype.copyTransformAttributes = function (csg) {
  22944. this.matrix = csg.matrix;
  22945. this.position = csg.position;
  22946. this.rotation = csg.rotation;
  22947. this.scaling = csg.scaling;
  22948. return this;
  22949. };
  22950. // Build Raw mesh from CSG
  22951. // Coordinates here are in world space
  22952. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  22953. var matrix = this.matrix.clone();
  22954. matrix.invert();
  22955. 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;
  22956. if (keepSubMeshes) {
  22957. // Sort Polygons, since subMeshes are indices range
  22958. polygons.sort(function (a, b) {
  22959. if (a.shared.meshId === b.shared.meshId) {
  22960. return a.shared.subMeshId - b.shared.subMeshId;
  22961. }
  22962. else {
  22963. return a.shared.meshId - b.shared.meshId;
  22964. }
  22965. });
  22966. }
  22967. for (var i = 0, il = polygons.length; i < il; i++) {
  22968. polygon = polygons[i];
  22969. // Building SubMeshes
  22970. if (!subMesh_dict[polygon.shared.meshId]) {
  22971. subMesh_dict[polygon.shared.meshId] = {};
  22972. }
  22973. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  22974. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  22975. indexStart: +Infinity,
  22976. indexEnd: -Infinity,
  22977. materialIndex: polygon.shared.materialIndex
  22978. };
  22979. }
  22980. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  22981. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  22982. polygonIndices[0] = 0;
  22983. polygonIndices[1] = j - 1;
  22984. polygonIndices[2] = j;
  22985. for (var k = 0; k < 3; k++) {
  22986. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  22987. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  22988. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  22989. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  22990. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  22991. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  22992. // Check if 2 points can be merged
  22993. 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)) {
  22994. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  22995. uvs.push(uv.x, uv.y);
  22996. normals.push(normal.x, normal.y, normal.z);
  22997. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  22998. }
  22999. indices.push(vertex_idx);
  23000. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  23001. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  23002. currentIndex++;
  23003. }
  23004. }
  23005. }
  23006. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  23007. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23008. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  23009. mesh.setIndices(indices);
  23010. if (keepSubMeshes) {
  23011. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  23012. var materialIndexOffset = 0, materialMaxIndex;
  23013. mesh.subMeshes.length = 0;
  23014. for (var m in subMesh_dict) {
  23015. materialMaxIndex = -1;
  23016. for (var sm in subMesh_dict[m]) {
  23017. subMesh_obj = subMesh_dict[m][sm];
  23018. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  23019. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  23020. }
  23021. materialIndexOffset += ++materialMaxIndex;
  23022. }
  23023. }
  23024. return mesh;
  23025. };
  23026. // Build Mesh from CSG taking material and transforms into account
  23027. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  23028. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  23029. mesh.material = material;
  23030. mesh.position.copyFrom(this.position);
  23031. mesh.rotation.copyFrom(this.rotation);
  23032. mesh.scaling.copyFrom(this.scaling);
  23033. mesh.computeWorldMatrix(true);
  23034. return mesh;
  23035. };
  23036. return CSG;
  23037. })();
  23038. BABYLON.CSG = CSG;
  23039. })(BABYLON || (BABYLON = {}));
  23040. //# sourceMappingURL=babylon.csg.js.map
  23041. var __extends = this.__extends || function (d, b) {
  23042. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23043. function __() { this.constructor = d; }
  23044. __.prototype = b.prototype;
  23045. d.prototype = new __();
  23046. };
  23047. var BABYLON;
  23048. (function (BABYLON) {
  23049. var OculusDistortionCorrectionPostProcess = (function (_super) {
  23050. __extends(OculusDistortionCorrectionPostProcess, _super);
  23051. //ANY
  23052. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  23053. var _this = this;
  23054. _super.call(this, name, "oculusDistortionCorrection", [
  23055. 'LensCenter',
  23056. 'Scale',
  23057. 'ScaleIn',
  23058. 'HmdWarpParam'
  23059. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23060. this._isRightEye = isRightEye;
  23061. this._distortionFactors = cameraSettings.DistortionK;
  23062. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  23063. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  23064. this.onSizeChanged = function () {
  23065. _this.aspectRatio = _this.width * .5 / _this.height;
  23066. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23067. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23068. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23069. };
  23070. this.onApply = function (effect) {
  23071. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23072. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23073. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23074. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23075. };
  23076. }
  23077. return OculusDistortionCorrectionPostProcess;
  23078. })(BABYLON.PostProcess);
  23079. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  23080. })(BABYLON || (BABYLON = {}));
  23081. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  23082. // Mainly based on these 2 articles :
  23083. // 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
  23084. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23085. var BABYLON;
  23086. (function (BABYLON) {
  23087. (function (JoystickAxis) {
  23088. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23089. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23090. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23091. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23092. var JoystickAxis = BABYLON.JoystickAxis;
  23093. var VirtualJoystick = (function () {
  23094. function VirtualJoystick(leftJoystick) {
  23095. var _this = this;
  23096. if (leftJoystick) {
  23097. this._leftJoystick = true;
  23098. }
  23099. else {
  23100. this._leftJoystick = false;
  23101. }
  23102. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23103. VirtualJoystick._globalJoystickIndex++;
  23104. // By default left & right arrow keys are moving the X
  23105. // and up & down keys are moving the Y
  23106. this._axisTargetedByLeftAndRight = 0 /* X */;
  23107. this._axisTargetedByUpAndDown = 1 /* Y */;
  23108. this.reverseLeftRight = false;
  23109. this.reverseUpDown = false;
  23110. // collections of pointers
  23111. this._touches = new BABYLON.SmartCollection();
  23112. this.deltaPosition = BABYLON.Vector3.Zero();
  23113. this._joystickSensibility = 25;
  23114. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23115. this._rotationSpeed = 25;
  23116. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23117. this._rotateOnAxisRelativeToMesh = false;
  23118. // injecting a canvas element on top of the canvas 3D game
  23119. if (!VirtualJoystick.vjCanvas) {
  23120. window.addEventListener("resize", function () {
  23121. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23122. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23123. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23124. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23126. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23127. }, false);
  23128. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23129. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23130. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23131. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23132. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23133. VirtualJoystick.vjCanvas.style.width = "100%";
  23134. VirtualJoystick.vjCanvas.style.height = "100%";
  23135. VirtualJoystick.vjCanvas.style.position = "absolute";
  23136. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23137. VirtualJoystick.vjCanvas.style.top = "0px";
  23138. VirtualJoystick.vjCanvas.style.left = "0px";
  23139. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23140. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23141. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23142. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23143. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23144. document.body.appendChild(VirtualJoystick.vjCanvas);
  23145. }
  23146. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23147. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23148. this.pressed = false;
  23149. // default joystick color
  23150. this._joystickColor = "cyan";
  23151. this._joystickPointerID = -1;
  23152. // current joystick position
  23153. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23154. // origin joystick position
  23155. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23156. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23157. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23158. _this._onPointerDown(evt);
  23159. }, false);
  23160. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23161. _this._onPointerMove(evt);
  23162. }, false);
  23163. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23164. _this._onPointerUp(evt);
  23165. }, false);
  23166. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23167. _this._onPointerUp(evt);
  23168. }, false);
  23169. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23170. evt.preventDefault(); // Disables system menu
  23171. }, false);
  23172. requestAnimationFrame(function () {
  23173. _this._drawVirtualJoystick();
  23174. });
  23175. }
  23176. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23177. this._joystickSensibility = newJoystickSensibility;
  23178. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23179. };
  23180. VirtualJoystick.prototype._onPointerDown = function (e) {
  23181. var positionOnScreenCondition;
  23182. e.preventDefault();
  23183. if (this._leftJoystick === true) {
  23184. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23185. }
  23186. else {
  23187. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23188. }
  23189. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23190. // First contact will be dedicated to the virtual joystick
  23191. this._joystickPointerID = e.pointerId;
  23192. this._joystickPointerStartPos.x = e.clientX;
  23193. this._joystickPointerStartPos.y = e.clientY;
  23194. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23195. this._deltaJoystickVector.x = 0;
  23196. this._deltaJoystickVector.y = 0;
  23197. this.pressed = true;
  23198. this._touches.add(e.pointerId.toString(), e);
  23199. }
  23200. else {
  23201. // You can only trigger the action buttons with a joystick declared
  23202. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23203. this._action();
  23204. this._touches.add(e.pointerId.toString(), e);
  23205. }
  23206. }
  23207. };
  23208. VirtualJoystick.prototype._onPointerMove = function (e) {
  23209. // If the current pointer is the one associated to the joystick (first touch contact)
  23210. if (this._joystickPointerID == e.pointerId) {
  23211. this._joystickPointerPos.x = e.clientX;
  23212. this._joystickPointerPos.y = e.clientY;
  23213. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23214. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23215. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23216. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23217. switch (this._axisTargetedByLeftAndRight) {
  23218. case 0 /* X */:
  23219. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23220. break;
  23221. case 1 /* Y */:
  23222. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23223. break;
  23224. case 2 /* Z */:
  23225. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23226. break;
  23227. }
  23228. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23229. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23230. switch (this._axisTargetedByUpAndDown) {
  23231. case 0 /* X */:
  23232. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23233. break;
  23234. case 1 /* Y */:
  23235. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23236. break;
  23237. case 2 /* Z */:
  23238. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23239. break;
  23240. }
  23241. }
  23242. else {
  23243. if (this._touches.item(e.pointerId.toString())) {
  23244. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23245. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23246. }
  23247. }
  23248. };
  23249. VirtualJoystick.prototype._onPointerUp = function (e) {
  23250. this._clearCanvas();
  23251. if (this._joystickPointerID == e.pointerId) {
  23252. this._joystickPointerID = -1;
  23253. this.pressed = false;
  23254. }
  23255. this._deltaJoystickVector.x = 0;
  23256. this._deltaJoystickVector.y = 0;
  23257. this._touches.remove(e.pointerId.toString());
  23258. };
  23259. /**
  23260. * Change the color of the virtual joystick
  23261. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23262. */
  23263. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23264. this._joystickColor = newColor;
  23265. };
  23266. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23267. this._action = action;
  23268. };
  23269. // Define which axis you'd like to control for left & right
  23270. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23271. switch (axis) {
  23272. case 0 /* X */:
  23273. case 1 /* Y */:
  23274. case 2 /* Z */:
  23275. this._axisTargetedByLeftAndRight = axis;
  23276. break;
  23277. default:
  23278. this._axisTargetedByLeftAndRight = 0 /* X */;
  23279. break;
  23280. }
  23281. };
  23282. // Define which axis you'd like to control for up & down
  23283. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23284. switch (axis) {
  23285. case 0 /* X */:
  23286. case 1 /* Y */:
  23287. case 2 /* Z */:
  23288. this._axisTargetedByUpAndDown = axis;
  23289. break;
  23290. default:
  23291. this._axisTargetedByUpAndDown = 1 /* Y */;
  23292. break;
  23293. }
  23294. };
  23295. VirtualJoystick.prototype._clearCanvas = function () {
  23296. if (this._leftJoystick) {
  23297. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23298. }
  23299. else {
  23300. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23301. }
  23302. };
  23303. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23304. var _this = this;
  23305. if (this.pressed) {
  23306. this._clearCanvas();
  23307. this._touches.forEach(function (touch) {
  23308. if (touch.pointerId === _this._joystickPointerID) {
  23309. VirtualJoystick.vjCanvasContext.beginPath();
  23310. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23311. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23312. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23313. VirtualJoystick.vjCanvasContext.stroke();
  23314. VirtualJoystick.vjCanvasContext.beginPath();
  23315. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23316. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23317. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23318. VirtualJoystick.vjCanvasContext.stroke();
  23319. VirtualJoystick.vjCanvasContext.beginPath();
  23320. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23321. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23322. VirtualJoystick.vjCanvasContext.stroke();
  23323. }
  23324. else {
  23325. VirtualJoystick.vjCanvasContext.beginPath();
  23326. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23327. VirtualJoystick.vjCanvasContext.beginPath();
  23328. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23329. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23330. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23331. VirtualJoystick.vjCanvasContext.stroke();
  23332. }
  23333. ;
  23334. });
  23335. }
  23336. requestAnimationFrame(function () {
  23337. _this._drawVirtualJoystick();
  23338. });
  23339. };
  23340. VirtualJoystick.prototype.releaseCanvas = function () {
  23341. if (VirtualJoystick.vjCanvas) {
  23342. document.body.removeChild(VirtualJoystick.vjCanvas);
  23343. VirtualJoystick.vjCanvas = null;
  23344. }
  23345. };
  23346. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23347. VirtualJoystick._globalJoystickIndex = 0;
  23348. return VirtualJoystick;
  23349. })();
  23350. BABYLON.VirtualJoystick = VirtualJoystick;
  23351. })(BABYLON || (BABYLON = {}));
  23352. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23353. var __extends = this.__extends || function (d, b) {
  23354. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23355. function __() { this.constructor = d; }
  23356. __.prototype = b.prototype;
  23357. d.prototype = new __();
  23358. };
  23359. var BABYLON;
  23360. (function (BABYLON) {
  23361. var OculusRiftDevKit2013_Metric = {
  23362. HResolution: 1280,
  23363. VResolution: 800,
  23364. HScreenSize: 0.149759993,
  23365. VScreenSize: 0.0935999975,
  23366. VScreenCenter: 0.0467999987,
  23367. EyeToScreenDistance: 0.0410000011,
  23368. LensSeparationDistance: 0.0635000020,
  23369. InterpupillaryDistance: 0.0640000030,
  23370. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23371. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23372. PostProcessScaleFactor: 1.714605507808412,
  23373. LensCenterOffset: 0.151976421
  23374. };
  23375. var _OculusInnerCamera = (function (_super) {
  23376. __extends(_OculusInnerCamera, _super);
  23377. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  23378. _super.call(this, name, position, scene);
  23379. this._workMatrix = new BABYLON.Matrix();
  23380. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23381. // Constants
  23382. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23383. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23384. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23385. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23386. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23387. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23388. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23389. // Postprocess
  23390. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23391. }
  23392. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  23393. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23394. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23395. return this._projectionMatrix;
  23396. };
  23397. _OculusInnerCamera.prototype._getViewMatrix = function () {
  23398. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23399. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23400. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23401. // Computing target and final matrix
  23402. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23403. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23404. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23405. return this._viewMatrix;
  23406. };
  23407. return _OculusInnerCamera;
  23408. })(BABYLON.FreeCamera);
  23409. var OculusCamera = (function (_super) {
  23410. __extends(OculusCamera, _super);
  23411. function OculusCamera(name, position, scene) {
  23412. _super.call(this, name, position, scene);
  23413. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  23414. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  23415. this.subCameras.push(this._leftCamera);
  23416. this.subCameras.push(this._rightCamera);
  23417. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23418. }
  23419. OculusCamera.prototype._update = function () {
  23420. this._leftCamera.position.copyFrom(this.position);
  23421. this._rightCamera.position.copyFrom(this.position);
  23422. this._updateCamera(this._leftCamera);
  23423. this._updateCamera(this._rightCamera);
  23424. _super.prototype._update.call(this);
  23425. };
  23426. OculusCamera.prototype._updateCamera = function (camera) {
  23427. camera.minZ = this.minZ;
  23428. camera.maxZ = this.maxZ;
  23429. camera.rotation.x = this.rotation.x;
  23430. camera.rotation.y = this.rotation.y;
  23431. camera.rotation.z = this.rotation.z;
  23432. };
  23433. // Oculus events
  23434. OculusCamera.prototype._onOrientationEvent = function (evt) {
  23435. var yaw = evt.alpha / 180 * Math.PI;
  23436. var pitch = evt.beta / 180 * Math.PI;
  23437. var roll = evt.gamma / 180 * Math.PI;
  23438. if (!this._offsetOrientation) {
  23439. this._offsetOrientation = {
  23440. yaw: yaw,
  23441. pitch: pitch,
  23442. roll: roll
  23443. };
  23444. return;
  23445. }
  23446. else {
  23447. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23448. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23449. this.rotation.z += this._offsetOrientation.roll - roll;
  23450. this._offsetOrientation.yaw = yaw;
  23451. this._offsetOrientation.pitch = pitch;
  23452. this._offsetOrientation.roll = roll;
  23453. }
  23454. };
  23455. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  23456. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23457. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23458. };
  23459. OculusCamera.prototype.detachControl = function (element) {
  23460. _super.prototype.detachControl.call(this, element);
  23461. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23462. };
  23463. return OculusCamera;
  23464. })(BABYLON.FreeCamera);
  23465. BABYLON.OculusCamera = OculusCamera;
  23466. })(BABYLON || (BABYLON = {}));
  23467. //# sourceMappingURL=babylon.oculusCamera.js.map
  23468. var __extends = this.__extends || function (d, b) {
  23469. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23470. function __() { this.constructor = d; }
  23471. __.prototype = b.prototype;
  23472. d.prototype = new __();
  23473. };
  23474. var BABYLON;
  23475. (function (BABYLON) {
  23476. var OculusRiftDevKit2013_Metric = {
  23477. HResolution: 1280,
  23478. VResolution: 800,
  23479. HScreenSize: 0.149759993,
  23480. VScreenSize: 0.0935999975,
  23481. VScreenCenter: 0.0467999987,
  23482. EyeToScreenDistance: 0.0410000011,
  23483. LensSeparationDistance: 0.0635000020,
  23484. InterpupillaryDistance: 0.0640000030,
  23485. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23486. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23487. PostProcessScaleFactor: 1.714605507808412,
  23488. LensCenterOffset: 0.151976421
  23489. };
  23490. var _OculusInnerGamepadCamera = (function (_super) {
  23491. __extends(_OculusInnerGamepadCamera, _super);
  23492. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  23493. _super.call(this, name, position, scene);
  23494. this._workMatrix = new BABYLON.Matrix();
  23495. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23496. // Constants
  23497. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23498. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23499. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23500. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23501. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23502. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23503. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23504. // Postprocess
  23505. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23506. }
  23507. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  23508. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23509. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23510. return this._projectionMatrix;
  23511. };
  23512. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  23513. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23514. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23515. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23516. // Computing target and final matrix
  23517. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23518. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23519. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23520. return this._viewMatrix;
  23521. };
  23522. return _OculusInnerGamepadCamera;
  23523. })(BABYLON.FreeCamera);
  23524. var OculusGamepadCamera = (function (_super) {
  23525. __extends(OculusGamepadCamera, _super);
  23526. function OculusGamepadCamera(name, position, scene) {
  23527. var _this = this;
  23528. _super.call(this, name, position, scene);
  23529. this.angularSensibility = 200;
  23530. this.moveSensibility = 75;
  23531. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  23532. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  23533. this.subCameras.push(this._leftCamera);
  23534. this.subCameras.push(this._rightCamera);
  23535. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23536. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23537. _this._onNewGameConnected(gamepad);
  23538. });
  23539. }
  23540. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23541. // Only the first gamepad can control the camera
  23542. if (gamepad.index === 0) {
  23543. this._gamepad = gamepad;
  23544. }
  23545. };
  23546. OculusGamepadCamera.prototype._update = function () {
  23547. this._leftCamera.position.copyFrom(this.position);
  23548. this._rightCamera.position.copyFrom(this.position);
  23549. this._updateCamera(this._leftCamera);
  23550. this._updateCamera(this._rightCamera);
  23551. _super.prototype._update.call(this);
  23552. };
  23553. OculusGamepadCamera.prototype._checkInputs = function () {
  23554. if (!this._gamepad) {
  23555. return;
  23556. }
  23557. var LSValues = this._gamepad.leftStick;
  23558. var normalizedLX = LSValues.x / this.moveSensibility;
  23559. var normalizedLY = LSValues.y / this.moveSensibility;
  23560. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23561. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23562. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23563. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23564. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23565. };
  23566. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  23567. camera.minZ = this.minZ;
  23568. camera.maxZ = this.maxZ;
  23569. camera.rotation.x = this.rotation.x;
  23570. camera.rotation.y = this.rotation.y;
  23571. camera.rotation.z = this.rotation.z;
  23572. };
  23573. // Oculus events
  23574. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  23575. var yaw = evt.alpha / 180 * Math.PI;
  23576. var pitch = evt.beta / 180 * Math.PI;
  23577. var roll = evt.gamma / 180 * Math.PI;
  23578. if (!this._offsetOrientation) {
  23579. this._offsetOrientation = {
  23580. yaw: yaw,
  23581. pitch: pitch,
  23582. roll: roll
  23583. };
  23584. return;
  23585. }
  23586. else {
  23587. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23588. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23589. this.rotation.z += this._offsetOrientation.roll - roll;
  23590. this._offsetOrientation.yaw = yaw;
  23591. this._offsetOrientation.pitch = pitch;
  23592. this._offsetOrientation.roll = roll;
  23593. }
  23594. };
  23595. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  23596. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23597. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23598. };
  23599. OculusGamepadCamera.prototype.detachControl = function (element) {
  23600. _super.prototype.detachControl.call(this, element);
  23601. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23602. };
  23603. OculusGamepadCamera.prototype.dispose = function () {
  23604. this._gamepads.dispose();
  23605. _super.prototype.dispose.call(this);
  23606. };
  23607. return OculusGamepadCamera;
  23608. })(BABYLON.FreeCamera);
  23609. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  23610. })(BABYLON || (BABYLON = {}));
  23611. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  23612. var __extends = this.__extends || function (d, b) {
  23613. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23614. function __() { this.constructor = d; }
  23615. __.prototype = b.prototype;
  23616. d.prototype = new __();
  23617. };
  23618. var BABYLON;
  23619. (function (BABYLON) {
  23620. // We're mainly based on the logic defined into the FreeCamera code
  23621. var VirtualJoysticksCamera = (function (_super) {
  23622. __extends(VirtualJoysticksCamera, _super);
  23623. function VirtualJoysticksCamera(name, position, scene) {
  23624. _super.call(this, name, position, scene);
  23625. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23626. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  23627. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  23628. this._leftjoystick.setJoystickSensibility(0.15);
  23629. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23630. this._rightjoystick.setAxisForUpDown(0 /* X */);
  23631. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  23632. this._rightjoystick.reverseUpDown = true;
  23633. this._rightjoystick.setJoystickSensibility(0.05);
  23634. this._rightjoystick.setJoystickColor("yellow");
  23635. }
  23636. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23637. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23638. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23639. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23640. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23641. if (!this._leftjoystick.pressed) {
  23642. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23643. }
  23644. if (!this._rightjoystick.pressed) {
  23645. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23646. }
  23647. };
  23648. VirtualJoysticksCamera.prototype.dispose = function () {
  23649. this._leftjoystick.releaseCanvas();
  23650. _super.prototype.dispose.call(this);
  23651. };
  23652. return VirtualJoysticksCamera;
  23653. })(BABYLON.FreeCamera);
  23654. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23655. })(BABYLON || (BABYLON = {}));
  23656. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23657. var __extends = this.__extends || function (d, b) {
  23658. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23659. function __() { this.constructor = d; }
  23660. __.prototype = b.prototype;
  23661. d.prototype = new __();
  23662. };
  23663. var BABYLON;
  23664. (function (BABYLON) {
  23665. var ShaderMaterial = (function (_super) {
  23666. __extends(ShaderMaterial, _super);
  23667. function ShaderMaterial(name, scene, shaderPath, options) {
  23668. _super.call(this, name, scene);
  23669. this._textures = new Array();
  23670. this._floats = new Array();
  23671. this._floatsArrays = {};
  23672. this._colors3 = new Array();
  23673. this._colors4 = new Array();
  23674. this._vectors2 = new Array();
  23675. this._vectors3 = new Array();
  23676. this._matrices = new Array();
  23677. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23678. this._shaderPath = shaderPath;
  23679. options.needAlphaBlending = options.needAlphaBlending || false;
  23680. options.needAlphaTesting = options.needAlphaTesting || false;
  23681. options.attributes = options.attributes || ["position", "normal", "uv"];
  23682. options.uniforms = options.uniforms || ["worldViewProjection"];
  23683. options.samplers = options.samplers || [];
  23684. this._options = options;
  23685. }
  23686. ShaderMaterial.prototype.needAlphaBlending = function () {
  23687. return this._options.needAlphaBlending;
  23688. };
  23689. ShaderMaterial.prototype.needAlphaTesting = function () {
  23690. return this._options.needAlphaTesting;
  23691. };
  23692. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23693. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23694. this._options.uniforms.push(uniformName);
  23695. }
  23696. };
  23697. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23698. if (this._options.samplers.indexOf(name) === -1) {
  23699. this._options.samplers.push(name);
  23700. }
  23701. this._textures[name] = texture;
  23702. return this;
  23703. };
  23704. ShaderMaterial.prototype.setFloat = function (name, value) {
  23705. this._checkUniform(name);
  23706. this._floats[name] = value;
  23707. return this;
  23708. };
  23709. ShaderMaterial.prototype.setFloats = function (name, value) {
  23710. this._checkUniform(name);
  23711. this._floatsArrays[name] = value;
  23712. return this;
  23713. };
  23714. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23715. this._checkUniform(name);
  23716. this._colors3[name] = value;
  23717. return this;
  23718. };
  23719. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23720. this._checkUniform(name);
  23721. this._colors4[name] = value;
  23722. return this;
  23723. };
  23724. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23725. this._checkUniform(name);
  23726. this._vectors2[name] = value;
  23727. return this;
  23728. };
  23729. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23730. this._checkUniform(name);
  23731. this._vectors3[name] = value;
  23732. return this;
  23733. };
  23734. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23735. this._checkUniform(name);
  23736. this._matrices[name] = value;
  23737. return this;
  23738. };
  23739. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23740. var scene = this.getScene();
  23741. var engine = scene.getEngine();
  23742. if (!this.checkReadyOnEveryCall) {
  23743. if (this._renderId === scene.getRenderId()) {
  23744. return true;
  23745. }
  23746. }
  23747. // Instances
  23748. var defines = [];
  23749. var fallbacks = new BABYLON.EffectFallbacks();
  23750. if (useInstances) {
  23751. defines.push("#define INSTANCES");
  23752. }
  23753. // Bones
  23754. if (mesh && mesh.useBones) {
  23755. defines.push("#define BONES");
  23756. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23757. defines.push("#define BONES4");
  23758. fallbacks.addFallback(0, "BONES4");
  23759. }
  23760. // Alpha test
  23761. if (engine.getAlphaTesting()) {
  23762. defines.push("#define ALPHATEST");
  23763. }
  23764. var previousEffect = this._effect;
  23765. var join = defines.join("\n");
  23766. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23767. if (!this._effect.isReady()) {
  23768. return false;
  23769. }
  23770. if (previousEffect !== this._effect) {
  23771. scene.resetCachedMaterial();
  23772. }
  23773. this._renderId = scene.getRenderId();
  23774. return true;
  23775. };
  23776. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23777. var scene = this.getScene();
  23778. if (this._options.uniforms.indexOf("world") !== -1) {
  23779. this._effect.setMatrix("world", world);
  23780. }
  23781. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23782. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23783. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23784. }
  23785. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23786. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23787. }
  23788. };
  23789. ShaderMaterial.prototype.bind = function (world, mesh) {
  23790. // Std values
  23791. this.bindOnlyWorldMatrix(world);
  23792. if (this.getScene().getCachedMaterial() !== this) {
  23793. if (this._options.uniforms.indexOf("view") !== -1) {
  23794. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23795. }
  23796. if (this._options.uniforms.indexOf("projection") !== -1) {
  23797. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23798. }
  23799. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23800. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23801. }
  23802. // Bones
  23803. if (mesh && mesh.useBones) {
  23804. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23805. }
  23806. for (var name in this._textures) {
  23807. this._effect.setTexture(name, this._textures[name]);
  23808. }
  23809. for (name in this._floats) {
  23810. this._effect.setFloat(name, this._floats[name]);
  23811. }
  23812. for (name in this._floatsArrays) {
  23813. this._effect.setArray(name, this._floatsArrays[name]);
  23814. }
  23815. for (name in this._colors3) {
  23816. this._effect.setColor3(name, this._colors3[name]);
  23817. }
  23818. for (name in this._colors4) {
  23819. var color = this._colors4[name];
  23820. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23821. }
  23822. for (name in this._vectors2) {
  23823. this._effect.setVector2(name, this._vectors2[name]);
  23824. }
  23825. for (name in this._vectors3) {
  23826. this._effect.setVector3(name, this._vectors3[name]);
  23827. }
  23828. for (name in this._matrices) {
  23829. this._effect.setMatrix(name, this._matrices[name]);
  23830. }
  23831. }
  23832. _super.prototype.bind.call(this, world, mesh);
  23833. };
  23834. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23835. for (var name in this._textures) {
  23836. this._textures[name].dispose();
  23837. }
  23838. this._textures = [];
  23839. _super.prototype.dispose.call(this, forceDisposeEffect);
  23840. };
  23841. return ShaderMaterial;
  23842. })(BABYLON.Material);
  23843. BABYLON.ShaderMaterial = ShaderMaterial;
  23844. })(BABYLON || (BABYLON = {}));
  23845. //# sourceMappingURL=babylon.shaderMaterial.js.map
  23846. var BABYLON;
  23847. (function (BABYLON) {
  23848. var VertexData = (function () {
  23849. function VertexData() {
  23850. }
  23851. VertexData.prototype.set = function (data, kind) {
  23852. switch (kind) {
  23853. case BABYLON.VertexBuffer.PositionKind:
  23854. this.positions = data;
  23855. break;
  23856. case BABYLON.VertexBuffer.NormalKind:
  23857. this.normals = data;
  23858. break;
  23859. case BABYLON.VertexBuffer.UVKind:
  23860. this.uvs = data;
  23861. break;
  23862. case BABYLON.VertexBuffer.UV2Kind:
  23863. this.uv2s = data;
  23864. break;
  23865. case BABYLON.VertexBuffer.ColorKind:
  23866. this.colors = data;
  23867. break;
  23868. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23869. this.matricesIndices = data;
  23870. break;
  23871. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23872. this.matricesWeights = data;
  23873. break;
  23874. }
  23875. };
  23876. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23877. this._applyTo(mesh, updatable);
  23878. };
  23879. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23880. this._applyTo(geometry, updatable);
  23881. };
  23882. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23883. this._update(mesh);
  23884. };
  23885. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23886. this._update(geometry);
  23887. };
  23888. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23889. if (this.positions) {
  23890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23891. }
  23892. if (this.normals) {
  23893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23894. }
  23895. if (this.uvs) {
  23896. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23897. }
  23898. if (this.uv2s) {
  23899. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  23900. }
  23901. if (this.colors) {
  23902. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23903. }
  23904. if (this.matricesIndices) {
  23905. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23906. }
  23907. if (this.matricesWeights) {
  23908. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23909. }
  23910. if (this.indices) {
  23911. meshOrGeometry.setIndices(this.indices);
  23912. }
  23913. };
  23914. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23915. if (this.positions) {
  23916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23917. }
  23918. if (this.normals) {
  23919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23920. }
  23921. if (this.uvs) {
  23922. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23923. }
  23924. if (this.uv2s) {
  23925. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  23926. }
  23927. if (this.colors) {
  23928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23929. }
  23930. if (this.matricesIndices) {
  23931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23932. }
  23933. if (this.matricesWeights) {
  23934. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23935. }
  23936. if (this.indices) {
  23937. meshOrGeometry.setIndices(this.indices);
  23938. }
  23939. };
  23940. VertexData.prototype.transform = function (matrix) {
  23941. var transformed = BABYLON.Vector3.Zero();
  23942. if (this.positions) {
  23943. var position = BABYLON.Vector3.Zero();
  23944. for (var index = 0; index < this.positions.length; index += 3) {
  23945. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23946. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23947. this.positions[index] = transformed.x;
  23948. this.positions[index + 1] = transformed.y;
  23949. this.positions[index + 2] = transformed.z;
  23950. }
  23951. }
  23952. if (this.normals) {
  23953. var normal = BABYLON.Vector3.Zero();
  23954. for (index = 0; index < this.normals.length; index += 3) {
  23955. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23956. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23957. this.normals[index] = transformed.x;
  23958. this.normals[index + 1] = transformed.y;
  23959. this.normals[index + 2] = transformed.z;
  23960. }
  23961. }
  23962. };
  23963. VertexData.prototype.merge = function (other) {
  23964. if (other.indices) {
  23965. if (!this.indices) {
  23966. this.indices = [];
  23967. }
  23968. var offset = this.positions ? this.positions.length / 3 : 0;
  23969. for (var index = 0; index < other.indices.length; index++) {
  23970. this.indices.push(other.indices[index] + offset);
  23971. }
  23972. }
  23973. if (other.positions) {
  23974. if (!this.positions) {
  23975. this.positions = [];
  23976. }
  23977. for (index = 0; index < other.positions.length; index++) {
  23978. this.positions.push(other.positions[index]);
  23979. }
  23980. }
  23981. if (other.normals) {
  23982. if (!this.normals) {
  23983. this.normals = [];
  23984. }
  23985. for (index = 0; index < other.normals.length; index++) {
  23986. this.normals.push(other.normals[index]);
  23987. }
  23988. }
  23989. if (other.uvs) {
  23990. if (!this.uvs) {
  23991. this.uvs = [];
  23992. }
  23993. for (index = 0; index < other.uvs.length; index++) {
  23994. this.uvs.push(other.uvs[index]);
  23995. }
  23996. }
  23997. if (other.uv2s) {
  23998. if (!this.uv2s) {
  23999. this.uv2s = [];
  24000. }
  24001. for (index = 0; index < other.uv2s.length; index++) {
  24002. this.uv2s.push(other.uv2s[index]);
  24003. }
  24004. }
  24005. if (other.matricesIndices) {
  24006. if (!this.matricesIndices) {
  24007. this.matricesIndices = [];
  24008. }
  24009. for (index = 0; index < other.matricesIndices.length; index++) {
  24010. this.matricesIndices.push(other.matricesIndices[index]);
  24011. }
  24012. }
  24013. if (other.matricesWeights) {
  24014. if (!this.matricesWeights) {
  24015. this.matricesWeights = [];
  24016. }
  24017. for (index = 0; index < other.matricesWeights.length; index++) {
  24018. this.matricesWeights.push(other.matricesWeights[index]);
  24019. }
  24020. }
  24021. if (other.colors) {
  24022. if (!this.colors) {
  24023. this.colors = [];
  24024. }
  24025. for (index = 0; index < other.colors.length; index++) {
  24026. this.colors.push(other.colors[index]);
  24027. }
  24028. }
  24029. };
  24030. // Statics
  24031. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24032. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24033. };
  24034. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24035. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24036. };
  24037. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24038. var result = new VertexData();
  24039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24040. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24041. }
  24042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24043. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24044. }
  24045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24046. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24047. }
  24048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24049. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24050. }
  24051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24052. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24053. }
  24054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24055. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24056. }
  24057. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24058. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24059. }
  24060. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24061. return result;
  24062. };
  24063. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24064. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24065. closeArray = closeArray || false;
  24066. closePath = closePath || false;
  24067. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24068. offset = offset || defaultOffset;
  24069. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24070. var positions = [];
  24071. var indices = [];
  24072. var normals = [];
  24073. var uvs = [];
  24074. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24075. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24076. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24077. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24078. var minlg; // minimal length among all paths from pathArray
  24079. var lg = []; // array of path lengths : nb of vertex per path
  24080. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24081. var p; // path iterator
  24082. var i; // point iterator
  24083. var j; // point iterator
  24084. // if single path in pathArray
  24085. if (pathArray.length < 2) {
  24086. var ar1 = [];
  24087. var ar2 = [];
  24088. for (i = 0; i < pathArray[0].length - offset; i++) {
  24089. ar1.push(pathArray[0][i]);
  24090. ar2.push(pathArray[0][i + offset]);
  24091. }
  24092. pathArray = [ar1, ar2];
  24093. }
  24094. // positions and horizontal distances (u)
  24095. var idc = 0;
  24096. minlg = pathArray[0].length;
  24097. for (p = 0; p < pathArray.length; p++) {
  24098. uTotalDistance[p] = 0;
  24099. us[p] = [0];
  24100. var path = pathArray[p];
  24101. var l = path.length;
  24102. minlg = (minlg < l) ? minlg : l;
  24103. lg[p] = l;
  24104. idx[p] = idc;
  24105. j = 0;
  24106. while (j < l) {
  24107. positions.push(path[j].x, path[j].y, path[j].z);
  24108. if (j > 0) {
  24109. var vectlg = path[j].subtract(path[j - 1]).length();
  24110. var dist = vectlg + uTotalDistance[p];
  24111. us[p].push(dist);
  24112. uTotalDistance[p] = dist;
  24113. }
  24114. j++;
  24115. }
  24116. if (closePath) {
  24117. vectlg = path[0].subtract(path[j - 1]).length();
  24118. dist = vectlg + uTotalDistance[p];
  24119. uTotalDistance[p] = dist;
  24120. }
  24121. idc += l;
  24122. }
  24123. for (i = 0; i < minlg; i++) {
  24124. vTotalDistance[i] = 0;
  24125. vs[i] = [0];
  24126. var path1;
  24127. var path2;
  24128. for (p = 0; p < pathArray.length - 1; p++) {
  24129. path1 = pathArray[p];
  24130. path2 = pathArray[p + 1];
  24131. vectlg = path2[i].subtract(path1[i]).length();
  24132. dist = vectlg + vTotalDistance[i];
  24133. vs[i].push(dist);
  24134. vTotalDistance[i] = dist;
  24135. }
  24136. if (closeArray) {
  24137. path1 = pathArray[p];
  24138. path2 = pathArray[0];
  24139. vectlg = path2[i].subtract(path1[i]).length();
  24140. dist = vectlg + vTotalDistance[i];
  24141. vTotalDistance[i] = dist;
  24142. }
  24143. }
  24144. // uvs
  24145. var u;
  24146. var v;
  24147. for (p = 0; p < pathArray.length; p++) {
  24148. for (i = 0; i < minlg; i++) {
  24149. u = us[p][i] / uTotalDistance[p];
  24150. v = vs[i][p] / vTotalDistance[i];
  24151. uvs.push(u, v);
  24152. }
  24153. }
  24154. // indices
  24155. p = 0; // path index
  24156. var pi = 0; // positions array index
  24157. var l1 = lg[p] - 1; // path1 length
  24158. var l2 = lg[p + 1] - 1; // path2 length
  24159. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24160. var shft = idx[1] - idx[0]; // shift
  24161. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24162. var t1; // two consecutive triangles, so 4 points : point1
  24163. var t2; // point2
  24164. var t3; // point3
  24165. var t4; // point4
  24166. while (pi <= min && p < path1nb) {
  24167. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  24168. t1 = pi;
  24169. t2 = pi + shft;
  24170. t3 = pi + 1;
  24171. t4 = pi + shft + 1;
  24172. indices.push(pi, pi + shft, pi + 1);
  24173. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24174. pi += 1;
  24175. if (pi === min) {
  24176. if (closePath) {
  24177. indices.push(pi, pi + shft, idx[p]);
  24178. indices.push(idx[p] + shft, idx[p], pi + shft);
  24179. t3 = idx[p];
  24180. t4 = idx[p] + shft;
  24181. }
  24182. p++;
  24183. if (p === lg.length - 1) {
  24184. shft = idx[0] - idx[p];
  24185. l1 = lg[p] - 1;
  24186. l2 = lg[0] - 1;
  24187. }
  24188. else {
  24189. shft = idx[p + 1] - idx[p];
  24190. l1 = lg[p] - 1;
  24191. l2 = lg[p + 1] - 1;
  24192. }
  24193. pi = idx[p];
  24194. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24195. }
  24196. }
  24197. // normals
  24198. VertexData.ComputeNormals(positions, indices, normals);
  24199. // sides
  24200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24201. // Result
  24202. var vertexData = new VertexData();
  24203. vertexData.indices = indices;
  24204. vertexData.positions = positions;
  24205. vertexData.normals = normals;
  24206. vertexData.uvs = uvs;
  24207. return vertexData;
  24208. };
  24209. VertexData.CreateBox = function (size, sideOrientation) {
  24210. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24211. var normalsSource = [
  24212. new BABYLON.Vector3(0, 0, 1),
  24213. new BABYLON.Vector3(0, 0, -1),
  24214. new BABYLON.Vector3(1, 0, 0),
  24215. new BABYLON.Vector3(-1, 0, 0),
  24216. new BABYLON.Vector3(0, 1, 0),
  24217. new BABYLON.Vector3(0, -1, 0)
  24218. ];
  24219. var indices = [];
  24220. var positions = [];
  24221. var normals = [];
  24222. var uvs = [];
  24223. size = size || 1;
  24224. for (var index = 0; index < normalsSource.length; index++) {
  24225. var normal = normalsSource[index];
  24226. // Get two vectors perpendicular to the face normal and to each other.
  24227. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24228. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24229. // Six indices (two triangles) per face.
  24230. var verticesLength = positions.length / 3;
  24231. indices.push(verticesLength);
  24232. indices.push(verticesLength + 1);
  24233. indices.push(verticesLength + 2);
  24234. indices.push(verticesLength);
  24235. indices.push(verticesLength + 2);
  24236. indices.push(verticesLength + 3);
  24237. // Four vertices per face.
  24238. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24239. positions.push(vertex.x, vertex.y, vertex.z);
  24240. normals.push(normal.x, normal.y, normal.z);
  24241. uvs.push(1.0, 1.0);
  24242. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24243. positions.push(vertex.x, vertex.y, vertex.z);
  24244. normals.push(normal.x, normal.y, normal.z);
  24245. uvs.push(0.0, 1.0);
  24246. vertex = normal.add(side1).add(side2).scale(size / 2);
  24247. positions.push(vertex.x, vertex.y, vertex.z);
  24248. normals.push(normal.x, normal.y, normal.z);
  24249. uvs.push(0.0, 0.0);
  24250. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24251. positions.push(vertex.x, vertex.y, vertex.z);
  24252. normals.push(normal.x, normal.y, normal.z);
  24253. uvs.push(1.0, 0.0);
  24254. }
  24255. // sides
  24256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24257. // Result
  24258. var vertexData = new VertexData();
  24259. vertexData.indices = indices;
  24260. vertexData.positions = positions;
  24261. vertexData.normals = normals;
  24262. vertexData.uvs = uvs;
  24263. return vertexData;
  24264. };
  24265. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24266. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24267. segments = segments || 32;
  24268. diameter = diameter || 1;
  24269. var radius = diameter / 2;
  24270. var totalZRotationSteps = 2 + segments;
  24271. var totalYRotationSteps = 2 * totalZRotationSteps;
  24272. var indices = [];
  24273. var positions = [];
  24274. var normals = [];
  24275. var uvs = [];
  24276. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24277. var normalizedZ = zRotationStep / totalZRotationSteps;
  24278. var angleZ = (normalizedZ * Math.PI);
  24279. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24280. var normalizedY = yRotationStep / totalYRotationSteps;
  24281. var angleY = normalizedY * Math.PI * 2;
  24282. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24283. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24284. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24285. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24286. var vertex = complete.scale(radius);
  24287. var normal = BABYLON.Vector3.Normalize(vertex);
  24288. positions.push(vertex.x, vertex.y, vertex.z);
  24289. normals.push(normal.x, normal.y, normal.z);
  24290. uvs.push(normalizedZ, normalizedY);
  24291. }
  24292. if (zRotationStep > 0) {
  24293. var verticesCount = positions.length / 3;
  24294. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24295. indices.push((firstIndex));
  24296. indices.push((firstIndex + 1));
  24297. indices.push(firstIndex + totalYRotationSteps + 1);
  24298. indices.push((firstIndex + totalYRotationSteps + 1));
  24299. indices.push((firstIndex + 1));
  24300. indices.push((firstIndex + totalYRotationSteps + 2));
  24301. }
  24302. }
  24303. }
  24304. // Sides
  24305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24306. // Result
  24307. var vertexData = new VertexData();
  24308. vertexData.indices = indices;
  24309. vertexData.positions = positions;
  24310. vertexData.normals = normals;
  24311. vertexData.uvs = uvs;
  24312. return vertexData;
  24313. };
  24314. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24315. if (subdivisions === void 0) { subdivisions = 1; }
  24316. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24317. var radiusTop = diameterTop / 2;
  24318. var radiusBottom = diameterBottom / 2;
  24319. var indices = [];
  24320. var positions = [];
  24321. var normals = [];
  24322. var uvs = [];
  24323. height = height || 1;
  24324. diameterTop = diameterTop || 0.5;
  24325. diameterBottom = diameterBottom || 1;
  24326. tessellation = tessellation || 16;
  24327. subdivisions = subdivisions || 1;
  24328. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24329. var getCircleVector = function (i) {
  24330. var angle = (i * 2.0 * Math.PI / tessellation);
  24331. var dx = Math.cos(angle);
  24332. var dz = Math.sin(angle);
  24333. return new BABYLON.Vector3(dx, 0, dz);
  24334. };
  24335. var createCylinderCap = function (isTop) {
  24336. var radius = isTop ? radiusTop : radiusBottom;
  24337. if (radius === 0) {
  24338. return;
  24339. }
  24340. var vbase = positions.length / 3;
  24341. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24342. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24343. if (!isTop) {
  24344. offset.scaleInPlace(-1);
  24345. textureScale.x = -textureScale.x;
  24346. }
  24347. for (var i = 0; i < tessellation; i++) {
  24348. var circleVector = getCircleVector(i);
  24349. var position = circleVector.scale(radius).add(offset);
  24350. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24351. positions.push(position.x, position.y, position.z);
  24352. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24353. }
  24354. for (i = 0; i < tessellation - 2; i++) {
  24355. if (!isTop) {
  24356. indices.push(vbase);
  24357. indices.push(vbase + (i + 2) % tessellation);
  24358. indices.push(vbase + (i + 1) % tessellation);
  24359. }
  24360. else {
  24361. indices.push(vbase);
  24362. indices.push(vbase + (i + 1) % tessellation);
  24363. indices.push(vbase + (i + 2) % tessellation);
  24364. }
  24365. }
  24366. };
  24367. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  24368. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  24369. var stride = tessellation + 1;
  24370. for (var i = 0; i <= tessellation; i++) {
  24371. var circleVector = getCircleVector(i);
  24372. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24373. var position, radius = radiusBottom;
  24374. for (var s = 0; s <= subdivisions; s++) {
  24375. // Update variables
  24376. position = circleVector.scale(radius);
  24377. position.addInPlace(base.add(offset.scale(s)));
  24378. textureCoordinate.y += 1 / subdivisions;
  24379. radius += (radiusTop - radiusBottom) / subdivisions;
  24380. // Push in arrays
  24381. positions.push(position.x, position.y, position.z);
  24382. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24383. }
  24384. }
  24385. subdivisions += 1;
  24386. for (s = 0; s < subdivisions - 1; s++) {
  24387. for (i = 0; i <= tessellation; i++) {
  24388. indices.push(i * subdivisions + s);
  24389. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24390. indices.push(i * subdivisions + (s + 1));
  24391. indices.push(i * subdivisions + (s + 1));
  24392. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24393. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24394. }
  24395. }
  24396. // Create flat triangle fan caps to seal the top and bottom.
  24397. createCylinderCap(true);
  24398. createCylinderCap(false);
  24399. // Normals
  24400. VertexData.ComputeNormals(positions, indices, normals);
  24401. // Sides
  24402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24403. // Result
  24404. var vertexData = new VertexData();
  24405. vertexData.indices = indices;
  24406. vertexData.positions = positions;
  24407. vertexData.normals = normals;
  24408. vertexData.uvs = uvs;
  24409. return vertexData;
  24410. };
  24411. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24412. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24413. var indices = [];
  24414. var positions = [];
  24415. var normals = [];
  24416. var uvs = [];
  24417. diameter = diameter || 1;
  24418. thickness = thickness || 0.5;
  24419. tessellation = tessellation || 16;
  24420. var stride = tessellation + 1;
  24421. for (var i = 0; i <= tessellation; i++) {
  24422. var u = i / tessellation;
  24423. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24424. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24425. for (var j = 0; j <= tessellation; j++) {
  24426. var v = 1 - j / tessellation;
  24427. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24428. var dx = Math.cos(innerAngle);
  24429. var dy = Math.sin(innerAngle);
  24430. // Create a vertex.
  24431. var normal = new BABYLON.Vector3(dx, dy, 0);
  24432. var position = normal.scale(thickness / 2);
  24433. var textureCoordinate = new BABYLON.Vector2(u, v);
  24434. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24435. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24436. positions.push(position.x, position.y, position.z);
  24437. normals.push(normal.x, normal.y, normal.z);
  24438. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24439. // And create indices for two triangles.
  24440. var nextI = (i + 1) % stride;
  24441. var nextJ = (j + 1) % stride;
  24442. indices.push(i * stride + j);
  24443. indices.push(i * stride + nextJ);
  24444. indices.push(nextI * stride + j);
  24445. indices.push(i * stride + nextJ);
  24446. indices.push(nextI * stride + nextJ);
  24447. indices.push(nextI * stride + j);
  24448. }
  24449. }
  24450. // Sides
  24451. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24452. // Result
  24453. var vertexData = new VertexData();
  24454. vertexData.indices = indices;
  24455. vertexData.positions = positions;
  24456. vertexData.normals = normals;
  24457. vertexData.uvs = uvs;
  24458. return vertexData;
  24459. };
  24460. VertexData.CreateLines = function (points) {
  24461. var indices = [];
  24462. var positions = [];
  24463. for (var index = 0; index < points.length; index++) {
  24464. positions.push(points[index].x, points[index].y, points[index].z);
  24465. if (index > 0) {
  24466. indices.push(index - 1);
  24467. indices.push(index);
  24468. }
  24469. }
  24470. // Result
  24471. var vertexData = new VertexData();
  24472. vertexData.indices = indices;
  24473. vertexData.positions = positions;
  24474. return vertexData;
  24475. };
  24476. VertexData.CreateGround = function (width, height, subdivisions) {
  24477. var indices = [];
  24478. var positions = [];
  24479. var normals = [];
  24480. var uvs = [];
  24481. var row, col;
  24482. width = width || 1;
  24483. height = height || 1;
  24484. subdivisions = subdivisions || 1;
  24485. for (row = 0; row <= subdivisions; row++) {
  24486. for (col = 0; col <= subdivisions; col++) {
  24487. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24488. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24489. positions.push(position.x, position.y, position.z);
  24490. normals.push(normal.x, normal.y, normal.z);
  24491. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24492. }
  24493. }
  24494. for (row = 0; row < subdivisions; row++) {
  24495. for (col = 0; col < subdivisions; col++) {
  24496. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24497. indices.push(col + 1 + row * (subdivisions + 1));
  24498. indices.push(col + row * (subdivisions + 1));
  24499. indices.push(col + (row + 1) * (subdivisions + 1));
  24500. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24501. indices.push(col + row * (subdivisions + 1));
  24502. }
  24503. }
  24504. // Result
  24505. var vertexData = new VertexData();
  24506. vertexData.indices = indices;
  24507. vertexData.positions = positions;
  24508. vertexData.normals = normals;
  24509. vertexData.uvs = uvs;
  24510. return vertexData;
  24511. };
  24512. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24513. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24514. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24515. var indices = [];
  24516. var positions = [];
  24517. var normals = [];
  24518. var uvs = [];
  24519. var row, col, tileRow, tileCol;
  24520. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24521. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24522. precision.w = (precision.w < 1) ? 1 : precision.w;
  24523. precision.h = (precision.h < 1) ? 1 : precision.h;
  24524. var tileSize = {
  24525. 'w': (xmax - xmin) / subdivisions.w,
  24526. 'h': (zmax - zmin) / subdivisions.h
  24527. };
  24528. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24529. // Indices
  24530. var base = positions.length / 3;
  24531. var rowLength = precision.w + 1;
  24532. for (row = 0; row < precision.h; row++) {
  24533. for (col = 0; col < precision.w; col++) {
  24534. var square = [
  24535. base + col + row * rowLength,
  24536. base + (col + 1) + row * rowLength,
  24537. base + (col + 1) + (row + 1) * rowLength,
  24538. base + col + (row + 1) * rowLength
  24539. ];
  24540. indices.push(square[1]);
  24541. indices.push(square[2]);
  24542. indices.push(square[3]);
  24543. indices.push(square[0]);
  24544. indices.push(square[1]);
  24545. indices.push(square[3]);
  24546. }
  24547. }
  24548. // Position, normals and uvs
  24549. var position = BABYLON.Vector3.Zero();
  24550. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24551. for (row = 0; row <= precision.h; row++) {
  24552. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24553. for (col = 0; col <= precision.w; col++) {
  24554. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24555. position.y = 0;
  24556. positions.push(position.x, position.y, position.z);
  24557. normals.push(normal.x, normal.y, normal.z);
  24558. uvs.push(col / precision.w, row / precision.h);
  24559. }
  24560. }
  24561. }
  24562. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24563. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24564. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24565. }
  24566. }
  24567. // Result
  24568. var vertexData = new VertexData();
  24569. vertexData.indices = indices;
  24570. vertexData.positions = positions;
  24571. vertexData.normals = normals;
  24572. vertexData.uvs = uvs;
  24573. return vertexData;
  24574. };
  24575. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24576. var indices = [];
  24577. var positions = [];
  24578. var normals = [];
  24579. var uvs = [];
  24580. var row, col;
  24581. for (row = 0; row <= subdivisions; row++) {
  24582. for (col = 0; col <= subdivisions; col++) {
  24583. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24584. // Compute height
  24585. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24586. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24587. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24588. var r = buffer[pos] / 255.0;
  24589. var g = buffer[pos + 1] / 255.0;
  24590. var b = buffer[pos + 2] / 255.0;
  24591. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24592. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24593. // Add vertex
  24594. positions.push(position.x, position.y, position.z);
  24595. normals.push(0, 0, 0);
  24596. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24597. }
  24598. }
  24599. for (row = 0; row < subdivisions; row++) {
  24600. for (col = 0; col < subdivisions; col++) {
  24601. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24602. indices.push(col + 1 + row * (subdivisions + 1));
  24603. indices.push(col + row * (subdivisions + 1));
  24604. indices.push(col + (row + 1) * (subdivisions + 1));
  24605. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24606. indices.push(col + row * (subdivisions + 1));
  24607. }
  24608. }
  24609. // Normals
  24610. VertexData.ComputeNormals(positions, indices, normals);
  24611. // Result
  24612. var vertexData = new VertexData();
  24613. vertexData.indices = indices;
  24614. vertexData.positions = positions;
  24615. vertexData.normals = normals;
  24616. vertexData.uvs = uvs;
  24617. return vertexData;
  24618. };
  24619. VertexData.CreatePlane = function (size, sideOrientation) {
  24620. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24621. var indices = [];
  24622. var positions = [];
  24623. var normals = [];
  24624. var uvs = [];
  24625. size = size || 1;
  24626. // Vertices
  24627. var halfSize = size / 2.0;
  24628. positions.push(-halfSize, -halfSize, 0);
  24629. normals.push(0, 0, -1.0);
  24630. uvs.push(0.0, 0.0);
  24631. positions.push(halfSize, -halfSize, 0);
  24632. normals.push(0, 0, -1.0);
  24633. uvs.push(1.0, 0.0);
  24634. positions.push(halfSize, halfSize, 0);
  24635. normals.push(0, 0, -1.0);
  24636. uvs.push(1.0, 1.0);
  24637. positions.push(-halfSize, halfSize, 0);
  24638. normals.push(0, 0, -1.0);
  24639. uvs.push(0.0, 1.0);
  24640. // Indices
  24641. indices.push(0);
  24642. indices.push(1);
  24643. indices.push(2);
  24644. indices.push(0);
  24645. indices.push(2);
  24646. indices.push(3);
  24647. // Sides
  24648. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24649. // Result
  24650. var vertexData = new VertexData();
  24651. vertexData.indices = indices;
  24652. vertexData.positions = positions;
  24653. vertexData.normals = normals;
  24654. vertexData.uvs = uvs;
  24655. return vertexData;
  24656. };
  24657. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24658. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24659. var positions = [];
  24660. var indices = [];
  24661. var normals = [];
  24662. var uvs = [];
  24663. // positions and uvs
  24664. positions.push(0, 0, 0); // disc center first
  24665. uvs.push(0.5, 0.5);
  24666. var step = Math.PI * 2 / tessellation;
  24667. for (var a = 0; a < Math.PI * 2; a += step) {
  24668. var x = Math.cos(a);
  24669. var y = Math.sin(a);
  24670. var u = (x + 1) / 2;
  24671. var v = (1 - y) / 2;
  24672. positions.push(radius * x, radius * y, 0);
  24673. uvs.push(u, v);
  24674. }
  24675. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24676. uvs.push(uvs[2], uvs[3]);
  24677. //indices
  24678. var vertexNb = positions.length / 3;
  24679. for (var i = 1; i < vertexNb - 1; i++) {
  24680. indices.push(i + 1, 0, i);
  24681. }
  24682. // result
  24683. VertexData.ComputeNormals(positions, indices, normals);
  24684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24685. var vertexData = new VertexData();
  24686. vertexData.indices = indices;
  24687. vertexData.positions = positions;
  24688. vertexData.normals = normals;
  24689. vertexData.uvs = uvs;
  24690. return vertexData;
  24691. };
  24692. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24693. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24694. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24695. var indices = [];
  24696. var positions = [];
  24697. var normals = [];
  24698. var uvs = [];
  24699. radius = radius || 2;
  24700. tube = tube || 0.5;
  24701. radialSegments = radialSegments || 32;
  24702. tubularSegments = tubularSegments || 32;
  24703. p = p || 2;
  24704. q = q || 3;
  24705. // Helper
  24706. var getPos = function (angle) {
  24707. var cu = Math.cos(angle);
  24708. var su = Math.sin(angle);
  24709. var quOverP = q / p * angle;
  24710. var cs = Math.cos(quOverP);
  24711. var tx = radius * (2 + cs) * 0.5 * cu;
  24712. var ty = radius * (2 + cs) * su * 0.5;
  24713. var tz = radius * Math.sin(quOverP) * 0.5;
  24714. return new BABYLON.Vector3(tx, ty, tz);
  24715. };
  24716. for (var i = 0; i <= radialSegments; i++) {
  24717. var modI = i % radialSegments;
  24718. var u = modI / radialSegments * 2 * p * Math.PI;
  24719. var p1 = getPos(u);
  24720. var p2 = getPos(u + 0.01);
  24721. var tang = p2.subtract(p1);
  24722. var n = p2.add(p1);
  24723. var bitan = BABYLON.Vector3.Cross(tang, n);
  24724. n = BABYLON.Vector3.Cross(bitan, tang);
  24725. bitan.normalize();
  24726. n.normalize();
  24727. for (var j = 0; j < tubularSegments; j++) {
  24728. var modJ = j % tubularSegments;
  24729. var v = modJ / tubularSegments * 2 * Math.PI;
  24730. var cx = -tube * Math.cos(v);
  24731. var cy = tube * Math.sin(v);
  24732. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24733. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24734. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24735. uvs.push(i / radialSegments);
  24736. uvs.push(j / tubularSegments);
  24737. }
  24738. }
  24739. for (i = 0; i < radialSegments; i++) {
  24740. for (j = 0; j < tubularSegments; j++) {
  24741. var jNext = (j + 1) % tubularSegments;
  24742. var a = i * tubularSegments + j;
  24743. var b = (i + 1) * tubularSegments + j;
  24744. var c = (i + 1) * tubularSegments + jNext;
  24745. var d = i * tubularSegments + jNext;
  24746. indices.push(d);
  24747. indices.push(b);
  24748. indices.push(a);
  24749. indices.push(d);
  24750. indices.push(c);
  24751. indices.push(b);
  24752. }
  24753. }
  24754. // Normals
  24755. VertexData.ComputeNormals(positions, indices, normals);
  24756. // Sides
  24757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24758. // Result
  24759. var vertexData = new VertexData();
  24760. vertexData.indices = indices;
  24761. vertexData.positions = positions;
  24762. vertexData.normals = normals;
  24763. vertexData.uvs = uvs;
  24764. return vertexData;
  24765. };
  24766. // Tools
  24767. /**
  24768. * @param {any} - positions (number[] or Float32Array)
  24769. * @param {any} - indices (number[] or Uint16Array)
  24770. * @param {any} - normals (number[] or Float32Array)
  24771. */
  24772. VertexData.ComputeNormals = function (positions, indices, normals) {
  24773. var index = 0;
  24774. // temp Vector3
  24775. var p1 = BABYLON.Vector3.Zero();
  24776. var p2 = BABYLON.Vector3.Zero();
  24777. var p3 = BABYLON.Vector3.Zero();
  24778. var p1p2 = BABYLON.Vector3.Zero();
  24779. var p3p2 = BABYLON.Vector3.Zero();
  24780. var faceNormal = BABYLON.Vector3.Zero();
  24781. var vertexNormali1 = BABYLON.Vector3.Zero();
  24782. var vertexNormali2 = BABYLON.Vector3.Zero();
  24783. var vertexNormali3 = BABYLON.Vector3.Zero();
  24784. // indice triplet = 1 face
  24785. var nbFaces = indices.length / 3;
  24786. for (index = 0; index < nbFaces; index++) {
  24787. var i1 = indices[index * 3];
  24788. var i2 = indices[index * 3 + 1];
  24789. var i3 = indices[index * 3 + 2];
  24790. // setting the temp V3
  24791. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24792. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24793. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24794. p1.subtractToRef(p2, p1p2);
  24795. p3.subtractToRef(p2, p3p2);
  24796. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24797. faceNormal.normalize();
  24798. // All intermediate results are stored in the normals array :
  24799. // get the normals at i1, i2 and i3 indexes
  24800. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24801. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24802. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24803. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24804. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24805. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24806. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24807. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24808. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24809. // make intermediate vectors3 from normals values
  24810. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24811. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24812. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24813. // add the current face normals to these intermediate vectors3
  24814. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24815. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24816. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24817. // store back intermediate vectors3 into the normals array
  24818. normals[i1 * 3] = vertexNormali1.x;
  24819. normals[i1 * 3 + 1] = vertexNormali1.y;
  24820. normals[i1 * 3 + 2] = vertexNormali1.z;
  24821. normals[i2 * 3] = vertexNormali2.x;
  24822. normals[i2 * 3 + 1] = vertexNormali2.y;
  24823. normals[i2 * 3 + 2] = vertexNormali2.z;
  24824. normals[i3 * 3] = vertexNormali3.x;
  24825. normals[i3 * 3 + 1] = vertexNormali3.y;
  24826. normals[i3 * 3 + 2] = vertexNormali3.z;
  24827. }
  24828. for (index = 0; index < normals.length / 3; index++) {
  24829. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24830. vertexNormali1.normalize();
  24831. normals[index * 3] = vertexNormali1.x;
  24832. normals[index * 3 + 1] = vertexNormali1.y;
  24833. normals[index * 3 + 2] = vertexNormali1.z;
  24834. }
  24835. };
  24836. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24837. var li = indices.length;
  24838. var ln = normals.length;
  24839. var i;
  24840. var n;
  24841. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24842. switch (sideOrientation) {
  24843. case BABYLON.Mesh.FRONTSIDE:
  24844. break;
  24845. case BABYLON.Mesh.BACKSIDE:
  24846. var tmp;
  24847. for (i = 0; i < li; i += 3) {
  24848. tmp = indices[i];
  24849. indices[i] = indices[i + 2];
  24850. indices[i + 2] = tmp;
  24851. }
  24852. for (n = 0; n < ln; n++) {
  24853. normals[n] = -normals[n];
  24854. }
  24855. break;
  24856. case BABYLON.Mesh.DOUBLESIDE:
  24857. // positions
  24858. var lp = positions.length;
  24859. var l = lp / 3;
  24860. for (var p = 0; p < lp; p++) {
  24861. positions[lp + p] = positions[p];
  24862. }
  24863. for (i = 0; i < li; i += 3) {
  24864. indices[i + li] = indices[i + 2] + l;
  24865. indices[i + 1 + li] = indices[i + 1] + l;
  24866. indices[i + 2 + li] = indices[i] + l;
  24867. }
  24868. for (n = 0; n < ln; n++) {
  24869. normals[ln + n] = -normals[n];
  24870. }
  24871. // uvs
  24872. var lu = uvs.length;
  24873. for (var u = 0; u < lu; u++) {
  24874. uvs[u + lu] = uvs[u];
  24875. }
  24876. break;
  24877. }
  24878. };
  24879. return VertexData;
  24880. })();
  24881. BABYLON.VertexData = VertexData;
  24882. })(BABYLON || (BABYLON = {}));
  24883. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  24884. var __extends = this.__extends || function (d, b) {
  24885. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24886. function __() { this.constructor = d; }
  24887. __.prototype = b.prototype;
  24888. d.prototype = new __();
  24889. };
  24890. var BABYLON;
  24891. (function (BABYLON) {
  24892. var buildCamera = function (that, name) {
  24893. that._leftCamera.isIntermediate = true;
  24894. that.subCameras.push(that._leftCamera);
  24895. that.subCameras.push(that._rightCamera);
  24896. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  24897. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  24898. that._anaglyphPostProcess.onApply = function (effect) {
  24899. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  24900. };
  24901. that._update();
  24902. };
  24903. var AnaglyphArcRotateCamera = (function (_super) {
  24904. __extends(AnaglyphArcRotateCamera, _super);
  24905. // ANY
  24906. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  24907. _super.call(this, name, alpha, beta, radius, target, scene);
  24908. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24909. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  24910. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  24911. buildCamera(this, name);
  24912. }
  24913. AnaglyphArcRotateCamera.prototype._update = function () {
  24914. this._updateCamera(this._leftCamera);
  24915. this._updateCamera(this._rightCamera);
  24916. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  24917. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  24918. _super.prototype._update.call(this);
  24919. };
  24920. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  24921. camera.beta = this.beta;
  24922. camera.radius = this.radius;
  24923. camera.minZ = this.minZ;
  24924. camera.maxZ = this.maxZ;
  24925. camera.fov = this.fov;
  24926. camera.target = this.target;
  24927. };
  24928. return AnaglyphArcRotateCamera;
  24929. })(BABYLON.ArcRotateCamera);
  24930. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  24931. var AnaglyphFreeCamera = (function (_super) {
  24932. __extends(AnaglyphFreeCamera, _super);
  24933. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  24934. _super.call(this, name, position, scene);
  24935. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24936. this._transformMatrix = new BABYLON.Matrix();
  24937. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  24938. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  24939. buildCamera(this, name);
  24940. }
  24941. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  24942. var target = this.getTarget();
  24943. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  24944. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  24945. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  24946. };
  24947. AnaglyphFreeCamera.prototype._update = function () {
  24948. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  24949. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  24950. this._updateCamera(this._leftCamera);
  24951. this._updateCamera(this._rightCamera);
  24952. _super.prototype._update.call(this);
  24953. };
  24954. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  24955. camera.minZ = this.minZ;
  24956. camera.maxZ = this.maxZ;
  24957. camera.fov = this.fov;
  24958. camera.viewport = this.viewport;
  24959. camera.setTarget(this.getTarget());
  24960. };
  24961. return AnaglyphFreeCamera;
  24962. })(BABYLON.FreeCamera);
  24963. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  24964. })(BABYLON || (BABYLON = {}));
  24965. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  24966. var __extends = this.__extends || function (d, b) {
  24967. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24968. function __() { this.constructor = d; }
  24969. __.prototype = b.prototype;
  24970. d.prototype = new __();
  24971. };
  24972. var BABYLON;
  24973. (function (BABYLON) {
  24974. var AnaglyphPostProcess = (function (_super) {
  24975. __extends(AnaglyphPostProcess, _super);
  24976. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24977. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  24978. }
  24979. return AnaglyphPostProcess;
  24980. })(BABYLON.PostProcess);
  24981. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  24982. })(BABYLON || (BABYLON = {}));
  24983. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  24984. var BABYLON;
  24985. (function (BABYLON) {
  24986. var Tags = (function () {
  24987. function Tags() {
  24988. }
  24989. Tags.EnableFor = function (obj) {
  24990. obj._tags = obj._tags || {};
  24991. obj.hasTags = function () {
  24992. return Tags.HasTags(obj);
  24993. };
  24994. obj.addTags = function (tagsString) {
  24995. return Tags.AddTagsTo(obj, tagsString);
  24996. };
  24997. obj.removeTags = function (tagsString) {
  24998. return Tags.RemoveTagsFrom(obj, tagsString);
  24999. };
  25000. obj.matchesTagsQuery = function (tagsQuery) {
  25001. return Tags.MatchesQuery(obj, tagsQuery);
  25002. };
  25003. };
  25004. Tags.DisableFor = function (obj) {
  25005. delete obj._tags;
  25006. delete obj.hasTags;
  25007. delete obj.addTags;
  25008. delete obj.removeTags;
  25009. delete obj.matchesTagsQuery;
  25010. };
  25011. Tags.HasTags = function (obj) {
  25012. if (!obj._tags) {
  25013. return false;
  25014. }
  25015. return !BABYLON.Tools.IsEmpty(obj._tags);
  25016. };
  25017. Tags.GetTags = function (obj) {
  25018. if (!obj._tags) {
  25019. return null;
  25020. }
  25021. return obj._tags;
  25022. };
  25023. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25024. // a tag cannot start with '||', '&&', and '!'
  25025. // it cannot contain whitespaces
  25026. Tags.AddTagsTo = function (obj, tagsString) {
  25027. if (!tagsString) {
  25028. return;
  25029. }
  25030. var tags = tagsString.split(" ");
  25031. for (var t in tags) {
  25032. Tags._AddTagTo(obj, tags[t]);
  25033. }
  25034. };
  25035. Tags._AddTagTo = function (obj, tag) {
  25036. tag = tag.trim();
  25037. if (tag === "" || tag === "true" || tag === "false") {
  25038. return;
  25039. }
  25040. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25041. return;
  25042. }
  25043. Tags.EnableFor(obj);
  25044. obj._tags[tag] = true;
  25045. };
  25046. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25047. if (!Tags.HasTags(obj)) {
  25048. return;
  25049. }
  25050. var tags = tagsString.split(" ");
  25051. for (var t in tags) {
  25052. Tags._RemoveTagFrom(obj, tags[t]);
  25053. }
  25054. };
  25055. Tags._RemoveTagFrom = function (obj, tag) {
  25056. delete obj._tags[tag];
  25057. };
  25058. Tags.MatchesQuery = function (obj, tagsQuery) {
  25059. if (tagsQuery === undefined) {
  25060. return true;
  25061. }
  25062. if (tagsQuery === "") {
  25063. return Tags.HasTags(obj);
  25064. }
  25065. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25066. };
  25067. return Tags;
  25068. })();
  25069. BABYLON.Tags = Tags;
  25070. })(BABYLON || (BABYLON = {}));
  25071. //# sourceMappingURL=babylon.tags.js.map
  25072. var BABYLON;
  25073. (function (BABYLON) {
  25074. var Internals;
  25075. (function (Internals) {
  25076. var AndOrNotEvaluator = (function () {
  25077. function AndOrNotEvaluator() {
  25078. }
  25079. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25080. if (!query.match(/\([^\(\)]*\)/g)) {
  25081. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25082. }
  25083. else {
  25084. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25085. // remove parenthesis
  25086. r = r.slice(1, r.length - 1);
  25087. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25088. });
  25089. }
  25090. if (query === "true") {
  25091. return true;
  25092. }
  25093. if (query === "false") {
  25094. return false;
  25095. }
  25096. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25097. };
  25098. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25099. evaluateCallback = evaluateCallback || (function (r) {
  25100. return r === "true" ? true : false;
  25101. });
  25102. var result;
  25103. var or = parenthesisContent.split("||");
  25104. for (var i in or) {
  25105. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25106. var and = ori.split("&&");
  25107. if (and.length > 1) {
  25108. for (var j = 0; j < and.length; ++j) {
  25109. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25110. if (andj !== "true" && andj !== "false") {
  25111. if (andj[0] === "!") {
  25112. result = !evaluateCallback(andj.substring(1));
  25113. }
  25114. else {
  25115. result = evaluateCallback(andj);
  25116. }
  25117. }
  25118. else {
  25119. result = andj === "true" ? true : false;
  25120. }
  25121. if (!result) {
  25122. ori = "false";
  25123. break;
  25124. }
  25125. }
  25126. }
  25127. if (result || ori === "true") {
  25128. result = true;
  25129. break;
  25130. }
  25131. // result equals false (or undefined)
  25132. if (ori !== "true" && ori !== "false") {
  25133. if (ori[0] === "!") {
  25134. result = !evaluateCallback(ori.substring(1));
  25135. }
  25136. else {
  25137. result = evaluateCallback(ori);
  25138. }
  25139. }
  25140. else {
  25141. result = ori === "true" ? true : false;
  25142. }
  25143. }
  25144. // the whole parenthesis scope is replaced by 'true' or 'false'
  25145. return result ? "true" : "false";
  25146. };
  25147. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25148. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25149. // remove whitespaces
  25150. r = r.replace(/[\s]/g, function () { return ""; });
  25151. return r.length % 2 ? "!" : "";
  25152. });
  25153. booleanString = booleanString.trim();
  25154. if (booleanString === "!true") {
  25155. booleanString = "false";
  25156. }
  25157. else if (booleanString === "!false") {
  25158. booleanString = "true";
  25159. }
  25160. return booleanString;
  25161. };
  25162. return AndOrNotEvaluator;
  25163. })();
  25164. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25165. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25166. })(BABYLON || (BABYLON = {}));
  25167. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25168. var BABYLON;
  25169. (function (BABYLON) {
  25170. var PostProcessRenderPass = (function () {
  25171. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25172. this._enabled = true;
  25173. this._refCount = 0;
  25174. this._name = name;
  25175. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25176. this.setRenderList(renderList);
  25177. this._renderTexture.onBeforeRender = beforeRender;
  25178. this._renderTexture.onAfterRender = afterRender;
  25179. this._scene = scene;
  25180. this._renderList = renderList;
  25181. }
  25182. // private
  25183. PostProcessRenderPass.prototype._incRefCount = function () {
  25184. if (this._refCount === 0) {
  25185. this._scene.customRenderTargets.push(this._renderTexture);
  25186. }
  25187. return ++this._refCount;
  25188. };
  25189. PostProcessRenderPass.prototype._decRefCount = function () {
  25190. this._refCount--;
  25191. if (this._refCount <= 0) {
  25192. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25193. }
  25194. return this._refCount;
  25195. };
  25196. PostProcessRenderPass.prototype._update = function () {
  25197. this.setRenderList(this._renderList);
  25198. };
  25199. // public
  25200. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25201. this._renderTexture.renderList = renderList;
  25202. };
  25203. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25204. return this._renderTexture;
  25205. };
  25206. return PostProcessRenderPass;
  25207. })();
  25208. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25209. })(BABYLON || (BABYLON = {}));
  25210. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25211. var BABYLON;
  25212. (function (BABYLON) {
  25213. var PostProcessRenderEffect = (function () {
  25214. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25215. this._engine = engine;
  25216. this._name = name;
  25217. this._singleInstance = singleInstance || true;
  25218. this._getPostProcess = getPostProcess;
  25219. this._cameras = [];
  25220. this._indicesForCamera = [];
  25221. this._postProcesses = {};
  25222. this._renderPasses = {};
  25223. this._renderEffectAsPasses = {};
  25224. }
  25225. PostProcessRenderEffect.prototype._update = function () {
  25226. for (var renderPassName in this._renderPasses) {
  25227. this._renderPasses[renderPassName]._update();
  25228. }
  25229. };
  25230. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25231. this._renderPasses[renderPass._name] = renderPass;
  25232. this._linkParameters();
  25233. };
  25234. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25235. delete this._renderPasses[renderPass._name];
  25236. this._linkParameters();
  25237. };
  25238. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25239. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25240. this._linkParameters();
  25241. };
  25242. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25243. for (var renderPassName in this._renderPasses) {
  25244. if (renderPassName === passName) {
  25245. return this._renderPasses[passName];
  25246. }
  25247. }
  25248. };
  25249. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25250. this._renderPasses = {};
  25251. this._linkParameters();
  25252. };
  25253. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25254. var cameraKey;
  25255. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25256. for (var i = 0; i < _cam.length; i++) {
  25257. var camera = _cam[i];
  25258. var cameraName = camera.name;
  25259. if (this._singleInstance) {
  25260. cameraKey = 0;
  25261. }
  25262. else {
  25263. cameraKey = cameraName;
  25264. }
  25265. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25266. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25267. if (!this._indicesForCamera[cameraName]) {
  25268. this._indicesForCamera[cameraName] = [];
  25269. }
  25270. this._indicesForCamera[cameraName].push(index);
  25271. if (this._cameras.indexOf(camera) === -1) {
  25272. this._cameras[cameraName] = camera;
  25273. }
  25274. for (var passName in this._renderPasses) {
  25275. this._renderPasses[passName]._incRefCount();
  25276. }
  25277. }
  25278. this._linkParameters();
  25279. };
  25280. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25281. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25282. for (var i = 0; i < _cam.length; i++) {
  25283. var camera = _cam[i];
  25284. var cameraName = camera.name;
  25285. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25286. var index = this._cameras.indexOf(cameraName);
  25287. this._indicesForCamera.splice(index, 1);
  25288. this._cameras.splice(index, 1);
  25289. for (var passName in this._renderPasses) {
  25290. this._renderPasses[passName]._decRefCount();
  25291. }
  25292. }
  25293. };
  25294. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25295. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25296. for (var i = 0; i < _cam.length; i++) {
  25297. var camera = _cam[i];
  25298. var cameraName = camera.name;
  25299. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25300. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25301. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25302. }
  25303. }
  25304. for (var passName in this._renderPasses) {
  25305. this._renderPasses[passName]._incRefCount();
  25306. }
  25307. }
  25308. };
  25309. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25310. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25311. for (var i = 0; i < _cam.length; i++) {
  25312. var camera = _cam[i];
  25313. var cameraName = camera.Name;
  25314. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25315. for (var passName in this._renderPasses) {
  25316. this._renderPasses[passName]._decRefCount();
  25317. }
  25318. }
  25319. };
  25320. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25321. if (this._singleInstance) {
  25322. return this._postProcesses[0];
  25323. }
  25324. else {
  25325. return this._postProcesses[camera.name];
  25326. }
  25327. };
  25328. PostProcessRenderEffect.prototype._linkParameters = function () {
  25329. var _this = this;
  25330. for (var index in this._postProcesses) {
  25331. if (this.applyParameters) {
  25332. this.applyParameters(this._postProcesses[index]);
  25333. }
  25334. this._postProcesses[index].onBeforeRender = function (effect) {
  25335. _this._linkTextures(effect);
  25336. };
  25337. }
  25338. };
  25339. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25340. for (var renderPassName in this._renderPasses) {
  25341. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25342. }
  25343. for (var renderEffectName in this._renderEffectAsPasses) {
  25344. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25345. }
  25346. };
  25347. return PostProcessRenderEffect;
  25348. })();
  25349. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25350. })(BABYLON || (BABYLON = {}));
  25351. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25352. var BABYLON;
  25353. (function (BABYLON) {
  25354. var PostProcessRenderPipeline = (function () {
  25355. function PostProcessRenderPipeline(engine, name) {
  25356. this._engine = engine;
  25357. this._name = name;
  25358. this._renderEffects = {};
  25359. this._renderEffectsForIsolatedPass = {};
  25360. this._cameras = [];
  25361. }
  25362. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25363. this._renderEffects[renderEffect._name] = renderEffect;
  25364. };
  25365. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25366. var renderEffects = this._renderEffects[renderEffectName];
  25367. if (!renderEffects) {
  25368. return;
  25369. }
  25370. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25371. };
  25372. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25373. var renderEffects = this._renderEffects[renderEffectName];
  25374. if (!renderEffects) {
  25375. return;
  25376. }
  25377. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25378. };
  25379. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25380. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25381. var indicesToDelete = [];
  25382. for (var i = 0; i < _cam.length; i++) {
  25383. var camera = _cam[i];
  25384. var cameraName = camera.name;
  25385. if (this._cameras.indexOf(camera) === -1) {
  25386. this._cameras[cameraName] = camera;
  25387. }
  25388. else if (unique) {
  25389. indicesToDelete.push(i);
  25390. }
  25391. }
  25392. for (var i = 0; i < indicesToDelete.length; i++) {
  25393. cameras.splice(indicesToDelete[i], 1);
  25394. }
  25395. for (var renderEffectName in this._renderEffects) {
  25396. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25397. }
  25398. };
  25399. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25400. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25401. for (var renderEffectName in this._renderEffects) {
  25402. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25403. }
  25404. for (var i = 0; i < _cam.length; i++) {
  25405. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25406. }
  25407. };
  25408. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25409. var _this = this;
  25410. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25411. var pass = null;
  25412. for (var renderEffectName in this._renderEffects) {
  25413. pass = this._renderEffects[renderEffectName].getPass(passName);
  25414. if (pass != null) {
  25415. break;
  25416. }
  25417. }
  25418. if (pass === null) {
  25419. return;
  25420. }
  25421. for (var renderEffectName in this._renderEffects) {
  25422. this._renderEffects[renderEffectName]._disable(_cam);
  25423. }
  25424. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25425. for (var i = 0; i < _cam.length; i++) {
  25426. var camera = _cam[i];
  25427. var cameraName = camera.name;
  25428. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25429. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25430. });
  25431. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25432. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25433. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25434. }
  25435. };
  25436. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25437. var _this = this;
  25438. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25439. for (var i = 0; i < _cam.length; i++) {
  25440. var camera = _cam[i];
  25441. var cameraName = camera.name;
  25442. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25443. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25444. });
  25445. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25446. }
  25447. for (var renderEffectName in this._renderEffects) {
  25448. this._renderEffects[renderEffectName]._enable(_cam);
  25449. }
  25450. };
  25451. PostProcessRenderPipeline.prototype._update = function () {
  25452. for (var renderEffectName in this._renderEffects) {
  25453. this._renderEffects[renderEffectName]._update();
  25454. }
  25455. for (var i = 0; i < this._cameras.length; i++) {
  25456. var cameraName = this._cameras[i].name;
  25457. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25458. this._renderEffectsForIsolatedPass[cameraName]._update();
  25459. }
  25460. }
  25461. };
  25462. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25463. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25464. return PostProcessRenderPipeline;
  25465. })();
  25466. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25467. })(BABYLON || (BABYLON = {}));
  25468. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25469. var BABYLON;
  25470. (function (BABYLON) {
  25471. var PostProcessRenderPipelineManager = (function () {
  25472. function PostProcessRenderPipelineManager() {
  25473. this._renderPipelines = {};
  25474. }
  25475. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25476. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25477. };
  25478. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25479. var renderPipeline = this._renderPipelines[renderPipelineName];
  25480. if (!renderPipeline) {
  25481. return;
  25482. }
  25483. renderPipeline._attachCameras(cameras, unique);
  25484. };
  25485. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25486. var renderPipeline = this._renderPipelines[renderPipelineName];
  25487. if (!renderPipeline) {
  25488. return;
  25489. }
  25490. renderPipeline._detachCameras(cameras);
  25491. };
  25492. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25493. var renderPipeline = this._renderPipelines[renderPipelineName];
  25494. if (!renderPipeline) {
  25495. return;
  25496. }
  25497. renderPipeline._enableEffect(renderEffectName, cameras);
  25498. };
  25499. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25500. var renderPipeline = this._renderPipelines[renderPipelineName];
  25501. if (!renderPipeline) {
  25502. return;
  25503. }
  25504. renderPipeline._disableEffect(renderEffectName, cameras);
  25505. };
  25506. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25507. var renderPipeline = this._renderPipelines[renderPipelineName];
  25508. if (!renderPipeline) {
  25509. return;
  25510. }
  25511. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25512. };
  25513. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25514. var renderPipeline = this._renderPipelines[renderPipelineName];
  25515. if (!renderPipeline) {
  25516. return;
  25517. }
  25518. renderPipeline._disableDisplayOnlyPass(cameras);
  25519. };
  25520. PostProcessRenderPipelineManager.prototype.update = function () {
  25521. for (var renderPipelineName in this._renderPipelines) {
  25522. this._renderPipelines[renderPipelineName]._update();
  25523. }
  25524. };
  25525. return PostProcessRenderPipelineManager;
  25526. })();
  25527. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25528. })(BABYLON || (BABYLON = {}));
  25529. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25530. var __extends = this.__extends || function (d, b) {
  25531. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25532. function __() { this.constructor = d; }
  25533. __.prototype = b.prototype;
  25534. d.prototype = new __();
  25535. };
  25536. var BABYLON;
  25537. (function (BABYLON) {
  25538. var DisplayPassPostProcess = (function (_super) {
  25539. __extends(DisplayPassPostProcess, _super);
  25540. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25541. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25542. }
  25543. return DisplayPassPostProcess;
  25544. })(BABYLON.PostProcess);
  25545. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25546. })(BABYLON || (BABYLON = {}));
  25547. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25548. var BABYLON;
  25549. (function (BABYLON) {
  25550. var BoundingBoxRenderer = (function () {
  25551. function BoundingBoxRenderer(scene) {
  25552. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25553. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25554. this.showBackLines = true;
  25555. this.renderList = new BABYLON.SmartArray(32);
  25556. this._scene = scene;
  25557. }
  25558. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25559. if (this._colorShader) {
  25560. return;
  25561. }
  25562. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25563. attributes: ["position"],
  25564. uniforms: ["worldViewProjection", "color"]
  25565. });
  25566. var engine = this._scene.getEngine();
  25567. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25568. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25569. 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]);
  25570. };
  25571. BoundingBoxRenderer.prototype.reset = function () {
  25572. this.renderList.reset();
  25573. };
  25574. BoundingBoxRenderer.prototype.render = function () {
  25575. if (this.renderList.length === 0) {
  25576. return;
  25577. }
  25578. this._prepareRessources();
  25579. if (!this._colorShader.isReady()) {
  25580. return;
  25581. }
  25582. var engine = this._scene.getEngine();
  25583. engine.setDepthWrite(false);
  25584. this._colorShader._preBind();
  25585. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25586. var boundingBox = this.renderList.data[boundingBoxIndex];
  25587. var min = boundingBox.minimum;
  25588. var max = boundingBox.maximum;
  25589. var diff = max.subtract(min);
  25590. var median = min.add(diff.scale(0.5));
  25591. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  25592. // VBOs
  25593. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25594. if (this.showBackLines) {
  25595. // Back
  25596. engine.setDepthFunctionToGreaterOrEqual();
  25597. this._scene.resetCachedMaterial();
  25598. this._colorShader.setColor4("color", this.backColor.toColor4());
  25599. this._colorShader.bind(worldMatrix);
  25600. // Draw order
  25601. engine.draw(false, 0, 24);
  25602. }
  25603. // Front
  25604. engine.setDepthFunctionToLess();
  25605. this._scene.resetCachedMaterial();
  25606. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25607. this._colorShader.bind(worldMatrix);
  25608. // Draw order
  25609. engine.draw(false, 0, 24);
  25610. }
  25611. this._colorShader.unbind();
  25612. engine.setDepthFunctionToLessOrEqual();
  25613. engine.setDepthWrite(true);
  25614. };
  25615. BoundingBoxRenderer.prototype.dispose = function () {
  25616. if (!this._colorShader) {
  25617. return;
  25618. }
  25619. this._colorShader.dispose();
  25620. this._vb.dispose();
  25621. this._scene.getEngine()._releaseBuffer(this._ib);
  25622. };
  25623. return BoundingBoxRenderer;
  25624. })();
  25625. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25626. })(BABYLON || (BABYLON = {}));
  25627. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25628. var __extends = this.__extends || function (d, b) {
  25629. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25630. function __() { this.constructor = d; }
  25631. __.prototype = b.prototype;
  25632. d.prototype = new __();
  25633. };
  25634. var BABYLON;
  25635. (function (BABYLON) {
  25636. var Condition = (function () {
  25637. function Condition(actionManager) {
  25638. this._actionManager = actionManager;
  25639. }
  25640. Condition.prototype.isValid = function () {
  25641. return true;
  25642. };
  25643. Condition.prototype._getProperty = function (propertyPath) {
  25644. return this._actionManager._getProperty(propertyPath);
  25645. };
  25646. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25647. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25648. };
  25649. return Condition;
  25650. })();
  25651. BABYLON.Condition = Condition;
  25652. var ValueCondition = (function (_super) {
  25653. __extends(ValueCondition, _super);
  25654. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25655. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25656. _super.call(this, actionManager);
  25657. this.propertyPath = propertyPath;
  25658. this.value = value;
  25659. this.operator = operator;
  25660. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25661. this._property = this._getProperty(this.propertyPath);
  25662. }
  25663. Object.defineProperty(ValueCondition, "IsEqual", {
  25664. get: function () {
  25665. return ValueCondition._IsEqual;
  25666. },
  25667. enumerable: true,
  25668. configurable: true
  25669. });
  25670. Object.defineProperty(ValueCondition, "IsDifferent", {
  25671. get: function () {
  25672. return ValueCondition._IsDifferent;
  25673. },
  25674. enumerable: true,
  25675. configurable: true
  25676. });
  25677. Object.defineProperty(ValueCondition, "IsGreater", {
  25678. get: function () {
  25679. return ValueCondition._IsGreater;
  25680. },
  25681. enumerable: true,
  25682. configurable: true
  25683. });
  25684. Object.defineProperty(ValueCondition, "IsLesser", {
  25685. get: function () {
  25686. return ValueCondition._IsLesser;
  25687. },
  25688. enumerable: true,
  25689. configurable: true
  25690. });
  25691. // Methods
  25692. ValueCondition.prototype.isValid = function () {
  25693. switch (this.operator) {
  25694. case ValueCondition.IsGreater:
  25695. return this._target[this._property] > this.value;
  25696. case ValueCondition.IsLesser:
  25697. return this._target[this._property] < this.value;
  25698. case ValueCondition.IsEqual:
  25699. case ValueCondition.IsDifferent:
  25700. var check;
  25701. if (this.value.equals) {
  25702. check = this.value.equals(this._target[this._property]);
  25703. }
  25704. else {
  25705. check = this.value === this._target[this._property];
  25706. }
  25707. return this.operator === ValueCondition.IsEqual ? check : !check;
  25708. }
  25709. return false;
  25710. };
  25711. // Statics
  25712. ValueCondition._IsEqual = 0;
  25713. ValueCondition._IsDifferent = 1;
  25714. ValueCondition._IsGreater = 2;
  25715. ValueCondition._IsLesser = 3;
  25716. return ValueCondition;
  25717. })(Condition);
  25718. BABYLON.ValueCondition = ValueCondition;
  25719. var PredicateCondition = (function (_super) {
  25720. __extends(PredicateCondition, _super);
  25721. function PredicateCondition(actionManager, predicate) {
  25722. _super.call(this, actionManager);
  25723. this.predicate = predicate;
  25724. }
  25725. PredicateCondition.prototype.isValid = function () {
  25726. return this.predicate();
  25727. };
  25728. return PredicateCondition;
  25729. })(Condition);
  25730. BABYLON.PredicateCondition = PredicateCondition;
  25731. var StateCondition = (function (_super) {
  25732. __extends(StateCondition, _super);
  25733. function StateCondition(actionManager, target, value) {
  25734. _super.call(this, actionManager);
  25735. this.value = value;
  25736. this._target = target;
  25737. }
  25738. // Methods
  25739. StateCondition.prototype.isValid = function () {
  25740. return this._target.state === this.value;
  25741. };
  25742. return StateCondition;
  25743. })(Condition);
  25744. BABYLON.StateCondition = StateCondition;
  25745. })(BABYLON || (BABYLON = {}));
  25746. //# sourceMappingURL=babylon.condition.js.map
  25747. var BABYLON;
  25748. (function (BABYLON) {
  25749. var Action = (function () {
  25750. function Action(triggerOptions, condition) {
  25751. this.triggerOptions = triggerOptions;
  25752. if (triggerOptions.parameter) {
  25753. this.trigger = triggerOptions.trigger;
  25754. this._triggerParameter = triggerOptions.parameter;
  25755. }
  25756. else {
  25757. this.trigger = triggerOptions;
  25758. }
  25759. this._nextActiveAction = this;
  25760. this._condition = condition;
  25761. }
  25762. // Methods
  25763. Action.prototype._prepare = function () {
  25764. };
  25765. Action.prototype.getTriggerParameter = function () {
  25766. return this._triggerParameter;
  25767. };
  25768. Action.prototype._executeCurrent = function (evt) {
  25769. if (this._nextActiveAction._condition) {
  25770. var condition = this._nextActiveAction._condition;
  25771. var currentRenderId = this._actionManager.getScene().getRenderId();
  25772. // We cache the current evaluation for the current frame
  25773. if (condition._evaluationId === currentRenderId) {
  25774. if (!condition._currentResult) {
  25775. return;
  25776. }
  25777. }
  25778. else {
  25779. condition._evaluationId = currentRenderId;
  25780. if (!condition.isValid()) {
  25781. condition._currentResult = false;
  25782. return;
  25783. }
  25784. condition._currentResult = true;
  25785. }
  25786. }
  25787. this._nextActiveAction.execute(evt);
  25788. if (this._nextActiveAction._child) {
  25789. if (!this._nextActiveAction._child._actionManager) {
  25790. this._nextActiveAction._child._actionManager = this._actionManager;
  25791. }
  25792. this._nextActiveAction = this._nextActiveAction._child;
  25793. }
  25794. else {
  25795. this._nextActiveAction = this;
  25796. }
  25797. };
  25798. Action.prototype.execute = function (evt) {
  25799. };
  25800. Action.prototype.then = function (action) {
  25801. this._child = action;
  25802. action._actionManager = this._actionManager;
  25803. action._prepare();
  25804. return action;
  25805. };
  25806. Action.prototype._getProperty = function (propertyPath) {
  25807. return this._actionManager._getProperty(propertyPath);
  25808. };
  25809. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25810. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25811. };
  25812. return Action;
  25813. })();
  25814. BABYLON.Action = Action;
  25815. })(BABYLON || (BABYLON = {}));
  25816. //# sourceMappingURL=babylon.action.js.map
  25817. var BABYLON;
  25818. (function (BABYLON) {
  25819. /**
  25820. * ActionEvent is the event beint sent when an action is triggered.
  25821. */
  25822. var ActionEvent = (function () {
  25823. /**
  25824. * @constructor
  25825. * @param source The mesh that triggered the action.
  25826. * @param pointerX the X mouse cursor position at the time of the event
  25827. * @param pointerY the Y mouse cursor position at the time of the event
  25828. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25829. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25830. */
  25831. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25832. this.source = source;
  25833. this.pointerX = pointerX;
  25834. this.pointerY = pointerY;
  25835. this.meshUnderPointer = meshUnderPointer;
  25836. this.sourceEvent = sourceEvent;
  25837. }
  25838. /**
  25839. * Helper function to auto-create an ActionEvent from a source mesh.
  25840. * @param source the source mesh that triggered the event
  25841. * @param evt {Event} The original (browser) event
  25842. */
  25843. ActionEvent.CreateNew = function (source, evt) {
  25844. var scene = source.getScene();
  25845. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25846. };
  25847. /**
  25848. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25849. * @param scene the scene where the event occurred
  25850. * @param evt {Event} The original (browser) event
  25851. */
  25852. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25853. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25854. };
  25855. return ActionEvent;
  25856. })();
  25857. BABYLON.ActionEvent = ActionEvent;
  25858. /**
  25859. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25860. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25861. */
  25862. var ActionManager = (function () {
  25863. function ActionManager(scene) {
  25864. // Members
  25865. this.actions = new Array();
  25866. this._scene = scene;
  25867. scene._actionManagers.push(this);
  25868. }
  25869. Object.defineProperty(ActionManager, "NothingTrigger", {
  25870. get: function () {
  25871. return ActionManager._NothingTrigger;
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25877. get: function () {
  25878. return ActionManager._OnPickTrigger;
  25879. },
  25880. enumerable: true,
  25881. configurable: true
  25882. });
  25883. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25884. get: function () {
  25885. return ActionManager._OnLeftPickTrigger;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25891. get: function () {
  25892. return ActionManager._OnRightPickTrigger;
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25898. get: function () {
  25899. return ActionManager._OnCenterPickTrigger;
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25905. get: function () {
  25906. return ActionManager._OnPointerOverTrigger;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25912. get: function () {
  25913. return ActionManager._OnPointerOutTrigger;
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25919. get: function () {
  25920. return ActionManager._OnEveryFrameTrigger;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25926. get: function () {
  25927. return ActionManager._OnIntersectionEnterTrigger;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25933. get: function () {
  25934. return ActionManager._OnIntersectionExitTrigger;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25940. get: function () {
  25941. return ActionManager._OnKeyDownTrigger;
  25942. },
  25943. enumerable: true,
  25944. configurable: true
  25945. });
  25946. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25947. get: function () {
  25948. return ActionManager._OnKeyUpTrigger;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25954. get: function () {
  25955. return ActionManager._OnPickUpTrigger;
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. // Methods
  25961. ActionManager.prototype.dispose = function () {
  25962. var index = this._scene._actionManagers.indexOf(this);
  25963. if (index > -1) {
  25964. this._scene._actionManagers.splice(index, 1);
  25965. }
  25966. };
  25967. ActionManager.prototype.getScene = function () {
  25968. return this._scene;
  25969. };
  25970. /**
  25971. * Does this action manager handles actions of any of the given triggers
  25972. * @param {number[]} triggers - the triggers to be tested
  25973. * @return {boolean} whether one (or more) of the triggers is handeled
  25974. */
  25975. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25976. for (var index = 0; index < this.actions.length; index++) {
  25977. var action = this.actions[index];
  25978. if (triggers.indexOf(action.trigger) > -1) {
  25979. return true;
  25980. }
  25981. }
  25982. return false;
  25983. };
  25984. /**
  25985. * Does this action manager handles actions of a given trigger
  25986. * @param {number} trigger - the trigger to be tested
  25987. * @return {boolean} whether the trigger is handeled
  25988. */
  25989. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25990. for (var index = 0; index < this.actions.length; index++) {
  25991. var action = this.actions[index];
  25992. if (action.trigger === trigger) {
  25993. return true;
  25994. }
  25995. }
  25996. return false;
  25997. };
  25998. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25999. /**
  26000. * Does this action manager has pointer triggers
  26001. * @return {boolean} whether or not it has pointer triggers
  26002. */
  26003. get: function () {
  26004. for (var index = 0; index < this.actions.length; index++) {
  26005. var action = this.actions[index];
  26006. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26007. return true;
  26008. }
  26009. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26010. return true;
  26011. }
  26012. }
  26013. return false;
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26019. /**
  26020. * Does this action manager has pick triggers
  26021. * @return {boolean} whether or not it has pick triggers
  26022. */
  26023. get: function () {
  26024. for (var index = 0; index < this.actions.length; index++) {
  26025. var action = this.actions[index];
  26026. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26027. return true;
  26028. }
  26029. }
  26030. return false;
  26031. },
  26032. enumerable: true,
  26033. configurable: true
  26034. });
  26035. /**
  26036. * Registers an action to this action manager
  26037. * @param {BABYLON.Action} action - the action to be registered
  26038. * @return {BABYLON.Action} the action amended (prepared) after registration
  26039. */
  26040. ActionManager.prototype.registerAction = function (action) {
  26041. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26042. if (this.getScene().actionManager !== this) {
  26043. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26044. return null;
  26045. }
  26046. }
  26047. this.actions.push(action);
  26048. action._actionManager = this;
  26049. action._prepare();
  26050. return action;
  26051. };
  26052. /**
  26053. * Process a specific trigger
  26054. * @param {number} trigger - the trigger to process
  26055. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26056. */
  26057. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26058. for (var index = 0; index < this.actions.length; index++) {
  26059. var action = this.actions[index];
  26060. if (action.trigger === trigger) {
  26061. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26062. var parameter = action.getTriggerParameter();
  26063. if (parameter) {
  26064. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26065. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26066. if (actualkey !== parameter.toLowerCase()) {
  26067. continue;
  26068. }
  26069. }
  26070. }
  26071. action._executeCurrent(evt);
  26072. }
  26073. }
  26074. };
  26075. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26076. var properties = propertyPath.split(".");
  26077. for (var index = 0; index < properties.length - 1; index++) {
  26078. target = target[properties[index]];
  26079. }
  26080. return target;
  26081. };
  26082. ActionManager.prototype._getProperty = function (propertyPath) {
  26083. var properties = propertyPath.split(".");
  26084. return properties[properties.length - 1];
  26085. };
  26086. // Statics
  26087. ActionManager._NothingTrigger = 0;
  26088. ActionManager._OnPickTrigger = 1;
  26089. ActionManager._OnLeftPickTrigger = 2;
  26090. ActionManager._OnRightPickTrigger = 3;
  26091. ActionManager._OnCenterPickTrigger = 4;
  26092. ActionManager._OnPointerOverTrigger = 5;
  26093. ActionManager._OnPointerOutTrigger = 6;
  26094. ActionManager._OnEveryFrameTrigger = 7;
  26095. ActionManager._OnIntersectionEnterTrigger = 8;
  26096. ActionManager._OnIntersectionExitTrigger = 9;
  26097. ActionManager._OnKeyDownTrigger = 10;
  26098. ActionManager._OnKeyUpTrigger = 11;
  26099. ActionManager._OnPickUpTrigger = 12;
  26100. return ActionManager;
  26101. })();
  26102. BABYLON.ActionManager = ActionManager;
  26103. })(BABYLON || (BABYLON = {}));
  26104. //# sourceMappingURL=babylon.actionManager.js.map
  26105. var __extends = this.__extends || function (d, b) {
  26106. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26107. function __() { this.constructor = d; }
  26108. __.prototype = b.prototype;
  26109. d.prototype = new __();
  26110. };
  26111. var BABYLON;
  26112. (function (BABYLON) {
  26113. var InterpolateValueAction = (function (_super) {
  26114. __extends(InterpolateValueAction, _super);
  26115. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26116. if (duration === void 0) { duration = 1000; }
  26117. _super.call(this, triggerOptions, condition);
  26118. this.propertyPath = propertyPath;
  26119. this.value = value;
  26120. this.duration = duration;
  26121. this.stopOtherAnimations = stopOtherAnimations;
  26122. this._target = target;
  26123. }
  26124. InterpolateValueAction.prototype._prepare = function () {
  26125. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26126. this._property = this._getProperty(this.propertyPath);
  26127. };
  26128. InterpolateValueAction.prototype.execute = function () {
  26129. var scene = this._actionManager.getScene();
  26130. var keys = [
  26131. {
  26132. frame: 0,
  26133. value: this._target[this._property]
  26134. },
  26135. {
  26136. frame: 100,
  26137. value: this.value
  26138. }
  26139. ];
  26140. var dataType;
  26141. if (typeof this.value === "number") {
  26142. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26143. }
  26144. else if (this.value instanceof BABYLON.Color3) {
  26145. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26146. }
  26147. else if (this.value instanceof BABYLON.Vector3) {
  26148. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26149. }
  26150. else if (this.value instanceof BABYLON.Matrix) {
  26151. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26152. }
  26153. else if (this.value instanceof BABYLON.Quaternion) {
  26154. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26155. }
  26156. else {
  26157. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26158. return;
  26159. }
  26160. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26161. animation.setKeys(keys);
  26162. if (this.stopOtherAnimations) {
  26163. scene.stopAnimation(this._target);
  26164. }
  26165. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26166. };
  26167. return InterpolateValueAction;
  26168. })(BABYLON.Action);
  26169. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26170. })(BABYLON || (BABYLON = {}));
  26171. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26172. var __extends = this.__extends || function (d, b) {
  26173. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26174. function __() { this.constructor = d; }
  26175. __.prototype = b.prototype;
  26176. d.prototype = new __();
  26177. };
  26178. var BABYLON;
  26179. (function (BABYLON) {
  26180. var SwitchBooleanAction = (function (_super) {
  26181. __extends(SwitchBooleanAction, _super);
  26182. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26183. _super.call(this, triggerOptions, condition);
  26184. this.propertyPath = propertyPath;
  26185. this._target = target;
  26186. }
  26187. SwitchBooleanAction.prototype._prepare = function () {
  26188. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26189. this._property = this._getProperty(this.propertyPath);
  26190. };
  26191. SwitchBooleanAction.prototype.execute = function () {
  26192. this._target[this._property] = !this._target[this._property];
  26193. };
  26194. return SwitchBooleanAction;
  26195. })(BABYLON.Action);
  26196. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26197. var SetStateAction = (function (_super) {
  26198. __extends(SetStateAction, _super);
  26199. function SetStateAction(triggerOptions, target, value, condition) {
  26200. _super.call(this, triggerOptions, condition);
  26201. this.value = value;
  26202. this._target = target;
  26203. }
  26204. SetStateAction.prototype.execute = function () {
  26205. this._target.state = this.value;
  26206. };
  26207. return SetStateAction;
  26208. })(BABYLON.Action);
  26209. BABYLON.SetStateAction = SetStateAction;
  26210. var SetValueAction = (function (_super) {
  26211. __extends(SetValueAction, _super);
  26212. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26213. _super.call(this, triggerOptions, condition);
  26214. this.propertyPath = propertyPath;
  26215. this.value = value;
  26216. this._target = target;
  26217. }
  26218. SetValueAction.prototype._prepare = function () {
  26219. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26220. this._property = this._getProperty(this.propertyPath);
  26221. };
  26222. SetValueAction.prototype.execute = function () {
  26223. this._target[this._property] = this.value;
  26224. };
  26225. return SetValueAction;
  26226. })(BABYLON.Action);
  26227. BABYLON.SetValueAction = SetValueAction;
  26228. var IncrementValueAction = (function (_super) {
  26229. __extends(IncrementValueAction, _super);
  26230. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26231. _super.call(this, triggerOptions, condition);
  26232. this.propertyPath = propertyPath;
  26233. this.value = value;
  26234. this._target = target;
  26235. }
  26236. IncrementValueAction.prototype._prepare = function () {
  26237. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26238. this._property = this._getProperty(this.propertyPath);
  26239. if (typeof this._target[this._property] !== "number") {
  26240. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26241. }
  26242. };
  26243. IncrementValueAction.prototype.execute = function () {
  26244. this._target[this._property] += this.value;
  26245. };
  26246. return IncrementValueAction;
  26247. })(BABYLON.Action);
  26248. BABYLON.IncrementValueAction = IncrementValueAction;
  26249. var PlayAnimationAction = (function (_super) {
  26250. __extends(PlayAnimationAction, _super);
  26251. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26252. _super.call(this, triggerOptions, condition);
  26253. this.from = from;
  26254. this.to = to;
  26255. this.loop = loop;
  26256. this._target = target;
  26257. }
  26258. PlayAnimationAction.prototype._prepare = function () {
  26259. };
  26260. PlayAnimationAction.prototype.execute = function () {
  26261. var scene = this._actionManager.getScene();
  26262. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26263. };
  26264. return PlayAnimationAction;
  26265. })(BABYLON.Action);
  26266. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26267. var StopAnimationAction = (function (_super) {
  26268. __extends(StopAnimationAction, _super);
  26269. function StopAnimationAction(triggerOptions, target, condition) {
  26270. _super.call(this, triggerOptions, condition);
  26271. this._target = target;
  26272. }
  26273. StopAnimationAction.prototype._prepare = function () {
  26274. };
  26275. StopAnimationAction.prototype.execute = function () {
  26276. var scene = this._actionManager.getScene();
  26277. scene.stopAnimation(this._target);
  26278. };
  26279. return StopAnimationAction;
  26280. })(BABYLON.Action);
  26281. BABYLON.StopAnimationAction = StopAnimationAction;
  26282. var DoNothingAction = (function (_super) {
  26283. __extends(DoNothingAction, _super);
  26284. function DoNothingAction(triggerOptions, condition) {
  26285. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26286. _super.call(this, triggerOptions, condition);
  26287. }
  26288. DoNothingAction.prototype.execute = function () {
  26289. };
  26290. return DoNothingAction;
  26291. })(BABYLON.Action);
  26292. BABYLON.DoNothingAction = DoNothingAction;
  26293. var CombineAction = (function (_super) {
  26294. __extends(CombineAction, _super);
  26295. function CombineAction(triggerOptions, children, condition) {
  26296. _super.call(this, triggerOptions, condition);
  26297. this.children = children;
  26298. }
  26299. CombineAction.prototype._prepare = function () {
  26300. for (var index = 0; index < this.children.length; index++) {
  26301. this.children[index]._actionManager = this._actionManager;
  26302. this.children[index]._prepare();
  26303. }
  26304. };
  26305. CombineAction.prototype.execute = function (evt) {
  26306. for (var index = 0; index < this.children.length; index++) {
  26307. this.children[index].execute(evt);
  26308. }
  26309. };
  26310. return CombineAction;
  26311. })(BABYLON.Action);
  26312. BABYLON.CombineAction = CombineAction;
  26313. var ExecuteCodeAction = (function (_super) {
  26314. __extends(ExecuteCodeAction, _super);
  26315. function ExecuteCodeAction(triggerOptions, func, condition) {
  26316. _super.call(this, triggerOptions, condition);
  26317. this.func = func;
  26318. }
  26319. ExecuteCodeAction.prototype.execute = function (evt) {
  26320. this.func(evt);
  26321. };
  26322. return ExecuteCodeAction;
  26323. })(BABYLON.Action);
  26324. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26325. var SetParentAction = (function (_super) {
  26326. __extends(SetParentAction, _super);
  26327. function SetParentAction(triggerOptions, target, parent, condition) {
  26328. _super.call(this, triggerOptions, condition);
  26329. this._target = target;
  26330. this._parent = parent;
  26331. }
  26332. SetParentAction.prototype._prepare = function () {
  26333. };
  26334. SetParentAction.prototype.execute = function () {
  26335. if (this._target.parent === this._parent) {
  26336. return;
  26337. }
  26338. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26339. invertParentWorldMatrix.invert();
  26340. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26341. this._target.parent = this._parent;
  26342. };
  26343. return SetParentAction;
  26344. })(BABYLON.Action);
  26345. BABYLON.SetParentAction = SetParentAction;
  26346. var PlaySoundAction = (function (_super) {
  26347. __extends(PlaySoundAction, _super);
  26348. function PlaySoundAction(triggerOptions, sound, condition) {
  26349. _super.call(this, triggerOptions, condition);
  26350. this._sound = sound;
  26351. }
  26352. PlaySoundAction.prototype._prepare = function () {
  26353. };
  26354. PlaySoundAction.prototype.execute = function () {
  26355. if (this._sound !== undefined)
  26356. this._sound.play();
  26357. };
  26358. return PlaySoundAction;
  26359. })(BABYLON.Action);
  26360. BABYLON.PlaySoundAction = PlaySoundAction;
  26361. var StopSoundAction = (function (_super) {
  26362. __extends(StopSoundAction, _super);
  26363. function StopSoundAction(triggerOptions, sound, condition) {
  26364. _super.call(this, triggerOptions, condition);
  26365. this._sound = sound;
  26366. }
  26367. StopSoundAction.prototype._prepare = function () {
  26368. };
  26369. StopSoundAction.prototype.execute = function () {
  26370. if (this._sound !== undefined)
  26371. this._sound.stop();
  26372. };
  26373. return StopSoundAction;
  26374. })(BABYLON.Action);
  26375. BABYLON.StopSoundAction = StopSoundAction;
  26376. })(BABYLON || (BABYLON = {}));
  26377. //# sourceMappingURL=babylon.directActions.js.map
  26378. var __extends = this.__extends || function (d, b) {
  26379. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26380. function __() { this.constructor = d; }
  26381. __.prototype = b.prototype;
  26382. d.prototype = new __();
  26383. };
  26384. var BABYLON;
  26385. (function (BABYLON) {
  26386. var Geometry = (function () {
  26387. function Geometry(id, scene, vertexData, updatable, mesh) {
  26388. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26389. this._totalVertices = 0;
  26390. this._indices = [];
  26391. this._isDisposed = false;
  26392. this.id = id;
  26393. this._engine = scene.getEngine();
  26394. this._meshes = [];
  26395. this._scene = scene;
  26396. // vertexData
  26397. if (vertexData) {
  26398. this.setAllVerticesData(vertexData, updatable);
  26399. }
  26400. else {
  26401. this._totalVertices = 0;
  26402. this._indices = [];
  26403. }
  26404. // applyToMesh
  26405. if (mesh) {
  26406. this.applyToMesh(mesh);
  26407. mesh.computeWorldMatrix(true);
  26408. }
  26409. }
  26410. Geometry.prototype.getScene = function () {
  26411. return this._scene;
  26412. };
  26413. Geometry.prototype.getEngine = function () {
  26414. return this._engine;
  26415. };
  26416. Geometry.prototype.isReady = function () {
  26417. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26418. };
  26419. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26420. vertexData.applyToGeometry(this, updatable);
  26421. this.notifyUpdate();
  26422. };
  26423. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26424. this._vertexBuffers = this._vertexBuffers || {};
  26425. if (this._vertexBuffers[kind]) {
  26426. this._vertexBuffers[kind].dispose();
  26427. }
  26428. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26429. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26430. stride = this._vertexBuffers[kind].getStrideSize();
  26431. this._totalVertices = data.length / stride;
  26432. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26433. var meshes = this._meshes;
  26434. var numOfMeshes = meshes.length;
  26435. for (var index = 0; index < numOfMeshes; index++) {
  26436. var mesh = meshes[index];
  26437. mesh._resetPointsArrayCache();
  26438. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26439. mesh._createGlobalSubMesh();
  26440. mesh.computeWorldMatrix(true);
  26441. }
  26442. }
  26443. this.notifyUpdate(kind);
  26444. };
  26445. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26446. var vertexBuffer = this.getVertexBuffer(kind);
  26447. if (!vertexBuffer) {
  26448. return;
  26449. }
  26450. vertexBuffer.updateDirectly(data, offset);
  26451. this.notifyUpdate(kind);
  26452. };
  26453. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26454. var vertexBuffer = this.getVertexBuffer(kind);
  26455. if (!vertexBuffer) {
  26456. return;
  26457. }
  26458. vertexBuffer.update(data);
  26459. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26460. var extend;
  26461. var stride = vertexBuffer.getStrideSize();
  26462. this._totalVertices = data.length / stride;
  26463. if (updateExtends) {
  26464. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26465. }
  26466. var meshes = this._meshes;
  26467. var numOfMeshes = meshes.length;
  26468. for (var index = 0; index < numOfMeshes; index++) {
  26469. var mesh = meshes[index];
  26470. mesh._resetPointsArrayCache();
  26471. if (updateExtends) {
  26472. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26473. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26474. var subMesh = mesh.subMeshes[subIndex];
  26475. subMesh.refreshBoundingInfo();
  26476. }
  26477. }
  26478. }
  26479. }
  26480. this.notifyUpdate(kind);
  26481. };
  26482. Geometry.prototype.getTotalVertices = function () {
  26483. if (!this.isReady()) {
  26484. return 0;
  26485. }
  26486. return this._totalVertices;
  26487. };
  26488. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26489. var vertexBuffer = this.getVertexBuffer(kind);
  26490. if (!vertexBuffer) {
  26491. return null;
  26492. }
  26493. var orig = vertexBuffer.getData();
  26494. if (!copyWhenShared || this._meshes.length === 1) {
  26495. return orig;
  26496. }
  26497. else {
  26498. var len = orig.length;
  26499. var copy = [];
  26500. for (var i = 0; i < len; i++) {
  26501. copy.push(orig[i]);
  26502. }
  26503. return copy;
  26504. }
  26505. };
  26506. Geometry.prototype.getVertexBuffer = function (kind) {
  26507. if (!this.isReady()) {
  26508. return null;
  26509. }
  26510. return this._vertexBuffers[kind];
  26511. };
  26512. Geometry.prototype.getVertexBuffers = function () {
  26513. if (!this.isReady()) {
  26514. return null;
  26515. }
  26516. return this._vertexBuffers;
  26517. };
  26518. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26519. if (!this._vertexBuffers) {
  26520. if (this._delayInfo) {
  26521. return this._delayInfo.indexOf(kind) !== -1;
  26522. }
  26523. return false;
  26524. }
  26525. return this._vertexBuffers[kind] !== undefined;
  26526. };
  26527. Geometry.prototype.getVerticesDataKinds = function () {
  26528. var result = [];
  26529. if (!this._vertexBuffers && this._delayInfo) {
  26530. for (var kind in this._delayInfo) {
  26531. result.push(kind);
  26532. }
  26533. }
  26534. else {
  26535. for (kind in this._vertexBuffers) {
  26536. result.push(kind);
  26537. }
  26538. }
  26539. return result;
  26540. };
  26541. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26542. if (this._indexBuffer) {
  26543. this._engine._releaseBuffer(this._indexBuffer);
  26544. }
  26545. this._indices = indices;
  26546. if (this._meshes.length !== 0 && this._indices) {
  26547. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26548. }
  26549. if (totalVertices !== undefined) {
  26550. this._totalVertices = totalVertices;
  26551. }
  26552. var meshes = this._meshes;
  26553. var numOfMeshes = meshes.length;
  26554. for (var index = 0; index < numOfMeshes; index++) {
  26555. meshes[index]._createGlobalSubMesh();
  26556. }
  26557. this.notifyUpdate();
  26558. };
  26559. Geometry.prototype.getTotalIndices = function () {
  26560. if (!this.isReady()) {
  26561. return 0;
  26562. }
  26563. return this._indices.length;
  26564. };
  26565. Geometry.prototype.getIndices = function (copyWhenShared) {
  26566. if (!this.isReady()) {
  26567. return null;
  26568. }
  26569. var orig = this._indices;
  26570. if (!copyWhenShared || this._meshes.length === 1) {
  26571. return orig;
  26572. }
  26573. else {
  26574. var len = orig.length;
  26575. var copy = [];
  26576. for (var i = 0; i < len; i++) {
  26577. copy.push(orig[i]);
  26578. }
  26579. return copy;
  26580. }
  26581. };
  26582. Geometry.prototype.getIndexBuffer = function () {
  26583. if (!this.isReady()) {
  26584. return null;
  26585. }
  26586. return this._indexBuffer;
  26587. };
  26588. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26589. var meshes = this._meshes;
  26590. var index = meshes.indexOf(mesh);
  26591. if (index === -1) {
  26592. return;
  26593. }
  26594. for (var kind in this._vertexBuffers) {
  26595. this._vertexBuffers[kind].dispose();
  26596. }
  26597. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26598. this._indexBuffer = null;
  26599. }
  26600. meshes.splice(index, 1);
  26601. mesh._geometry = null;
  26602. if (meshes.length === 0 && shouldDispose) {
  26603. this.dispose();
  26604. }
  26605. };
  26606. Geometry.prototype.applyToMesh = function (mesh) {
  26607. if (mesh._geometry === this) {
  26608. return;
  26609. }
  26610. var previousGeometry = mesh._geometry;
  26611. if (previousGeometry) {
  26612. previousGeometry.releaseForMesh(mesh);
  26613. }
  26614. var meshes = this._meshes;
  26615. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26616. mesh._geometry = this;
  26617. this._scene.pushGeometry(this);
  26618. meshes.push(mesh);
  26619. if (this.isReady()) {
  26620. this._applyToMesh(mesh);
  26621. }
  26622. else {
  26623. mesh._boundingInfo = this._boundingInfo;
  26624. }
  26625. };
  26626. Geometry.prototype._applyToMesh = function (mesh) {
  26627. var numOfMeshes = this._meshes.length;
  26628. for (var kind in this._vertexBuffers) {
  26629. if (numOfMeshes === 1) {
  26630. this._vertexBuffers[kind].create();
  26631. }
  26632. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26633. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26634. mesh._resetPointsArrayCache();
  26635. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26636. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26637. mesh._createGlobalSubMesh();
  26638. //bounding info was just created again, world matrix should be applied again.
  26639. mesh._updateBoundingInfo();
  26640. }
  26641. }
  26642. // indexBuffer
  26643. if (numOfMeshes === 1 && this._indices) {
  26644. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26645. }
  26646. if (this._indexBuffer) {
  26647. this._indexBuffer.references = numOfMeshes;
  26648. }
  26649. };
  26650. Geometry.prototype.notifyUpdate = function (kind) {
  26651. if (this.onGeometryUpdated) {
  26652. this.onGeometryUpdated(this, kind);
  26653. }
  26654. };
  26655. Geometry.prototype.load = function (scene, onLoaded) {
  26656. var _this = this;
  26657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26658. return;
  26659. }
  26660. if (this.isReady()) {
  26661. if (onLoaded) {
  26662. onLoaded();
  26663. }
  26664. return;
  26665. }
  26666. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26667. scene._addPendingData(this);
  26668. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26669. _this._delayLoadingFunction(JSON.parse(data), _this);
  26670. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26671. _this._delayInfo = [];
  26672. scene._removePendingData(_this);
  26673. var meshes = _this._meshes;
  26674. var numOfMeshes = meshes.length;
  26675. for (var index = 0; index < numOfMeshes; index++) {
  26676. _this._applyToMesh(meshes[index]);
  26677. }
  26678. if (onLoaded) {
  26679. onLoaded();
  26680. }
  26681. }, function () {
  26682. }, scene.database);
  26683. };
  26684. Geometry.prototype.isDisposed = function () {
  26685. return this._isDisposed;
  26686. };
  26687. Geometry.prototype.dispose = function () {
  26688. var meshes = this._meshes;
  26689. var numOfMeshes = meshes.length;
  26690. var index;
  26691. for (index = 0; index < numOfMeshes; index++) {
  26692. this.releaseForMesh(meshes[index]);
  26693. }
  26694. this._meshes = [];
  26695. for (var kind in this._vertexBuffers) {
  26696. this._vertexBuffers[kind].dispose();
  26697. }
  26698. this._vertexBuffers = [];
  26699. this._totalVertices = 0;
  26700. if (this._indexBuffer) {
  26701. this._engine._releaseBuffer(this._indexBuffer);
  26702. }
  26703. this._indexBuffer = null;
  26704. this._indices = [];
  26705. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26706. this.delayLoadingFile = null;
  26707. this._delayLoadingFunction = null;
  26708. this._delayInfo = [];
  26709. this._boundingInfo = null; // todo: .dispose()
  26710. this._scene.removeGeometry(this);
  26711. this._isDisposed = true;
  26712. };
  26713. Geometry.prototype.copy = function (id) {
  26714. var vertexData = new BABYLON.VertexData();
  26715. vertexData.indices = [];
  26716. var indices = this.getIndices();
  26717. for (var index = 0; index < indices.length; index++) {
  26718. vertexData.indices.push(indices[index]);
  26719. }
  26720. var updatable = false;
  26721. var stopChecking = false;
  26722. for (var kind in this._vertexBuffers) {
  26723. // using slice() to make a copy of the array and not just reference it
  26724. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26725. if (!stopChecking) {
  26726. updatable = this.getVertexBuffer(kind).isUpdatable();
  26727. stopChecking = !updatable;
  26728. }
  26729. }
  26730. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26731. geometry.delayLoadState = this.delayLoadState;
  26732. geometry.delayLoadingFile = this.delayLoadingFile;
  26733. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26734. for (kind in this._delayInfo) {
  26735. geometry._delayInfo = geometry._delayInfo || [];
  26736. geometry._delayInfo.push(kind);
  26737. }
  26738. // Bounding info
  26739. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26740. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26741. return geometry;
  26742. };
  26743. // Statics
  26744. Geometry.ExtractFromMesh = function (mesh, id) {
  26745. var geometry = mesh._geometry;
  26746. if (!geometry) {
  26747. return null;
  26748. }
  26749. return geometry.copy(id);
  26750. };
  26751. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26752. // be aware Math.random() could cause collisions
  26753. Geometry.RandomId = function () {
  26754. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26755. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26756. return v.toString(16);
  26757. });
  26758. };
  26759. return Geometry;
  26760. })();
  26761. BABYLON.Geometry = Geometry;
  26762. /////// Primitives //////////////////////////////////////////////
  26763. var Geometry;
  26764. (function (Geometry) {
  26765. var Primitives;
  26766. (function (Primitives) {
  26767. /// Abstract class
  26768. var _Primitive = (function (_super) {
  26769. __extends(_Primitive, _super);
  26770. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26771. this._beingRegenerated = true;
  26772. this._canBeRegenerated = canBeRegenerated;
  26773. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26774. this._beingRegenerated = false;
  26775. }
  26776. _Primitive.prototype.canBeRegenerated = function () {
  26777. return this._canBeRegenerated;
  26778. };
  26779. _Primitive.prototype.regenerate = function () {
  26780. if (!this._canBeRegenerated) {
  26781. return;
  26782. }
  26783. this._beingRegenerated = true;
  26784. this.setAllVerticesData(this._regenerateVertexData(), false);
  26785. this._beingRegenerated = false;
  26786. };
  26787. _Primitive.prototype.asNewGeometry = function (id) {
  26788. return _super.prototype.copy.call(this, id);
  26789. };
  26790. // overrides
  26791. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26792. if (!this._beingRegenerated) {
  26793. return;
  26794. }
  26795. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26796. };
  26797. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26798. if (!this._beingRegenerated) {
  26799. return;
  26800. }
  26801. _super.prototype.setVerticesData.call(this, kind, data, false);
  26802. };
  26803. // to override
  26804. // protected
  26805. _Primitive.prototype._regenerateVertexData = function () {
  26806. throw new Error("Abstract method");
  26807. };
  26808. _Primitive.prototype.copy = function (id) {
  26809. throw new Error("Must be overriden in sub-classes.");
  26810. };
  26811. return _Primitive;
  26812. })(Geometry);
  26813. Primitives._Primitive = _Primitive;
  26814. var Ribbon = (function (_super) {
  26815. __extends(Ribbon, _super);
  26816. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26818. this.pathArray = pathArray;
  26819. this.closeArray = closeArray;
  26820. this.closePath = closePath;
  26821. this.offset = offset;
  26822. this.side = side;
  26823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26824. }
  26825. Ribbon.prototype._regenerateVertexData = function () {
  26826. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26827. };
  26828. Ribbon.prototype.copy = function (id) {
  26829. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26830. };
  26831. return Ribbon;
  26832. })(_Primitive);
  26833. Primitives.Ribbon = Ribbon;
  26834. var Box = (function (_super) {
  26835. __extends(Box, _super);
  26836. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26838. this.size = size;
  26839. this.side = side;
  26840. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26841. }
  26842. Box.prototype._regenerateVertexData = function () {
  26843. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26844. };
  26845. Box.prototype.copy = function (id) {
  26846. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26847. };
  26848. return Box;
  26849. })(_Primitive);
  26850. Primitives.Box = Box;
  26851. var Sphere = (function (_super) {
  26852. __extends(Sphere, _super);
  26853. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26854. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26855. this.segments = segments;
  26856. this.diameter = diameter;
  26857. this.side = side;
  26858. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26859. }
  26860. Sphere.prototype._regenerateVertexData = function () {
  26861. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26862. };
  26863. Sphere.prototype.copy = function (id) {
  26864. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26865. };
  26866. return Sphere;
  26867. })(_Primitive);
  26868. Primitives.Sphere = Sphere;
  26869. var Cylinder = (function (_super) {
  26870. __extends(Cylinder, _super);
  26871. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26872. if (subdivisions === void 0) { subdivisions = 1; }
  26873. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26874. this.height = height;
  26875. this.diameterTop = diameterTop;
  26876. this.diameterBottom = diameterBottom;
  26877. this.tessellation = tessellation;
  26878. this.subdivisions = subdivisions;
  26879. this.side = side;
  26880. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26881. }
  26882. Cylinder.prototype._regenerateVertexData = function () {
  26883. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26884. };
  26885. Cylinder.prototype.copy = function (id) {
  26886. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26887. };
  26888. return Cylinder;
  26889. })(_Primitive);
  26890. Primitives.Cylinder = Cylinder;
  26891. var Torus = (function (_super) {
  26892. __extends(Torus, _super);
  26893. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26894. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26895. this.diameter = diameter;
  26896. this.thickness = thickness;
  26897. this.tessellation = tessellation;
  26898. this.side = side;
  26899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26900. }
  26901. Torus.prototype._regenerateVertexData = function () {
  26902. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26903. };
  26904. Torus.prototype.copy = function (id) {
  26905. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26906. };
  26907. return Torus;
  26908. })(_Primitive);
  26909. Primitives.Torus = Torus;
  26910. var Ground = (function (_super) {
  26911. __extends(Ground, _super);
  26912. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26913. this.width = width;
  26914. this.height = height;
  26915. this.subdivisions = subdivisions;
  26916. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26917. }
  26918. Ground.prototype._regenerateVertexData = function () {
  26919. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26920. };
  26921. Ground.prototype.copy = function (id) {
  26922. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26923. };
  26924. return Ground;
  26925. })(_Primitive);
  26926. Primitives.Ground = Ground;
  26927. var TiledGround = (function (_super) {
  26928. __extends(TiledGround, _super);
  26929. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26930. this.xmin = xmin;
  26931. this.zmin = zmin;
  26932. this.xmax = xmax;
  26933. this.zmax = zmax;
  26934. this.subdivisions = subdivisions;
  26935. this.precision = precision;
  26936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26937. }
  26938. TiledGround.prototype._regenerateVertexData = function () {
  26939. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26940. };
  26941. TiledGround.prototype.copy = function (id) {
  26942. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26943. };
  26944. return TiledGround;
  26945. })(_Primitive);
  26946. Primitives.TiledGround = TiledGround;
  26947. var Plane = (function (_super) {
  26948. __extends(Plane, _super);
  26949. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26951. this.size = size;
  26952. this.side = side;
  26953. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26954. }
  26955. Plane.prototype._regenerateVertexData = function () {
  26956. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26957. };
  26958. Plane.prototype.copy = function (id) {
  26959. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26960. };
  26961. return Plane;
  26962. })(_Primitive);
  26963. Primitives.Plane = Plane;
  26964. var TorusKnot = (function (_super) {
  26965. __extends(TorusKnot, _super);
  26966. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26967. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26968. this.radius = radius;
  26969. this.tube = tube;
  26970. this.radialSegments = radialSegments;
  26971. this.tubularSegments = tubularSegments;
  26972. this.p = p;
  26973. this.q = q;
  26974. this.side = side;
  26975. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26976. }
  26977. TorusKnot.prototype._regenerateVertexData = function () {
  26978. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26979. };
  26980. TorusKnot.prototype.copy = function (id) {
  26981. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26982. };
  26983. return TorusKnot;
  26984. })(_Primitive);
  26985. Primitives.TorusKnot = TorusKnot;
  26986. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26987. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26988. })(BABYLON || (BABYLON = {}));
  26989. //# sourceMappingURL=babylon.geometry.js.map
  26990. var __extends = this.__extends || function (d, b) {
  26991. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26992. function __() { this.constructor = d; }
  26993. __.prototype = b.prototype;
  26994. d.prototype = new __();
  26995. };
  26996. var BABYLON;
  26997. (function (BABYLON) {
  26998. var GroundMesh = (function (_super) {
  26999. __extends(GroundMesh, _super);
  27000. function GroundMesh(name, scene) {
  27001. _super.call(this, name, scene);
  27002. this.generateOctree = false;
  27003. this._worldInverse = new BABYLON.Matrix();
  27004. }
  27005. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27006. get: function () {
  27007. return this._subdivisions;
  27008. },
  27009. enumerable: true,
  27010. configurable: true
  27011. });
  27012. GroundMesh.prototype.optimize = function (chunksCount) {
  27013. this.subdivide(this._subdivisions);
  27014. this.createOrUpdateSubmeshesOctree(32);
  27015. };
  27016. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27017. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27018. this.getWorldMatrix().invertToRef(this._worldInverse);
  27019. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27020. var pickInfo = this.intersects(ray);
  27021. if (pickInfo.hit) {
  27022. return pickInfo.pickedPoint.y;
  27023. }
  27024. return 0;
  27025. };
  27026. return GroundMesh;
  27027. })(BABYLON.Mesh);
  27028. BABYLON.GroundMesh = GroundMesh;
  27029. })(BABYLON || (BABYLON = {}));
  27030. //# sourceMappingURL=babylon.groundMesh.js.map
  27031. var __extends = this.__extends || function (d, b) {
  27032. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27033. function __() { this.constructor = d; }
  27034. __.prototype = b.prototype;
  27035. d.prototype = new __();
  27036. };
  27037. var BABYLON;
  27038. (function (BABYLON) {
  27039. var Gamepads = (function () {
  27040. function Gamepads(ongamedpadconnected) {
  27041. var _this = this;
  27042. this.babylonGamepads = [];
  27043. this.oneGamepadConnected = false;
  27044. this.isMonitoring = false;
  27045. this.gamepadEventSupported = 'GamepadEvent' in window;
  27046. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27047. 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=";
  27048. this._callbackGamepadConnected = ongamedpadconnected;
  27049. if (this.gamepadSupportAvailable) {
  27050. // Checking if the gamepad connected event is supported (like in Firefox)
  27051. if (this.gamepadEventSupported) {
  27052. window.addEventListener('gamepadconnected', function (evt) {
  27053. _this._onGamepadConnected(evt);
  27054. }, false);
  27055. window.addEventListener('gamepaddisconnected', function (evt) {
  27056. _this._onGamepadDisconnected(evt);
  27057. }, false);
  27058. }
  27059. else {
  27060. this._startMonitoringGamepads();
  27061. }
  27062. if (!this.oneGamepadConnected) {
  27063. this._insertGamepadDOMInstructions();
  27064. }
  27065. }
  27066. else {
  27067. this._insertGamepadDOMNotSupported();
  27068. }
  27069. }
  27070. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27071. Gamepads.gamepadDOMInfo = document.createElement("div");
  27072. var buttonAImage = document.createElement("img");
  27073. buttonAImage.src = this.buttonADataURL;
  27074. var spanMessage = document.createElement("span");
  27075. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27076. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27077. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27078. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27079. Gamepads.gamepadDOMInfo.style.width = "100%";
  27080. Gamepads.gamepadDOMInfo.style.height = "48px";
  27081. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27082. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27083. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27084. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27085. buttonAImage.style.position = "relative";
  27086. buttonAImage.style.bottom = "8px";
  27087. spanMessage.style.position = "relative";
  27088. spanMessage.style.fontSize = "32px";
  27089. spanMessage.style.bottom = "32px";
  27090. spanMessage.style.color = "green";
  27091. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27092. };
  27093. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27094. Gamepads.gamepadDOMInfo = document.createElement("div");
  27095. var spanMessage = document.createElement("span");
  27096. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27097. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27098. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27099. Gamepads.gamepadDOMInfo.style.width = "100%";
  27100. Gamepads.gamepadDOMInfo.style.height = "40px";
  27101. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27102. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27103. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27104. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27105. spanMessage.style.position = "relative";
  27106. spanMessage.style.fontSize = "32px";
  27107. spanMessage.style.color = "red";
  27108. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27109. };
  27110. Gamepads.prototype.dispose = function () {
  27111. if (Gamepads.gamepadDOMInfo) {
  27112. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27113. }
  27114. };
  27115. Gamepads.prototype._onGamepadConnected = function (evt) {
  27116. var newGamepad = this._addNewGamepad(evt.gamepad);
  27117. if (this._callbackGamepadConnected)
  27118. this._callbackGamepadConnected(newGamepad);
  27119. this._startMonitoringGamepads();
  27120. };
  27121. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27122. if (!this.oneGamepadConnected) {
  27123. this.oneGamepadConnected = true;
  27124. if (Gamepads.gamepadDOMInfo) {
  27125. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27126. Gamepads.gamepadDOMInfo = null;
  27127. }
  27128. }
  27129. var newGamepad;
  27130. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27131. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27132. }
  27133. else {
  27134. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27135. }
  27136. this.babylonGamepads.push(newGamepad);
  27137. return newGamepad;
  27138. };
  27139. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27140. for (var i in this.babylonGamepads) {
  27141. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27142. this.babylonGamepads.splice(i, 1);
  27143. break;
  27144. }
  27145. }
  27146. // If no gamepads are left, stop the polling loop.
  27147. if (this.babylonGamepads.length == 0) {
  27148. this._stopMonitoringGamepads();
  27149. }
  27150. };
  27151. Gamepads.prototype._startMonitoringGamepads = function () {
  27152. if (!this.isMonitoring) {
  27153. this.isMonitoring = true;
  27154. this._checkGamepadsStatus();
  27155. }
  27156. };
  27157. Gamepads.prototype._stopMonitoringGamepads = function () {
  27158. this.isMonitoring = false;
  27159. };
  27160. Gamepads.prototype._checkGamepadsStatus = function () {
  27161. var _this = this;
  27162. // updating gamepad objects
  27163. this._updateGamepadObjects();
  27164. for (var i in this.babylonGamepads) {
  27165. this.babylonGamepads[i].update();
  27166. }
  27167. if (this.isMonitoring) {
  27168. if (window.requestAnimationFrame) {
  27169. window.requestAnimationFrame(function () {
  27170. _this._checkGamepadsStatus();
  27171. });
  27172. }
  27173. else if (window.mozRequestAnimationFrame) {
  27174. window.mozRequestAnimationFrame(function () {
  27175. _this._checkGamepadsStatus();
  27176. });
  27177. }
  27178. else if (window.webkitRequestAnimationFrame) {
  27179. window.webkitRequestAnimationFrame(function () {
  27180. _this._checkGamepadsStatus();
  27181. });
  27182. }
  27183. }
  27184. };
  27185. // This function is called only on Chrome, which does not yet support
  27186. // connection/disconnection events, but requires you to monitor
  27187. // an array for changes.
  27188. Gamepads.prototype._updateGamepadObjects = function () {
  27189. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27190. for (var i = 0; i < gamepads.length; i++) {
  27191. if (gamepads[i]) {
  27192. if (!(gamepads[i].index in this.babylonGamepads)) {
  27193. var newGamepad = this._addNewGamepad(gamepads[i]);
  27194. if (this._callbackGamepadConnected) {
  27195. this._callbackGamepadConnected(newGamepad);
  27196. }
  27197. }
  27198. else {
  27199. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27200. }
  27201. }
  27202. }
  27203. };
  27204. return Gamepads;
  27205. })();
  27206. BABYLON.Gamepads = Gamepads;
  27207. var StickValues = (function () {
  27208. function StickValues(x, y) {
  27209. this.x = x;
  27210. this.y = y;
  27211. }
  27212. return StickValues;
  27213. })();
  27214. BABYLON.StickValues = StickValues;
  27215. var Gamepad = (function () {
  27216. function Gamepad(id, index, browserGamepad) {
  27217. this.id = id;
  27218. this.index = index;
  27219. this.browserGamepad = browserGamepad;
  27220. if (this.browserGamepad.axes.length >= 2) {
  27221. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27222. }
  27223. if (this.browserGamepad.axes.length >= 4) {
  27224. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27225. }
  27226. }
  27227. Gamepad.prototype.onleftstickchanged = function (callback) {
  27228. this._onleftstickchanged = callback;
  27229. };
  27230. Gamepad.prototype.onrightstickchanged = function (callback) {
  27231. this._onrightstickchanged = callback;
  27232. };
  27233. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27234. get: function () {
  27235. return this._leftStick;
  27236. },
  27237. set: function (newValues) {
  27238. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27239. this._onleftstickchanged(newValues);
  27240. }
  27241. this._leftStick = newValues;
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27247. get: function () {
  27248. return this._rightStick;
  27249. },
  27250. set: function (newValues) {
  27251. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27252. this._onrightstickchanged(newValues);
  27253. }
  27254. this._rightStick = newValues;
  27255. },
  27256. enumerable: true,
  27257. configurable: true
  27258. });
  27259. Gamepad.prototype.update = function () {
  27260. if (this._leftStick) {
  27261. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27262. }
  27263. if (this._rightStick) {
  27264. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27265. }
  27266. };
  27267. return Gamepad;
  27268. })();
  27269. BABYLON.Gamepad = Gamepad;
  27270. var GenericPad = (function (_super) {
  27271. __extends(GenericPad, _super);
  27272. function GenericPad(id, index, gamepad) {
  27273. _super.call(this, id, index, gamepad);
  27274. this.id = id;
  27275. this.index = index;
  27276. this.gamepad = gamepad;
  27277. this._buttons = new Array(gamepad.buttons.length);
  27278. }
  27279. GenericPad.prototype.onbuttondown = function (callback) {
  27280. this._onbuttondown = callback;
  27281. };
  27282. GenericPad.prototype.onbuttonup = function (callback) {
  27283. this._onbuttonup = callback;
  27284. };
  27285. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27286. if (newValue !== currentValue) {
  27287. if (this._onbuttondown && newValue === 1) {
  27288. this._onbuttondown(buttonIndex);
  27289. }
  27290. if (this._onbuttonup && newValue === 0) {
  27291. this._onbuttonup(buttonIndex);
  27292. }
  27293. }
  27294. return newValue;
  27295. };
  27296. GenericPad.prototype.update = function () {
  27297. _super.prototype.update.call(this);
  27298. for (var index = 0; index < this._buttons.length; index++) {
  27299. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27300. }
  27301. };
  27302. return GenericPad;
  27303. })(Gamepad);
  27304. BABYLON.GenericPad = GenericPad;
  27305. (function (Xbox360Button) {
  27306. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27307. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27308. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27309. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27310. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27311. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27312. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27313. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27314. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27315. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27316. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27317. var Xbox360Button = BABYLON.Xbox360Button;
  27318. (function (Xbox360Dpad) {
  27319. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27320. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27321. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27322. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27323. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27324. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27325. var Xbox360Pad = (function (_super) {
  27326. __extends(Xbox360Pad, _super);
  27327. function Xbox360Pad() {
  27328. _super.apply(this, arguments);
  27329. this._leftTrigger = 0;
  27330. this._rightTrigger = 0;
  27331. this._buttonA = 0;
  27332. this._buttonB = 0;
  27333. this._buttonX = 0;
  27334. this._buttonY = 0;
  27335. this._buttonBack = 0;
  27336. this._buttonStart = 0;
  27337. this._buttonLB = 0;
  27338. this._buttonRB = 0;
  27339. this._buttonLeftStick = 0;
  27340. this._buttonRightStick = 0;
  27341. this._dPadUp = 0;
  27342. this._dPadDown = 0;
  27343. this._dPadLeft = 0;
  27344. this._dPadRight = 0;
  27345. }
  27346. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27347. this._onlefttriggerchanged = callback;
  27348. };
  27349. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27350. this._onrighttriggerchanged = callback;
  27351. };
  27352. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27353. get: function () {
  27354. return this._leftTrigger;
  27355. },
  27356. set: function (newValue) {
  27357. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27358. this._onlefttriggerchanged(newValue);
  27359. }
  27360. this._leftTrigger = newValue;
  27361. },
  27362. enumerable: true,
  27363. configurable: true
  27364. });
  27365. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27366. get: function () {
  27367. return this._rightTrigger;
  27368. },
  27369. set: function (newValue) {
  27370. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27371. this._onrighttriggerchanged(newValue);
  27372. }
  27373. this._rightTrigger = newValue;
  27374. },
  27375. enumerable: true,
  27376. configurable: true
  27377. });
  27378. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27379. this._onbuttondown = callback;
  27380. };
  27381. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27382. this._onbuttonup = callback;
  27383. };
  27384. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27385. this._ondpaddown = callback;
  27386. };
  27387. Xbox360Pad.prototype.ondpadup = function (callback) {
  27388. this._ondpadup = callback;
  27389. };
  27390. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27391. if (newValue !== currentValue) {
  27392. if (this._onbuttondown && newValue === 1) {
  27393. this._onbuttondown(buttonType);
  27394. }
  27395. if (this._onbuttonup && newValue === 0) {
  27396. this._onbuttonup(buttonType);
  27397. }
  27398. }
  27399. return newValue;
  27400. };
  27401. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27402. if (newValue !== currentValue) {
  27403. if (this._ondpaddown && newValue === 1) {
  27404. this._ondpaddown(buttonType);
  27405. }
  27406. if (this._ondpadup && newValue === 0) {
  27407. this._ondpadup(buttonType);
  27408. }
  27409. }
  27410. return newValue;
  27411. };
  27412. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27413. get: function () {
  27414. return this._buttonA;
  27415. },
  27416. set: function (value) {
  27417. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  27418. },
  27419. enumerable: true,
  27420. configurable: true
  27421. });
  27422. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27423. get: function () {
  27424. return this._buttonB;
  27425. },
  27426. set: function (value) {
  27427. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  27428. },
  27429. enumerable: true,
  27430. configurable: true
  27431. });
  27432. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27433. get: function () {
  27434. return this._buttonX;
  27435. },
  27436. set: function (value) {
  27437. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  27438. },
  27439. enumerable: true,
  27440. configurable: true
  27441. });
  27442. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27443. get: function () {
  27444. return this._buttonY;
  27445. },
  27446. set: function (value) {
  27447. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  27448. },
  27449. enumerable: true,
  27450. configurable: true
  27451. });
  27452. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27453. get: function () {
  27454. return this._buttonStart;
  27455. },
  27456. set: function (value) {
  27457. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  27458. },
  27459. enumerable: true,
  27460. configurable: true
  27461. });
  27462. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27463. get: function () {
  27464. return this._buttonBack;
  27465. },
  27466. set: function (value) {
  27467. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  27468. },
  27469. enumerable: true,
  27470. configurable: true
  27471. });
  27472. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27473. get: function () {
  27474. return this._buttonLB;
  27475. },
  27476. set: function (value) {
  27477. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  27478. },
  27479. enumerable: true,
  27480. configurable: true
  27481. });
  27482. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27483. get: function () {
  27484. return this._buttonRB;
  27485. },
  27486. set: function (value) {
  27487. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  27488. },
  27489. enumerable: true,
  27490. configurable: true
  27491. });
  27492. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27493. get: function () {
  27494. return this._buttonLeftStick;
  27495. },
  27496. set: function (value) {
  27497. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  27498. },
  27499. enumerable: true,
  27500. configurable: true
  27501. });
  27502. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27503. get: function () {
  27504. return this._buttonRightStick;
  27505. },
  27506. set: function (value) {
  27507. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  27508. },
  27509. enumerable: true,
  27510. configurable: true
  27511. });
  27512. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27513. get: function () {
  27514. return this._dPadUp;
  27515. },
  27516. set: function (value) {
  27517. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  27518. },
  27519. enumerable: true,
  27520. configurable: true
  27521. });
  27522. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27523. get: function () {
  27524. return this._dPadDown;
  27525. },
  27526. set: function (value) {
  27527. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  27528. },
  27529. enumerable: true,
  27530. configurable: true
  27531. });
  27532. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27533. get: function () {
  27534. return this._dPadLeft;
  27535. },
  27536. set: function (value) {
  27537. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  27538. },
  27539. enumerable: true,
  27540. configurable: true
  27541. });
  27542. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27543. get: function () {
  27544. return this._dPadRight;
  27545. },
  27546. set: function (value) {
  27547. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  27548. },
  27549. enumerable: true,
  27550. configurable: true
  27551. });
  27552. Xbox360Pad.prototype.update = function () {
  27553. _super.prototype.update.call(this);
  27554. this.buttonA = this.browserGamepad.buttons[0].value;
  27555. this.buttonB = this.browserGamepad.buttons[1].value;
  27556. this.buttonX = this.browserGamepad.buttons[2].value;
  27557. this.buttonY = this.browserGamepad.buttons[3].value;
  27558. this.buttonLB = this.browserGamepad.buttons[4].value;
  27559. this.buttonRB = this.browserGamepad.buttons[5].value;
  27560. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27561. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27562. this.buttonBack = this.browserGamepad.buttons[8].value;
  27563. this.buttonStart = this.browserGamepad.buttons[9].value;
  27564. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27565. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27566. this.dPadUp = this.browserGamepad.buttons[12].value;
  27567. this.dPadDown = this.browserGamepad.buttons[13].value;
  27568. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27569. this.dPadRight = this.browserGamepad.buttons[15].value;
  27570. };
  27571. return Xbox360Pad;
  27572. })(Gamepad);
  27573. BABYLON.Xbox360Pad = Xbox360Pad;
  27574. })(BABYLON || (BABYLON = {}));
  27575. //# sourceMappingURL=babylon.gamepads.js.map
  27576. var __extends = this.__extends || function (d, b) {
  27577. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27578. function __() { this.constructor = d; }
  27579. __.prototype = b.prototype;
  27580. d.prototype = new __();
  27581. };
  27582. var BABYLON;
  27583. (function (BABYLON) {
  27584. // We're mainly based on the logic defined into the FreeCamera code
  27585. var GamepadCamera = (function (_super) {
  27586. __extends(GamepadCamera, _super);
  27587. function GamepadCamera(name, position, scene) {
  27588. var _this = this;
  27589. _super.call(this, name, position, scene);
  27590. this.angularSensibility = 200;
  27591. this.moveSensibility = 75;
  27592. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  27593. _this._onNewGameConnected(gamepad);
  27594. });
  27595. }
  27596. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27597. // Only the first gamepad can control the camera
  27598. if (gamepad.index === 0) {
  27599. this._gamepad = gamepad;
  27600. }
  27601. };
  27602. GamepadCamera.prototype._checkInputs = function () {
  27603. if (!this._gamepad) {
  27604. return;
  27605. }
  27606. var LSValues = this._gamepad.leftStick;
  27607. var normalizedLX = LSValues.x / this.moveSensibility;
  27608. var normalizedLY = LSValues.y / this.moveSensibility;
  27609. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27610. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27611. var RSValues = this._gamepad.rightStick;
  27612. var normalizedRX = RSValues.x / this.angularSensibility;
  27613. var normalizedRY = RSValues.y / this.angularSensibility;
  27614. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27615. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27616. ;
  27617. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27618. var speed = this._computeLocalCameraSpeed() * 50.0;
  27619. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27620. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27621. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27622. };
  27623. GamepadCamera.prototype.dispose = function () {
  27624. this._gamepads.dispose();
  27625. _super.prototype.dispose.call(this);
  27626. };
  27627. return GamepadCamera;
  27628. })(BABYLON.FreeCamera);
  27629. BABYLON.GamepadCamera = GamepadCamera;
  27630. })(BABYLON || (BABYLON = {}));
  27631. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27632. var __extends = this.__extends || function (d, b) {
  27633. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27634. function __() { this.constructor = d; }
  27635. __.prototype = b.prototype;
  27636. d.prototype = new __();
  27637. };
  27638. var BABYLON;
  27639. (function (BABYLON) {
  27640. var LinesMesh = (function (_super) {
  27641. __extends(LinesMesh, _super);
  27642. function LinesMesh(name, scene, updatable) {
  27643. if (updatable === void 0) { updatable = false; }
  27644. _super.call(this, name, scene);
  27645. this.color = new BABYLON.Color3(1, 1, 1);
  27646. this.alpha = 1;
  27647. this._indices = new Array();
  27648. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27649. attributes: ["position"],
  27650. uniforms: ["worldViewProjection", "color"],
  27651. needAlphaBlending: true
  27652. });
  27653. }
  27654. Object.defineProperty(LinesMesh.prototype, "material", {
  27655. get: function () {
  27656. return this._colorShader;
  27657. },
  27658. enumerable: true,
  27659. configurable: true
  27660. });
  27661. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27662. get: function () {
  27663. return false;
  27664. },
  27665. enumerable: true,
  27666. configurable: true
  27667. });
  27668. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27669. get: function () {
  27670. return false;
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27676. var engine = this.getScene().getEngine();
  27677. var indexToBind = this._geometry.getIndexBuffer();
  27678. // VBOs
  27679. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27680. // Color
  27681. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27682. };
  27683. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27684. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27685. return;
  27686. }
  27687. var engine = this.getScene().getEngine();
  27688. // Draw order
  27689. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27690. };
  27691. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27692. return null;
  27693. };
  27694. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27695. this._colorShader.dispose();
  27696. _super.prototype.dispose.call(this, doNotRecurse);
  27697. };
  27698. return LinesMesh;
  27699. })(BABYLON.Mesh);
  27700. BABYLON.LinesMesh = LinesMesh;
  27701. })(BABYLON || (BABYLON = {}));
  27702. //# sourceMappingURL=babylon.linesMesh.js.map
  27703. var BABYLON;
  27704. (function (BABYLON) {
  27705. var OutlineRenderer = (function () {
  27706. function OutlineRenderer(scene) {
  27707. this._scene = scene;
  27708. }
  27709. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27710. var _this = this;
  27711. if (useOverlay === void 0) { useOverlay = false; }
  27712. var scene = this._scene;
  27713. var engine = this._scene.getEngine();
  27714. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27715. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27716. return;
  27717. }
  27718. var mesh = subMesh.getRenderingMesh();
  27719. var material = subMesh.getMaterial();
  27720. engine.enableEffect(this._effect);
  27721. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27722. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27723. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27724. // Bones
  27725. if (mesh.useBones) {
  27726. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27727. }
  27728. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27729. // Alpha test
  27730. if (material && material.needAlphaTesting()) {
  27731. var alphaTexture = material.getAlphaTestTexture();
  27732. this._effect.setTexture("diffuseSampler", alphaTexture);
  27733. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27734. }
  27735. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  27736. _this._effect.setMatrix("world", world);
  27737. });
  27738. };
  27739. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27740. var defines = [];
  27741. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27742. var mesh = subMesh.getMesh();
  27743. var material = subMesh.getMaterial();
  27744. // Alpha test
  27745. if (material && material.needAlphaTesting()) {
  27746. defines.push("#define ALPHATEST");
  27747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27748. attribs.push(BABYLON.VertexBuffer.UVKind);
  27749. defines.push("#define UV1");
  27750. }
  27751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27752. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27753. defines.push("#define UV2");
  27754. }
  27755. }
  27756. // Bones
  27757. if (mesh.useBones) {
  27758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27760. defines.push("#define BONES");
  27761. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27762. }
  27763. // Instances
  27764. if (useInstances) {
  27765. defines.push("#define INSTANCES");
  27766. attribs.push("world0");
  27767. attribs.push("world1");
  27768. attribs.push("world2");
  27769. attribs.push("world3");
  27770. }
  27771. // Get correct effect
  27772. var join = defines.join("\n");
  27773. if (this._cachedDefines !== join) {
  27774. this._cachedDefines = join;
  27775. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27776. }
  27777. return this._effect.isReady();
  27778. };
  27779. return OutlineRenderer;
  27780. })();
  27781. BABYLON.OutlineRenderer = OutlineRenderer;
  27782. })(BABYLON || (BABYLON = {}));
  27783. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27784. var BABYLON;
  27785. (function (BABYLON) {
  27786. var MeshAssetTask = (function () {
  27787. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27788. this.name = name;
  27789. this.meshesNames = meshesNames;
  27790. this.rootUrl = rootUrl;
  27791. this.sceneFilename = sceneFilename;
  27792. this.isCompleted = false;
  27793. }
  27794. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27795. var _this = this;
  27796. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27797. _this.loadedMeshes = meshes;
  27798. _this.loadedParticleSystems = particleSystems;
  27799. _this.loadedSkeletons = skeletons;
  27800. _this.isCompleted = true;
  27801. if (_this.onSuccess) {
  27802. _this.onSuccess(_this);
  27803. }
  27804. onSuccess();
  27805. }, null, function () {
  27806. if (_this.onError) {
  27807. _this.onError(_this);
  27808. }
  27809. onError();
  27810. });
  27811. };
  27812. return MeshAssetTask;
  27813. })();
  27814. BABYLON.MeshAssetTask = MeshAssetTask;
  27815. var TextFileAssetTask = (function () {
  27816. function TextFileAssetTask(name, url) {
  27817. this.name = name;
  27818. this.url = url;
  27819. this.isCompleted = false;
  27820. }
  27821. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27822. var _this = this;
  27823. BABYLON.Tools.LoadFile(this.url, function (data) {
  27824. _this.text = data;
  27825. _this.isCompleted = true;
  27826. if (_this.onSuccess) {
  27827. _this.onSuccess(_this);
  27828. }
  27829. onSuccess();
  27830. }, null, scene.database, false, function () {
  27831. if (_this.onError) {
  27832. _this.onError(_this);
  27833. }
  27834. onError();
  27835. });
  27836. };
  27837. return TextFileAssetTask;
  27838. })();
  27839. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27840. var BinaryFileAssetTask = (function () {
  27841. function BinaryFileAssetTask(name, url) {
  27842. this.name = name;
  27843. this.url = url;
  27844. this.isCompleted = false;
  27845. }
  27846. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27847. var _this = this;
  27848. BABYLON.Tools.LoadFile(this.url, function (data) {
  27849. _this.data = data;
  27850. _this.isCompleted = true;
  27851. if (_this.onSuccess) {
  27852. _this.onSuccess(_this);
  27853. }
  27854. onSuccess();
  27855. }, null, scene.database, true, function () {
  27856. if (_this.onError) {
  27857. _this.onError(_this);
  27858. }
  27859. onError();
  27860. });
  27861. };
  27862. return BinaryFileAssetTask;
  27863. })();
  27864. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27865. var ImageAssetTask = (function () {
  27866. function ImageAssetTask(name, url) {
  27867. this.name = name;
  27868. this.url = url;
  27869. this.isCompleted = false;
  27870. }
  27871. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27872. var _this = this;
  27873. var img = new Image();
  27874. img.onload = function () {
  27875. _this.image = img;
  27876. _this.isCompleted = true;
  27877. if (_this.onSuccess) {
  27878. _this.onSuccess(_this);
  27879. }
  27880. onSuccess();
  27881. };
  27882. img.onerror = function () {
  27883. if (_this.onError) {
  27884. _this.onError(_this);
  27885. }
  27886. onError();
  27887. };
  27888. img.src = this.url;
  27889. };
  27890. return ImageAssetTask;
  27891. })();
  27892. BABYLON.ImageAssetTask = ImageAssetTask;
  27893. var TextureAssetTask = (function () {
  27894. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27896. this.name = name;
  27897. this.url = url;
  27898. this.noMipmap = noMipmap;
  27899. this.invertY = invertY;
  27900. this.samplingMode = samplingMode;
  27901. this.isCompleted = false;
  27902. }
  27903. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27904. var _this = this;
  27905. var onload = function () {
  27906. _this.isCompleted = true;
  27907. if (_this.onSuccess) {
  27908. _this.onSuccess(_this);
  27909. }
  27910. onSuccess();
  27911. };
  27912. var onerror = function () {
  27913. if (_this.onError) {
  27914. _this.onError(_this);
  27915. }
  27916. onError();
  27917. };
  27918. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27919. };
  27920. return TextureAssetTask;
  27921. })();
  27922. BABYLON.TextureAssetTask = TextureAssetTask;
  27923. var AssetsManager = (function () {
  27924. function AssetsManager(scene) {
  27925. this._tasks = new Array();
  27926. this._waitingTasksCount = 0;
  27927. this.useDefaultLoadingScreen = true;
  27928. this._scene = scene;
  27929. }
  27930. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27931. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27932. this._tasks.push(task);
  27933. return task;
  27934. };
  27935. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27936. var task = new TextFileAssetTask(taskName, url);
  27937. this._tasks.push(task);
  27938. return task;
  27939. };
  27940. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27941. var task = new BinaryFileAssetTask(taskName, url);
  27942. this._tasks.push(task);
  27943. return task;
  27944. };
  27945. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27946. var task = new ImageAssetTask(taskName, url);
  27947. this._tasks.push(task);
  27948. return task;
  27949. };
  27950. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27952. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27953. this._tasks.push(task);
  27954. return task;
  27955. };
  27956. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27957. this._waitingTasksCount--;
  27958. if (this._waitingTasksCount === 0) {
  27959. if (this.onFinish) {
  27960. this.onFinish(this._tasks);
  27961. }
  27962. this._scene.getEngine().hideLoadingUI();
  27963. }
  27964. };
  27965. AssetsManager.prototype._runTask = function (task) {
  27966. var _this = this;
  27967. task.run(this._scene, function () {
  27968. if (_this.onTaskSuccess) {
  27969. _this.onTaskSuccess(task);
  27970. }
  27971. _this._decreaseWaitingTasksCount();
  27972. }, function () {
  27973. if (_this.onTaskError) {
  27974. _this.onTaskError(task);
  27975. }
  27976. _this._decreaseWaitingTasksCount();
  27977. });
  27978. };
  27979. AssetsManager.prototype.reset = function () {
  27980. this._tasks = new Array();
  27981. return this;
  27982. };
  27983. AssetsManager.prototype.load = function () {
  27984. this._waitingTasksCount = this._tasks.length;
  27985. if (this._waitingTasksCount === 0) {
  27986. if (this.onFinish) {
  27987. this.onFinish(this._tasks);
  27988. }
  27989. return this;
  27990. }
  27991. if (this.useDefaultLoadingScreen) {
  27992. this._scene.getEngine().displayLoadingUI();
  27993. }
  27994. for (var index = 0; index < this._tasks.length; index++) {
  27995. var task = this._tasks[index];
  27996. this._runTask(task);
  27997. }
  27998. return this;
  27999. };
  28000. return AssetsManager;
  28001. })();
  28002. BABYLON.AssetsManager = AssetsManager;
  28003. })(BABYLON || (BABYLON = {}));
  28004. //# sourceMappingURL=babylon.assetsManager.js.map
  28005. var __extends = this.__extends || function (d, b) {
  28006. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28007. function __() { this.constructor = d; }
  28008. __.prototype = b.prototype;
  28009. d.prototype = new __();
  28010. };
  28011. var BABYLON;
  28012. (function (BABYLON) {
  28013. var VRDeviceOrientationCamera = (function (_super) {
  28014. __extends(VRDeviceOrientationCamera, _super);
  28015. function VRDeviceOrientationCamera(name, position, scene) {
  28016. _super.call(this, name, position, scene);
  28017. this._alpha = 0;
  28018. this._beta = 0;
  28019. this._gamma = 0;
  28020. }
  28021. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  28022. this._alpha = +evt.alpha | 0;
  28023. this._beta = +evt.beta | 0;
  28024. this._gamma = +evt.gamma | 0;
  28025. if (this._gamma < 0) {
  28026. this._gamma = 90 + this._gamma;
  28027. }
  28028. else {
  28029. // Incline it in the correct angle.
  28030. this._gamma = 270 - this._gamma;
  28031. }
  28032. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28033. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28034. this.rotation.z = this._beta / 180.0 * Math.PI;
  28035. };
  28036. return VRDeviceOrientationCamera;
  28037. })(BABYLON.OculusCamera);
  28038. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  28039. })(BABYLON || (BABYLON = {}));
  28040. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28041. var __extends = this.__extends || function (d, b) {
  28042. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28043. function __() { this.constructor = d; }
  28044. __.prototype = b.prototype;
  28045. d.prototype = new __();
  28046. };
  28047. var BABYLON;
  28048. (function (BABYLON) {
  28049. var WebVRCamera = (function (_super) {
  28050. __extends(WebVRCamera, _super);
  28051. function WebVRCamera(name, position, scene) {
  28052. _super.call(this, name, position, scene);
  28053. this._hmdDevice = null;
  28054. this._sensorDevice = null;
  28055. this._cacheState = null;
  28056. this._cacheQuaternion = new BABYLON.Quaternion();
  28057. this._cacheRotation = BABYLON.Vector3.Zero();
  28058. this._vrEnabled = false;
  28059. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28060. }
  28061. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  28062. var size = devices.length;
  28063. var i = 0;
  28064. // Reset devices.
  28065. this._sensorDevice = null;
  28066. this._hmdDevice = null;
  28067. while (i < size && this._hmdDevice === null) {
  28068. if (devices[i] instanceof HMDVRDevice) {
  28069. this._hmdDevice = devices[i];
  28070. }
  28071. i++;
  28072. }
  28073. i = 0;
  28074. while (i < size && this._sensorDevice === null) {
  28075. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28076. this._sensorDevice = devices[i];
  28077. }
  28078. i++;
  28079. }
  28080. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28081. };
  28082. WebVRCamera.prototype._update = function () {
  28083. if (this._vrEnabled) {
  28084. this._cacheState = this._sensorDevice.getState();
  28085. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28086. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28087. this.rotation.x = -this._cacheRotation.z;
  28088. this.rotation.y = -this._cacheRotation.y;
  28089. this.rotation.z = this._cacheRotation.x;
  28090. }
  28091. _super.prototype._update.call(this);
  28092. };
  28093. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  28094. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28095. if (navigator.getVRDevices) {
  28096. navigator.getVRDevices().then(this._getWebVRDevices);
  28097. }
  28098. else if (navigator.mozGetVRDevices) {
  28099. navigator.mozGetVRDevices(this._getWebVRDevices);
  28100. }
  28101. };
  28102. WebVRCamera.prototype.detachControl = function (element) {
  28103. _super.prototype.detachControl.call(this, element);
  28104. this._vrEnabled = false;
  28105. };
  28106. return WebVRCamera;
  28107. })(BABYLON.OculusCamera);
  28108. BABYLON.WebVRCamera = WebVRCamera;
  28109. })(BABYLON || (BABYLON = {}));
  28110. //# sourceMappingURL=babylon.webVRCamera.js.map
  28111. var __extends = this.__extends || function (d, b) {
  28112. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28113. function __() { this.constructor = d; }
  28114. __.prototype = b.prototype;
  28115. d.prototype = new __();
  28116. };
  28117. var BABYLON;
  28118. (function (BABYLON) {
  28119. // Standard optimizations
  28120. var SceneOptimization = (function () {
  28121. function SceneOptimization(priority) {
  28122. if (priority === void 0) { priority = 0; }
  28123. this.priority = priority;
  28124. this.apply = function (scene) {
  28125. return true; // Return true if everything that can be done was applied
  28126. };
  28127. }
  28128. return SceneOptimization;
  28129. })();
  28130. BABYLON.SceneOptimization = SceneOptimization;
  28131. var TextureOptimization = (function (_super) {
  28132. __extends(TextureOptimization, _super);
  28133. function TextureOptimization(priority, maximumSize) {
  28134. var _this = this;
  28135. if (priority === void 0) { priority = 0; }
  28136. if (maximumSize === void 0) { maximumSize = 1024; }
  28137. _super.call(this, priority);
  28138. this.priority = priority;
  28139. this.maximumSize = maximumSize;
  28140. this.apply = function (scene) {
  28141. var allDone = true;
  28142. for (var index = 0; index < scene.textures.length; index++) {
  28143. var texture = scene.textures[index];
  28144. if (!texture.canRescale) {
  28145. continue;
  28146. }
  28147. var currentSize = texture.getSize();
  28148. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28149. if (maxDimension > _this.maximumSize) {
  28150. texture.scale(0.5);
  28151. allDone = false;
  28152. }
  28153. }
  28154. return allDone;
  28155. };
  28156. }
  28157. return TextureOptimization;
  28158. })(SceneOptimization);
  28159. BABYLON.TextureOptimization = TextureOptimization;
  28160. var HardwareScalingOptimization = (function (_super) {
  28161. __extends(HardwareScalingOptimization, _super);
  28162. function HardwareScalingOptimization(priority, maximumScale) {
  28163. var _this = this;
  28164. if (priority === void 0) { priority = 0; }
  28165. if (maximumScale === void 0) { maximumScale = 2; }
  28166. _super.call(this, priority);
  28167. this.priority = priority;
  28168. this.maximumScale = maximumScale;
  28169. this._currentScale = 1;
  28170. this.apply = function (scene) {
  28171. _this._currentScale++;
  28172. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28173. return _this._currentScale >= _this.maximumScale;
  28174. };
  28175. }
  28176. return HardwareScalingOptimization;
  28177. })(SceneOptimization);
  28178. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28179. var ShadowsOptimization = (function (_super) {
  28180. __extends(ShadowsOptimization, _super);
  28181. function ShadowsOptimization() {
  28182. _super.apply(this, arguments);
  28183. this.apply = function (scene) {
  28184. scene.shadowsEnabled = false;
  28185. return true;
  28186. };
  28187. }
  28188. return ShadowsOptimization;
  28189. })(SceneOptimization);
  28190. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28191. var PostProcessesOptimization = (function (_super) {
  28192. __extends(PostProcessesOptimization, _super);
  28193. function PostProcessesOptimization() {
  28194. _super.apply(this, arguments);
  28195. this.apply = function (scene) {
  28196. scene.postProcessesEnabled = false;
  28197. return true;
  28198. };
  28199. }
  28200. return PostProcessesOptimization;
  28201. })(SceneOptimization);
  28202. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28203. var LensFlaresOptimization = (function (_super) {
  28204. __extends(LensFlaresOptimization, _super);
  28205. function LensFlaresOptimization() {
  28206. _super.apply(this, arguments);
  28207. this.apply = function (scene) {
  28208. scene.lensFlaresEnabled = false;
  28209. return true;
  28210. };
  28211. }
  28212. return LensFlaresOptimization;
  28213. })(SceneOptimization);
  28214. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28215. var ParticlesOptimization = (function (_super) {
  28216. __extends(ParticlesOptimization, _super);
  28217. function ParticlesOptimization() {
  28218. _super.apply(this, arguments);
  28219. this.apply = function (scene) {
  28220. scene.particlesEnabled = false;
  28221. return true;
  28222. };
  28223. }
  28224. return ParticlesOptimization;
  28225. })(SceneOptimization);
  28226. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28227. var RenderTargetsOptimization = (function (_super) {
  28228. __extends(RenderTargetsOptimization, _super);
  28229. function RenderTargetsOptimization() {
  28230. _super.apply(this, arguments);
  28231. this.apply = function (scene) {
  28232. scene.renderTargetsEnabled = false;
  28233. return true;
  28234. };
  28235. }
  28236. return RenderTargetsOptimization;
  28237. })(SceneOptimization);
  28238. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28239. var MergeMeshesOptimization = (function (_super) {
  28240. __extends(MergeMeshesOptimization, _super);
  28241. function MergeMeshesOptimization() {
  28242. var _this = this;
  28243. _super.apply(this, arguments);
  28244. this._canBeMerged = function (abstractMesh) {
  28245. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28246. return false;
  28247. }
  28248. var mesh = abstractMesh;
  28249. if (!mesh.isVisible || !mesh.isEnabled()) {
  28250. return false;
  28251. }
  28252. if (mesh.instances.length > 0) {
  28253. return false;
  28254. }
  28255. if (mesh.skeleton || mesh.hasLODLevels) {
  28256. return false;
  28257. }
  28258. return true;
  28259. };
  28260. this.apply = function (scene) {
  28261. var globalPool = scene.meshes.slice(0);
  28262. var globalLength = globalPool.length;
  28263. for (var index = 0; index < globalLength; index++) {
  28264. var currentPool = new Array();
  28265. var current = globalPool[index];
  28266. // Checks
  28267. if (!_this._canBeMerged(current)) {
  28268. continue;
  28269. }
  28270. currentPool.push(current);
  28271. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28272. var otherMesh = globalPool[subIndex];
  28273. if (!_this._canBeMerged(otherMesh)) {
  28274. continue;
  28275. }
  28276. if (otherMesh.material !== current.material) {
  28277. continue;
  28278. }
  28279. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28280. continue;
  28281. }
  28282. currentPool.push(otherMesh);
  28283. globalLength--;
  28284. globalPool.splice(subIndex, 1);
  28285. subIndex--;
  28286. }
  28287. if (currentPool.length < 2) {
  28288. continue;
  28289. }
  28290. // Merge meshes
  28291. BABYLON.Mesh.MergeMeshes(currentPool);
  28292. }
  28293. return true;
  28294. };
  28295. }
  28296. return MergeMeshesOptimization;
  28297. })(SceneOptimization);
  28298. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28299. // Options
  28300. var SceneOptimizerOptions = (function () {
  28301. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28302. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28303. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28304. this.targetFrameRate = targetFrameRate;
  28305. this.trackerDuration = trackerDuration;
  28306. this.optimizations = new Array();
  28307. }
  28308. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28309. var result = new SceneOptimizerOptions(targetFrameRate);
  28310. var priority = 0;
  28311. result.optimizations.push(new MergeMeshesOptimization(priority));
  28312. result.optimizations.push(new ShadowsOptimization(priority));
  28313. result.optimizations.push(new LensFlaresOptimization(priority));
  28314. // Next priority
  28315. priority++;
  28316. result.optimizations.push(new PostProcessesOptimization(priority));
  28317. result.optimizations.push(new ParticlesOptimization(priority));
  28318. // Next priority
  28319. priority++;
  28320. result.optimizations.push(new TextureOptimization(priority, 1024));
  28321. return result;
  28322. };
  28323. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28324. var result = new SceneOptimizerOptions(targetFrameRate);
  28325. var priority = 0;
  28326. result.optimizations.push(new MergeMeshesOptimization(priority));
  28327. result.optimizations.push(new ShadowsOptimization(priority));
  28328. result.optimizations.push(new LensFlaresOptimization(priority));
  28329. // Next priority
  28330. priority++;
  28331. result.optimizations.push(new PostProcessesOptimization(priority));
  28332. result.optimizations.push(new ParticlesOptimization(priority));
  28333. // Next priority
  28334. priority++;
  28335. result.optimizations.push(new TextureOptimization(priority, 512));
  28336. // Next priority
  28337. priority++;
  28338. result.optimizations.push(new RenderTargetsOptimization(priority));
  28339. // Next priority
  28340. priority++;
  28341. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28342. return result;
  28343. };
  28344. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28345. var result = new SceneOptimizerOptions(targetFrameRate);
  28346. var priority = 0;
  28347. result.optimizations.push(new MergeMeshesOptimization(priority));
  28348. result.optimizations.push(new ShadowsOptimization(priority));
  28349. result.optimizations.push(new LensFlaresOptimization(priority));
  28350. // Next priority
  28351. priority++;
  28352. result.optimizations.push(new PostProcessesOptimization(priority));
  28353. result.optimizations.push(new ParticlesOptimization(priority));
  28354. // Next priority
  28355. priority++;
  28356. result.optimizations.push(new TextureOptimization(priority, 256));
  28357. // Next priority
  28358. priority++;
  28359. result.optimizations.push(new RenderTargetsOptimization(priority));
  28360. // Next priority
  28361. priority++;
  28362. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28363. return result;
  28364. };
  28365. return SceneOptimizerOptions;
  28366. })();
  28367. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28368. // Scene optimizer tool
  28369. var SceneOptimizer = (function () {
  28370. function SceneOptimizer() {
  28371. }
  28372. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28373. // TODO: add an epsilon
  28374. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28375. if (onSuccess) {
  28376. onSuccess();
  28377. }
  28378. return;
  28379. }
  28380. // Apply current level of optimizations
  28381. var allDone = true;
  28382. var noOptimizationApplied = true;
  28383. for (var index = 0; index < options.optimizations.length; index++) {
  28384. var optimization = options.optimizations[index];
  28385. if (optimization.priority === currentPriorityLevel) {
  28386. noOptimizationApplied = false;
  28387. allDone = allDone && optimization.apply(scene);
  28388. }
  28389. }
  28390. // If no optimization was applied, this is a failure :(
  28391. if (noOptimizationApplied) {
  28392. if (onFailure) {
  28393. onFailure();
  28394. }
  28395. return;
  28396. }
  28397. // If all optimizations were done, move to next level
  28398. if (allDone) {
  28399. currentPriorityLevel++;
  28400. }
  28401. // Let's the system running for a specific amount of time before checking FPS
  28402. scene.executeWhenReady(function () {
  28403. setTimeout(function () {
  28404. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28405. }, options.trackerDuration);
  28406. });
  28407. };
  28408. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28409. if (!options) {
  28410. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28411. }
  28412. // Let's the system running for a specific amount of time before checking FPS
  28413. scene.executeWhenReady(function () {
  28414. setTimeout(function () {
  28415. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28416. }, options.trackerDuration);
  28417. });
  28418. };
  28419. return SceneOptimizer;
  28420. })();
  28421. BABYLON.SceneOptimizer = SceneOptimizer;
  28422. })(BABYLON || (BABYLON = {}));
  28423. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28424. var BABYLON;
  28425. (function (BABYLON) {
  28426. var Internals;
  28427. (function (Internals) {
  28428. var MeshLODLevel = (function () {
  28429. function MeshLODLevel(distance, mesh) {
  28430. this.distance = distance;
  28431. this.mesh = mesh;
  28432. }
  28433. return MeshLODLevel;
  28434. })();
  28435. Internals.MeshLODLevel = MeshLODLevel;
  28436. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28437. })(BABYLON || (BABYLON = {}));
  28438. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28439. var BABYLON;
  28440. (function (BABYLON) {
  28441. var AudioEngine = (function () {
  28442. function AudioEngine() {
  28443. this._audioContext = null;
  28444. this._audioContextInitialized = false;
  28445. this.canUseWebAudio = false;
  28446. this.WarnedWebAudioUnsupported = false;
  28447. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28448. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28449. this.canUseWebAudio = true;
  28450. }
  28451. }
  28452. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28453. get: function () {
  28454. if (!this._audioContextInitialized) {
  28455. this._initializeAudioContext();
  28456. }
  28457. return this._audioContext;
  28458. },
  28459. enumerable: true,
  28460. configurable: true
  28461. });
  28462. AudioEngine.prototype._initializeAudioContext = function () {
  28463. try {
  28464. if (this.canUseWebAudio) {
  28465. this._audioContext = new AudioContext();
  28466. // create a global volume gain node
  28467. this.masterGain = this._audioContext.createGain();
  28468. this.masterGain.gain.value = 1;
  28469. this.masterGain.connect(this._audioContext.destination);
  28470. this._audioContextInitialized = true;
  28471. }
  28472. }
  28473. catch (e) {
  28474. this.canUseWebAudio = false;
  28475. BABYLON.Tools.Error("Web Audio: " + e.message);
  28476. }
  28477. };
  28478. AudioEngine.prototype.dispose = function () {
  28479. if (this.canUseWebAudio && this._audioContextInitialized) {
  28480. if (this._connectedAnalyser) {
  28481. this._connectedAnalyser.stopDebugCanvas();
  28482. this._connectedAnalyser.dispose();
  28483. this.masterGain.disconnect();
  28484. this.masterGain.connect(this._audioContext.destination);
  28485. this._connectedAnalyser = null;
  28486. }
  28487. this.masterGain.gain.value = 1;
  28488. }
  28489. this.WarnedWebAudioUnsupported = false;
  28490. };
  28491. AudioEngine.prototype.getGlobalVolume = function () {
  28492. if (this.canUseWebAudio && this._audioContextInitialized) {
  28493. return this.masterGain.gain.value;
  28494. }
  28495. else {
  28496. return -1;
  28497. }
  28498. };
  28499. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28500. if (this.canUseWebAudio && this._audioContextInitialized) {
  28501. this.masterGain.gain.value = newVolume;
  28502. }
  28503. };
  28504. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28505. if (this._connectedAnalyser) {
  28506. this._connectedAnalyser.stopDebugCanvas();
  28507. }
  28508. if (this.canUseWebAudio && this._audioContextInitialized) {
  28509. this._connectedAnalyser = analyser;
  28510. this.masterGain.disconnect();
  28511. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28512. }
  28513. };
  28514. return AudioEngine;
  28515. })();
  28516. BABYLON.AudioEngine = AudioEngine;
  28517. })(BABYLON || (BABYLON = {}));
  28518. //# sourceMappingURL=babylon.audioEngine.js.map
  28519. var BABYLON;
  28520. (function (BABYLON) {
  28521. var Sound = (function () {
  28522. /**
  28523. * Create a sound and attach it to a scene
  28524. * @param name Name of your sound
  28525. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28526. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28527. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28528. */
  28529. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28530. var _this = this;
  28531. this.autoplay = false;
  28532. this.loop = false;
  28533. this.useCustomAttenuation = false;
  28534. this.spatialSound = false;
  28535. this.refDistance = 1;
  28536. this.rolloffFactor = 1;
  28537. this.maxDistance = 100;
  28538. this.distanceModel = "linear";
  28539. this._panningModel = "equalpower";
  28540. this._playbackRate = 1;
  28541. this._startTime = 0;
  28542. this._startOffset = 0;
  28543. this._position = BABYLON.Vector3.Zero();
  28544. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28545. this._volume = 1;
  28546. this._isLoaded = false;
  28547. this._isReadyToPlay = false;
  28548. this.isPlaying = false;
  28549. this.isPaused = false;
  28550. this._isDirectional = false;
  28551. // Used if you'd like to create a directional sound.
  28552. // If not set, the sound will be omnidirectional
  28553. this._coneInnerAngle = 360;
  28554. this._coneOuterAngle = 360;
  28555. this._coneOuterGain = 0;
  28556. this.name = name;
  28557. this._scene = scene;
  28558. this._readyToPlayCallback = readyToPlayCallback;
  28559. // Default custom attenuation function is a linear attenuation
  28560. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28561. if (currentDistance < maxDistance) {
  28562. return currentVolume * (1 - currentDistance / maxDistance);
  28563. }
  28564. else {
  28565. return 0;
  28566. }
  28567. };
  28568. if (options) {
  28569. this.autoplay = options.autoplay || false;
  28570. this.loop = options.loop || false;
  28571. // if volume === 0, we need another way to check this option
  28572. if (options.volume !== undefined) {
  28573. this._volume = options.volume;
  28574. }
  28575. this.spatialSound = options.spatialSound || false;
  28576. this.maxDistance = options.maxDistance || 100;
  28577. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28578. this.rolloffFactor = options.rolloffFactor || 1;
  28579. this.refDistance = options.refDistance || 1;
  28580. this.distanceModel = options.distanceModel || "linear";
  28581. this._playbackRate = options.playbackRate || 1;
  28582. }
  28583. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28584. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28585. this._soundGain.gain.value = this._volume;
  28586. this._inputAudioNode = this._soundGain;
  28587. this._ouputAudioNode = this._soundGain;
  28588. if (this.spatialSound) {
  28589. this._createSpatialParameters();
  28590. }
  28591. this._scene.mainSoundTrack.AddSound(this);
  28592. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28593. if (urlOrArrayBuffer) {
  28594. // If it's an URL
  28595. if (typeof (urlOrArrayBuffer) === "string") {
  28596. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28597. _this._soundLoaded(data);
  28598. }, null, null, true);
  28599. }
  28600. else {
  28601. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28602. this._soundLoaded(urlOrArrayBuffer);
  28603. }
  28604. else {
  28605. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28606. }
  28607. }
  28608. }
  28609. }
  28610. else {
  28611. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28612. this._scene.mainSoundTrack.AddSound(this);
  28613. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28614. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28615. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28616. }
  28617. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28618. if (this._readyToPlayCallback) {
  28619. window.setTimeout(function () {
  28620. _this._readyToPlayCallback();
  28621. }, 1000);
  28622. }
  28623. }
  28624. }
  28625. Sound.prototype.dispose = function () {
  28626. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28627. if (this.isPlaying) {
  28628. this.stop();
  28629. }
  28630. this._isReadyToPlay = false;
  28631. if (this.soundTrackId === -1) {
  28632. this._scene.mainSoundTrack.RemoveSound(this);
  28633. }
  28634. else {
  28635. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28636. }
  28637. if (this._soundGain) {
  28638. this._soundGain.disconnect();
  28639. this._soundGain = null;
  28640. }
  28641. if (this._soundPanner) {
  28642. this._soundPanner.disconnect();
  28643. this._soundPanner = null;
  28644. }
  28645. if (this._soundSource) {
  28646. this._soundSource.disconnect();
  28647. this._soundSource = null;
  28648. }
  28649. this._audioBuffer = null;
  28650. if (this._connectedMesh) {
  28651. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28652. this._connectedMesh = null;
  28653. }
  28654. }
  28655. };
  28656. Sound.prototype._soundLoaded = function (audioData) {
  28657. var _this = this;
  28658. this._isLoaded = true;
  28659. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28660. _this._audioBuffer = buffer;
  28661. _this._isReadyToPlay = true;
  28662. if (_this.autoplay) {
  28663. _this.play();
  28664. }
  28665. if (_this._readyToPlayCallback) {
  28666. _this._readyToPlayCallback();
  28667. }
  28668. }, function (error) {
  28669. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28670. });
  28671. };
  28672. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28674. this._audioBuffer = audioBuffer;
  28675. this._isReadyToPlay = true;
  28676. }
  28677. };
  28678. Sound.prototype.updateOptions = function (options) {
  28679. if (options) {
  28680. this.loop = options.loop || this.loop;
  28681. this.maxDistance = options.maxDistance || this.maxDistance;
  28682. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28683. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28684. this.refDistance = options.refDistance || this.refDistance;
  28685. this.distanceModel = options.distanceModel || this.distanceModel;
  28686. this._playbackRate = options.playbackRate || this._playbackRate;
  28687. }
  28688. };
  28689. Sound.prototype._createSpatialParameters = function () {
  28690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28691. if (this._scene.headphone) {
  28692. this._panningModel = "HRTF";
  28693. }
  28694. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28695. if (this.useCustomAttenuation) {
  28696. // Tricks to disable in a way embedded Web Audio attenuation
  28697. this._soundPanner.distanceModel = "linear";
  28698. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28699. this._soundPanner.refDistance = 1;
  28700. this._soundPanner.rolloffFactor = 1;
  28701. this._soundPanner.panningModel = this._panningModel;
  28702. }
  28703. else {
  28704. this._soundPanner.distanceModel = this.distanceModel;
  28705. this._soundPanner.maxDistance = this.maxDistance;
  28706. this._soundPanner.refDistance = this.refDistance;
  28707. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28708. this._soundPanner.panningModel = this._panningModel;
  28709. }
  28710. this._soundPanner.connect(this._ouputAudioNode);
  28711. this._inputAudioNode = this._soundPanner;
  28712. }
  28713. };
  28714. Sound.prototype.switchPanningModelToHRTF = function () {
  28715. this._panningModel = "HRTF";
  28716. this._switchPanningModel();
  28717. };
  28718. Sound.prototype.switchPanningModelToEqualPower = function () {
  28719. this._panningModel = "equalpower";
  28720. this._switchPanningModel();
  28721. };
  28722. Sound.prototype._switchPanningModel = function () {
  28723. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28724. this._soundPanner.panningModel = this._panningModel;
  28725. }
  28726. };
  28727. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28728. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28729. this._ouputAudioNode.disconnect();
  28730. this._ouputAudioNode.connect(soundTrackAudioNode);
  28731. }
  28732. };
  28733. /**
  28734. * Transform this sound into a directional source
  28735. * @param coneInnerAngle Size of the inner cone in degree
  28736. * @param coneOuterAngle Size of the outer cone in degree
  28737. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28738. */
  28739. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28740. if (coneOuterAngle < coneInnerAngle) {
  28741. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28742. return;
  28743. }
  28744. this._coneInnerAngle = coneInnerAngle;
  28745. this._coneOuterAngle = coneOuterAngle;
  28746. this._coneOuterGain = coneOuterGain;
  28747. this._isDirectional = true;
  28748. if (this.isPlaying && this.loop) {
  28749. this.stop();
  28750. this.play();
  28751. }
  28752. };
  28753. Sound.prototype.setPosition = function (newPosition) {
  28754. this._position = newPosition;
  28755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28756. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28757. }
  28758. };
  28759. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28760. this._localDirection = newLocalDirection;
  28761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28762. this._updateDirection();
  28763. }
  28764. };
  28765. Sound.prototype._updateDirection = function () {
  28766. var mat = this._connectedMesh.getWorldMatrix();
  28767. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28768. direction.normalize();
  28769. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28770. };
  28771. Sound.prototype.updateDistanceFromListener = function () {
  28772. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28773. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28774. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28775. }
  28776. };
  28777. Sound.prototype.setAttenuationFunction = function (callback) {
  28778. this._customAttenuationFunction = callback;
  28779. };
  28780. /**
  28781. * Play the sound
  28782. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28783. */
  28784. Sound.prototype.play = function (time) {
  28785. var _this = this;
  28786. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28787. try {
  28788. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28789. if (!this._soundSource) {
  28790. if (this.spatialSound) {
  28791. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28792. if (this._isDirectional) {
  28793. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28794. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28795. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28796. if (this._connectedMesh) {
  28797. this._updateDirection();
  28798. }
  28799. else {
  28800. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28801. }
  28802. }
  28803. }
  28804. }
  28805. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28806. this._soundSource.buffer = this._audioBuffer;
  28807. this._soundSource.connect(this._inputAudioNode);
  28808. this._soundSource.loop = this.loop;
  28809. this._soundSource.playbackRate.value = this._playbackRate;
  28810. this._startTime = startTime;
  28811. this._soundSource.onended = function () {
  28812. _this._onended();
  28813. };
  28814. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28815. this.isPlaying = true;
  28816. this.isPaused = false;
  28817. }
  28818. catch (ex) {
  28819. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28820. }
  28821. }
  28822. };
  28823. Sound.prototype._onended = function () {
  28824. this.isPlaying = false;
  28825. if (this.onended) {
  28826. this.onended();
  28827. }
  28828. };
  28829. /**
  28830. * Stop the sound
  28831. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28832. */
  28833. Sound.prototype.stop = function (time) {
  28834. if (this.isPlaying) {
  28835. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28836. this._soundSource.stop(stopTime);
  28837. this.isPlaying = false;
  28838. }
  28839. };
  28840. Sound.prototype.pause = function () {
  28841. if (this.isPlaying) {
  28842. this.stop(0);
  28843. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28844. this.isPaused = true;
  28845. }
  28846. };
  28847. Sound.prototype.setVolume = function (newVolume, time) {
  28848. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28849. if (time) {
  28850. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28851. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28852. }
  28853. else {
  28854. this._soundGain.gain.value = newVolume;
  28855. }
  28856. }
  28857. this._volume = newVolume;
  28858. };
  28859. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28860. this._playbackRate = newPlaybackRate;
  28861. if (this.isPlaying) {
  28862. this._soundSource.playbackRate.value = this._playbackRate;
  28863. }
  28864. };
  28865. Sound.prototype.getVolume = function () {
  28866. return this._volume;
  28867. };
  28868. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28869. var _this = this;
  28870. this._connectedMesh = meshToConnectTo;
  28871. if (!this.spatialSound) {
  28872. this._createSpatialParameters();
  28873. this.spatialSound = true;
  28874. if (this.isPlaying && this.loop) {
  28875. this.stop();
  28876. this.play();
  28877. }
  28878. }
  28879. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28880. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28881. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28882. };
  28883. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28884. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  28885. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  28886. this._updateDirection();
  28887. }
  28888. };
  28889. return Sound;
  28890. })();
  28891. BABYLON.Sound = Sound;
  28892. })(BABYLON || (BABYLON = {}));
  28893. //# sourceMappingURL=babylon.sound.js.map
  28894. var BABYLON;
  28895. (function (BABYLON) {
  28896. var SoundTrack = (function () {
  28897. function SoundTrack(scene, options) {
  28898. this.id = -1;
  28899. this._isMainTrack = false;
  28900. this._scene = scene;
  28901. this._audioEngine = BABYLON.Engine.audioEngine;
  28902. this.soundCollection = new Array();
  28903. if (this._audioEngine.canUseWebAudio) {
  28904. this._trackGain = this._audioEngine.audioContext.createGain();
  28905. this._trackGain.connect(this._audioEngine.masterGain);
  28906. if (options) {
  28907. if (options.volume) {
  28908. this._trackGain.gain.value = options.volume;
  28909. }
  28910. if (options.mainTrack) {
  28911. this._isMainTrack = options.mainTrack;
  28912. }
  28913. }
  28914. }
  28915. if (!this._isMainTrack) {
  28916. this._scene.soundTracks.push(this);
  28917. this.id = this._scene.soundTracks.length - 1;
  28918. }
  28919. }
  28920. SoundTrack.prototype.dispose = function () {
  28921. if (this._audioEngine.canUseWebAudio) {
  28922. if (this._connectedAnalyser) {
  28923. this._connectedAnalyser.stopDebugCanvas();
  28924. }
  28925. while (this.soundCollection.length) {
  28926. this.soundCollection[0].dispose();
  28927. }
  28928. this._trackGain.disconnect();
  28929. this._trackGain = null;
  28930. }
  28931. };
  28932. SoundTrack.prototype.AddSound = function (sound) {
  28933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28934. sound.connectToSoundTrackAudioNode(this._trackGain);
  28935. }
  28936. if (sound.soundTrackId) {
  28937. if (sound.soundTrackId === -1) {
  28938. this._scene.mainSoundTrack.RemoveSound(sound);
  28939. }
  28940. else {
  28941. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28942. }
  28943. }
  28944. this.soundCollection.push(sound);
  28945. sound.soundTrackId = this.id;
  28946. };
  28947. SoundTrack.prototype.RemoveSound = function (sound) {
  28948. var index = this.soundCollection.indexOf(sound);
  28949. if (index !== -1) {
  28950. this.soundCollection.splice(index, 1);
  28951. }
  28952. };
  28953. SoundTrack.prototype.setVolume = function (newVolume) {
  28954. if (this._audioEngine.canUseWebAudio) {
  28955. this._trackGain.gain.value = newVolume;
  28956. }
  28957. };
  28958. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28960. for (var i = 0; i < this.soundCollection.length; i++) {
  28961. this.soundCollection[i].switchPanningModelToHRTF();
  28962. }
  28963. }
  28964. };
  28965. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28967. for (var i = 0; i < this.soundCollection.length; i++) {
  28968. this.soundCollection[i].switchPanningModelToEqualPower();
  28969. }
  28970. }
  28971. };
  28972. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28973. if (this._connectedAnalyser) {
  28974. this._connectedAnalyser.stopDebugCanvas();
  28975. }
  28976. this._connectedAnalyser = analyser;
  28977. if (this._audioEngine.canUseWebAudio) {
  28978. this._trackGain.disconnect();
  28979. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28980. }
  28981. };
  28982. return SoundTrack;
  28983. })();
  28984. BABYLON.SoundTrack = SoundTrack;
  28985. })(BABYLON || (BABYLON = {}));
  28986. //# sourceMappingURL=babylon.soundtrack.js.map
  28987. var BABYLON;
  28988. (function (BABYLON) {
  28989. var DebugLayer = (function () {
  28990. function DebugLayer(scene) {
  28991. var _this = this;
  28992. this._transformationMatrix = BABYLON.Matrix.Identity();
  28993. this._enabled = false;
  28994. this._labelsEnabled = false;
  28995. this._displayStatistics = true;
  28996. this._displayTree = false;
  28997. this._displayLogs = false;
  28998. this._identityMatrix = BABYLON.Matrix.Identity();
  28999. this.axisRatio = 0.02;
  29000. this.accentColor = "orange";
  29001. this._scene = scene;
  29002. this._syncPositions = function () {
  29003. var engine = _this._scene.getEngine();
  29004. var canvasRect = engine.getRenderingCanvasClientRect();
  29005. if (_this._showUI) {
  29006. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29007. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29008. _this._statsDiv.style.width = "400px";
  29009. _this._statsDiv.style.height = "auto";
  29010. _this._statsSubsetDiv.style.maxHeight = "240px";
  29011. _this._optionsDiv.style.left = "0px";
  29012. _this._optionsDiv.style.top = "10px";
  29013. _this._optionsDiv.style.width = "200px";
  29014. _this._optionsDiv.style.height = "auto";
  29015. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29016. _this._logDiv.style.left = "0px";
  29017. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29018. _this._logDiv.style.width = "600px";
  29019. _this._logDiv.style.height = "160px";
  29020. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29021. _this._treeDiv.style.top = "10px";
  29022. _this._treeDiv.style.width = "300px";
  29023. _this._treeDiv.style.height = "auto";
  29024. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29025. }
  29026. _this._globalDiv.style.left = canvasRect.left + "px";
  29027. _this._globalDiv.style.top = canvasRect.top + "px";
  29028. _this._drawingCanvas.style.left = "0px";
  29029. _this._drawingCanvas.style.top = "0px";
  29030. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29031. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29032. var devicePixelRatio = window.devicePixelRatio || 1;
  29033. var context = _this._drawingContext;
  29034. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29035. _this._ratio = devicePixelRatio / backingStoreRatio;
  29036. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29037. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29038. };
  29039. this._onCanvasClick = function (evt) {
  29040. _this._clickPosition = {
  29041. x: evt.clientX * _this._ratio,
  29042. y: evt.clientY * _this._ratio
  29043. };
  29044. };
  29045. this._syncUI = function () {
  29046. if (_this._showUI) {
  29047. if (_this._displayStatistics) {
  29048. _this._displayStats();
  29049. _this._statsDiv.style.display = "";
  29050. }
  29051. else {
  29052. _this._statsDiv.style.display = "none";
  29053. }
  29054. if (_this._displayLogs) {
  29055. _this._logDiv.style.display = "";
  29056. }
  29057. else {
  29058. _this._logDiv.style.display = "none";
  29059. }
  29060. if (_this._displayTree) {
  29061. _this._treeDiv.style.display = "";
  29062. if (_this._needToRefreshMeshesTree) {
  29063. _this._needToRefreshMeshesTree = false;
  29064. _this._refreshMeshesTreeContent();
  29065. }
  29066. }
  29067. else {
  29068. _this._treeDiv.style.display = "none";
  29069. }
  29070. }
  29071. };
  29072. this._syncData = function () {
  29073. if (_this._labelsEnabled || !_this._showUI) {
  29074. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29075. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29076. var engine = _this._scene.getEngine();
  29077. var viewport = _this._camera.viewport;
  29078. var globalViewport = viewport.toGlobal(engine);
  29079. // Meshes
  29080. var meshes = _this._camera.getActiveMeshes();
  29081. for (var index = 0; index < meshes.length; index++) {
  29082. var mesh = meshes.data[index];
  29083. var position = mesh.getBoundingInfo().boundingSphere.center;
  29084. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29085. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29086. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29087. }
  29088. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29089. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29090. mesh.renderOverlay = !mesh.renderOverlay;
  29091. }, function () {
  29092. return mesh.renderOverlay ? 'red' : 'black';
  29093. });
  29094. }
  29095. }
  29096. // Cameras
  29097. var cameras = _this._scene.cameras;
  29098. for (index = 0; index < cameras.length; index++) {
  29099. var camera = cameras[index];
  29100. if (camera === _this._camera) {
  29101. continue;
  29102. }
  29103. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29104. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29105. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29106. _this._camera.detachControl(engine.getRenderingCanvas());
  29107. _this._camera = camera;
  29108. _this._camera.attachControl(engine.getRenderingCanvas());
  29109. }, function () {
  29110. return "purple";
  29111. });
  29112. }
  29113. }
  29114. // Lights
  29115. var lights = _this._scene.lights;
  29116. for (index = 0; index < lights.length; index++) {
  29117. var light = lights[index];
  29118. if (light.position) {
  29119. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29120. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29121. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29122. light.setEnabled(!light.isEnabled());
  29123. }, function () {
  29124. return light.isEnabled() ? "orange" : "gray";
  29125. });
  29126. }
  29127. }
  29128. }
  29129. }
  29130. _this._clickPosition = undefined;
  29131. };
  29132. }
  29133. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29134. while (this._treeSubsetDiv.hasChildNodes()) {
  29135. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29136. }
  29137. // Add meshes
  29138. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29139. sortedArray.sort(function (a, b) {
  29140. if (a.name === b.name) {
  29141. return 0;
  29142. }
  29143. return (a.name > b.name) ? 1 : -1;
  29144. });
  29145. for (var index = 0; index < sortedArray.length; index++) {
  29146. var mesh = sortedArray[index];
  29147. if (!mesh.isEnabled()) {
  29148. continue;
  29149. }
  29150. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29151. m.isVisible = element.checked;
  29152. }, mesh);
  29153. }
  29154. };
  29155. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29156. this._drawingContext.beginPath();
  29157. this._drawingContext.moveTo(zero.x, zero.y);
  29158. this._drawingContext.lineTo(unit.x, unit.y);
  29159. this._drawingContext.strokeStyle = color;
  29160. this._drawingContext.lineWidth = 4;
  29161. this._drawingContext.stroke();
  29162. this._drawingContext.font = "normal 14px Segoe UI";
  29163. this._drawingContext.fillStyle = color;
  29164. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29165. };
  29166. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29167. var position = mesh.getBoundingInfo().boundingSphere.center;
  29168. var worldMatrix = mesh.getWorldMatrix();
  29169. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29170. var unit = (unprojectedVector.subtract(position)).length();
  29171. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29172. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29173. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29174. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29175. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29176. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29177. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29178. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29179. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29180. };
  29181. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29182. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29183. this._drawingContext.font = "normal 12px Segoe UI";
  29184. var textMetrics = this._drawingContext.measureText(text);
  29185. var centerX = projectedPosition.x - textMetrics.width / 2;
  29186. var centerY = projectedPosition.y;
  29187. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29188. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29189. onClick();
  29190. }
  29191. this._drawingContext.beginPath();
  29192. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29193. this._drawingContext.fillStyle = getFillStyle();
  29194. this._drawingContext.globalAlpha = 0.5;
  29195. this._drawingContext.fill();
  29196. this._drawingContext.globalAlpha = 1.0;
  29197. this._drawingContext.strokeStyle = '#FFFFFF';
  29198. this._drawingContext.lineWidth = 1;
  29199. this._drawingContext.stroke();
  29200. this._drawingContext.fillStyle = "#FFFFFF";
  29201. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29202. this._drawingContext.beginPath();
  29203. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29204. this._drawingContext.fill();
  29205. }
  29206. };
  29207. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29208. if (!this._clickPosition) {
  29209. return false;
  29210. }
  29211. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29212. return false;
  29213. }
  29214. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29215. return false;
  29216. }
  29217. return true;
  29218. };
  29219. DebugLayer.prototype.isVisible = function () {
  29220. return this._enabled;
  29221. };
  29222. DebugLayer.prototype.hide = function () {
  29223. if (!this._enabled) {
  29224. return;
  29225. }
  29226. this._enabled = false;
  29227. var engine = this._scene.getEngine();
  29228. this._scene.unregisterBeforeRender(this._syncData);
  29229. this._scene.unregisterAfterRender(this._syncUI);
  29230. document.body.removeChild(this._globalDiv);
  29231. window.removeEventListener("resize", this._syncPositions);
  29232. this._scene.forceShowBoundingBoxes = false;
  29233. this._scene.forceWireframe = false;
  29234. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29235. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29236. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29237. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29238. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29239. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29240. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29241. this._scene.shadowsEnabled = true;
  29242. this._scene.particlesEnabled = true;
  29243. this._scene.postProcessesEnabled = true;
  29244. this._scene.collisionsEnabled = true;
  29245. this._scene.lightsEnabled = true;
  29246. this._scene.texturesEnabled = true;
  29247. this._scene.lensFlaresEnabled = true;
  29248. this._scene.proceduralTexturesEnabled = true;
  29249. this._scene.renderTargetsEnabled = true;
  29250. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29251. };
  29252. DebugLayer.prototype.show = function (showUI, camera) {
  29253. if (showUI === void 0) { showUI = true; }
  29254. if (camera === void 0) { camera = null; }
  29255. if (this._enabled) {
  29256. return;
  29257. }
  29258. this._enabled = true;
  29259. if (camera) {
  29260. this._camera = camera;
  29261. }
  29262. else {
  29263. this._camera = this._scene.activeCamera;
  29264. }
  29265. this._showUI = showUI;
  29266. var engine = this._scene.getEngine();
  29267. this._globalDiv = document.createElement("div");
  29268. document.body.appendChild(this._globalDiv);
  29269. this._generateDOMelements();
  29270. window.addEventListener("resize", this._syncPositions);
  29271. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29272. this._syncPositions();
  29273. this._scene.registerBeforeRender(this._syncData);
  29274. this._scene.registerAfterRender(this._syncUI);
  29275. };
  29276. DebugLayer.prototype._clearLabels = function () {
  29277. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29278. for (var index = 0; index < this._scene.meshes.length; index++) {
  29279. var mesh = this._scene.meshes[index];
  29280. mesh.renderOverlay = false;
  29281. }
  29282. };
  29283. DebugLayer.prototype._generateheader = function (root, text) {
  29284. var header = document.createElement("div");
  29285. header.innerHTML = text + "&nbsp;";
  29286. header.style.textAlign = "right";
  29287. header.style.width = "100%";
  29288. header.style.color = "white";
  29289. header.style.backgroundColor = "Black";
  29290. header.style.padding = "5px 5px 4px 0px";
  29291. header.style.marginLeft = "-5px";
  29292. header.style.fontWeight = "bold";
  29293. root.appendChild(header);
  29294. };
  29295. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29296. var label = document.createElement("label");
  29297. label.innerHTML = title;
  29298. label.style.color = color;
  29299. root.appendChild(label);
  29300. root.appendChild(document.createElement("br"));
  29301. };
  29302. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29303. if (tag === void 0) { tag = null; }
  29304. var label = document.createElement("label");
  29305. var boundingBoxesCheckbox = document.createElement("input");
  29306. boundingBoxesCheckbox.type = "checkbox";
  29307. boundingBoxesCheckbox.checked = initialState;
  29308. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29309. task(evt.target, tag);
  29310. });
  29311. label.appendChild(boundingBoxesCheckbox);
  29312. var container = document.createElement("span");
  29313. var leftPart = document.createElement("span");
  29314. var rightPart = document.createElement("span");
  29315. rightPart.style.cssFloat = "right";
  29316. leftPart.innerHTML = leftTitle;
  29317. rightPart.innerHTML = rightTitle;
  29318. rightPart.style.fontSize = "12px";
  29319. rightPart.style.maxWidth = "200px";
  29320. container.appendChild(leftPart);
  29321. container.appendChild(rightPart);
  29322. label.appendChild(container);
  29323. root.appendChild(label);
  29324. root.appendChild(document.createElement("br"));
  29325. };
  29326. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29327. if (tag === void 0) { tag = null; }
  29328. var label = document.createElement("label");
  29329. var checkBox = document.createElement("input");
  29330. checkBox.type = "checkbox";
  29331. checkBox.checked = initialState;
  29332. checkBox.addEventListener("change", function (evt) {
  29333. task(evt.target, tag);
  29334. });
  29335. label.appendChild(checkBox);
  29336. label.appendChild(document.createTextNode(title));
  29337. root.appendChild(label);
  29338. root.appendChild(document.createElement("br"));
  29339. };
  29340. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29341. if (tag === void 0) { tag = null; }
  29342. var button = document.createElement("button");
  29343. button.innerHTML = title;
  29344. button.style.height = "24px";
  29345. button.style.color = "#444444";
  29346. button.style.border = "1px solid white";
  29347. button.className = "debugLayerButton";
  29348. button.addEventListener("click", function (evt) {
  29349. task(evt.target, tag);
  29350. });
  29351. root.appendChild(button);
  29352. root.appendChild(document.createElement("br"));
  29353. };
  29354. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29355. if (tag === void 0) { tag = null; }
  29356. var label = document.createElement("label");
  29357. var boundingBoxesRadio = document.createElement("input");
  29358. boundingBoxesRadio.type = "radio";
  29359. boundingBoxesRadio.name = name;
  29360. boundingBoxesRadio.checked = initialState;
  29361. boundingBoxesRadio.addEventListener("change", function (evt) {
  29362. task(evt.target, tag);
  29363. });
  29364. label.appendChild(boundingBoxesRadio);
  29365. label.appendChild(document.createTextNode(title));
  29366. root.appendChild(label);
  29367. root.appendChild(document.createElement("br"));
  29368. };
  29369. DebugLayer.prototype._generateDOMelements = function () {
  29370. var _this = this;
  29371. this._globalDiv.id = "DebugLayer";
  29372. this._globalDiv.style.position = "absolute";
  29373. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29374. this._globalDiv.style.fontSize = "14px";
  29375. this._globalDiv.style.color = "white";
  29376. // Drawing canvas
  29377. this._drawingCanvas = document.createElement("canvas");
  29378. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29379. this._drawingCanvas.style.position = "absolute";
  29380. this._drawingCanvas.style.pointerEvents = "none";
  29381. this._drawingContext = this._drawingCanvas.getContext("2d");
  29382. this._globalDiv.appendChild(this._drawingCanvas);
  29383. if (this._showUI) {
  29384. var background = "rgba(128, 128, 128, 0.4)";
  29385. var border = "rgb(180, 180, 180) solid 1px";
  29386. // Stats
  29387. this._statsDiv = document.createElement("div");
  29388. this._statsDiv.id = "DebugLayerStats";
  29389. this._statsDiv.style.border = border;
  29390. this._statsDiv.style.position = "absolute";
  29391. this._statsDiv.style.background = background;
  29392. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29393. this._generateheader(this._statsDiv, "STATISTICS");
  29394. this._statsSubsetDiv = document.createElement("div");
  29395. this._statsSubsetDiv.style.paddingTop = "5px";
  29396. this._statsSubsetDiv.style.paddingBottom = "5px";
  29397. this._statsSubsetDiv.style.overflowY = "auto";
  29398. this._statsDiv.appendChild(this._statsSubsetDiv);
  29399. // Tree
  29400. this._treeDiv = document.createElement("div");
  29401. this._treeDiv.id = "DebugLayerTree";
  29402. this._treeDiv.style.border = border;
  29403. this._treeDiv.style.position = "absolute";
  29404. this._treeDiv.style.background = background;
  29405. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29406. this._treeDiv.style.display = "none";
  29407. this._generateheader(this._treeDiv, "MESHES TREE");
  29408. this._treeSubsetDiv = document.createElement("div");
  29409. this._treeSubsetDiv.style.paddingTop = "5px";
  29410. this._treeSubsetDiv.style.paddingRight = "5px";
  29411. this._treeSubsetDiv.style.overflowY = "auto";
  29412. this._treeSubsetDiv.style.maxHeight = "300px";
  29413. this._treeDiv.appendChild(this._treeSubsetDiv);
  29414. this._needToRefreshMeshesTree = true;
  29415. // Logs
  29416. this._logDiv = document.createElement("div");
  29417. this._logDiv.style.border = border;
  29418. this._logDiv.id = "DebugLayerLogs";
  29419. this._logDiv.style.position = "absolute";
  29420. this._logDiv.style.background = background;
  29421. this._logDiv.style.padding = "0px 0px 0px 5px";
  29422. this._logDiv.style.display = "none";
  29423. this._generateheader(this._logDiv, "LOGS");
  29424. this._logSubsetDiv = document.createElement("div");
  29425. this._logSubsetDiv.style.height = "127px";
  29426. this._logSubsetDiv.style.paddingTop = "5px";
  29427. this._logSubsetDiv.style.overflowY = "auto";
  29428. this._logSubsetDiv.style.fontSize = "12px";
  29429. this._logSubsetDiv.style.fontFamily = "consolas";
  29430. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29431. this._logDiv.appendChild(this._logSubsetDiv);
  29432. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29433. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29434. };
  29435. // Options
  29436. this._optionsDiv = document.createElement("div");
  29437. this._optionsDiv.id = "DebugLayerOptions";
  29438. this._optionsDiv.style.border = border;
  29439. this._optionsDiv.style.position = "absolute";
  29440. this._optionsDiv.style.background = background;
  29441. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29442. this._optionsDiv.style.overflowY = "auto";
  29443. this._generateheader(this._optionsDiv, "OPTIONS");
  29444. this._optionsSubsetDiv = document.createElement("div");
  29445. this._optionsSubsetDiv.style.paddingTop = "5px";
  29446. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29447. this._optionsSubsetDiv.style.overflowY = "auto";
  29448. this._optionsSubsetDiv.style.maxHeight = "200px";
  29449. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29450. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29451. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29452. _this._displayStatistics = element.checked;
  29453. });
  29454. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29455. _this._displayLogs = element.checked;
  29456. });
  29457. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29458. _this._displayTree = element.checked;
  29459. _this._needToRefreshMeshesTree = true;
  29460. });
  29461. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29462. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29463. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29464. _this._scene.forceShowBoundingBoxes = element.checked;
  29465. });
  29466. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29467. _this._labelsEnabled = element.checked;
  29468. if (!_this._labelsEnabled) {
  29469. _this._clearLabels();
  29470. }
  29471. });
  29472. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29473. if (element.checked) {
  29474. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29475. }
  29476. else {
  29477. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29478. }
  29479. });
  29480. ;
  29481. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29482. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29483. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29484. if (element.checked) {
  29485. _this._scene.forceWireframe = false;
  29486. _this._scene.forcePointsCloud = false;
  29487. }
  29488. });
  29489. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29490. if (element.checked) {
  29491. _this._scene.forceWireframe = true;
  29492. _this._scene.forcePointsCloud = false;
  29493. }
  29494. });
  29495. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29496. if (element.checked) {
  29497. _this._scene.forceWireframe = false;
  29498. _this._scene.forcePointsCloud = true;
  29499. }
  29500. });
  29501. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29502. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29503. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29504. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29505. });
  29506. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29507. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29508. });
  29509. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29510. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29511. });
  29512. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29513. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29514. });
  29515. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29516. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29517. });
  29518. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29519. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29520. });
  29521. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29522. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29523. });
  29524. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29525. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29526. });
  29527. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29528. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29529. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29530. _this._scene.animationsEnabled = element.checked;
  29531. });
  29532. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29533. _this._scene.collisionsEnabled = element.checked;
  29534. });
  29535. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29536. _this._scene.fogEnabled = element.checked;
  29537. });
  29538. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29539. _this._scene.lensFlaresEnabled = element.checked;
  29540. });
  29541. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29542. _this._scene.lightsEnabled = element.checked;
  29543. });
  29544. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29545. _this._scene.particlesEnabled = element.checked;
  29546. });
  29547. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29548. _this._scene.postProcessesEnabled = element.checked;
  29549. });
  29550. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29551. _this._scene.proceduralTexturesEnabled = element.checked;
  29552. });
  29553. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29554. _this._scene.renderTargetsEnabled = element.checked;
  29555. });
  29556. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29557. _this._scene.shadowsEnabled = element.checked;
  29558. });
  29559. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29560. _this._scene.skeletonsEnabled = element.checked;
  29561. });
  29562. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29563. _this._scene.spritesEnabled = element.checked;
  29564. });
  29565. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29566. _this._scene.texturesEnabled = element.checked;
  29567. });
  29568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29569. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29570. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29571. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29572. if (element.checked) {
  29573. _this._scene.headphone = true;
  29574. }
  29575. });
  29576. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29577. if (element.checked) {
  29578. _this._scene.headphone = false;
  29579. }
  29580. });
  29581. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29582. _this._scene.audioEnabled = !element.checked;
  29583. });
  29584. }
  29585. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29586. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29587. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29588. _this._scene.dumpNextRenderTargets = true;
  29589. });
  29590. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29591. this._globalDiv.appendChild(this._statsDiv);
  29592. this._globalDiv.appendChild(this._logDiv);
  29593. this._globalDiv.appendChild(this._optionsDiv);
  29594. this._globalDiv.appendChild(this._treeDiv);
  29595. }
  29596. };
  29597. DebugLayer.prototype._displayStats = function () {
  29598. var scene = this._scene;
  29599. var engine = scene.getEngine();
  29600. var glInfo = engine.getGlInfo();
  29601. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active indices: " + scene.getActiveIndices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  29602. if (this.customStatsFunction) {
  29603. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29604. }
  29605. };
  29606. return DebugLayer;
  29607. })();
  29608. BABYLON.DebugLayer = DebugLayer;
  29609. })(BABYLON || (BABYLON = {}));
  29610. //# sourceMappingURL=babylon.debugLayer.js.map
  29611. var __extends = this.__extends || function (d, b) {
  29612. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29613. function __() { this.constructor = d; }
  29614. __.prototype = b.prototype;
  29615. d.prototype = new __();
  29616. };
  29617. var BABYLON;
  29618. (function (BABYLON) {
  29619. var RawTexture = (function (_super) {
  29620. __extends(RawTexture, _super);
  29621. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29622. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29623. if (invertY === void 0) { invertY = false; }
  29624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29625. _super.call(this, null, scene, !generateMipMaps, invertY);
  29626. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29627. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29628. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29629. }
  29630. // Statics
  29631. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29632. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29633. if (invertY === void 0) { invertY = false; }
  29634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29635. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29636. };
  29637. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29638. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29639. if (invertY === void 0) { invertY = false; }
  29640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29641. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29642. };
  29643. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29644. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29645. if (invertY === void 0) { invertY = false; }
  29646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29647. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29648. };
  29649. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29650. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29651. if (invertY === void 0) { invertY = false; }
  29652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29653. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29654. };
  29655. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29656. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29657. if (invertY === void 0) { invertY = false; }
  29658. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29659. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29660. };
  29661. return RawTexture;
  29662. })(BABYLON.Texture);
  29663. BABYLON.RawTexture = RawTexture;
  29664. })(BABYLON || (BABYLON = {}));
  29665. //# sourceMappingURL=babylon.rawTexture.js.map
  29666. var __extends = this.__extends || function (d, b) {
  29667. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29668. function __() { this.constructor = d; }
  29669. __.prototype = b.prototype;
  29670. d.prototype = new __();
  29671. };
  29672. var BABYLON;
  29673. (function (BABYLON) {
  29674. var IndexedVector2 = (function (_super) {
  29675. __extends(IndexedVector2, _super);
  29676. function IndexedVector2(original, index) {
  29677. _super.call(this, original.x, original.y);
  29678. this.index = index;
  29679. }
  29680. return IndexedVector2;
  29681. })(BABYLON.Vector2);
  29682. var PolygonPoints = (function () {
  29683. function PolygonPoints() {
  29684. this.elements = new Array();
  29685. }
  29686. PolygonPoints.prototype.add = function (originalPoints) {
  29687. var _this = this;
  29688. var result = new Array();
  29689. originalPoints.forEach(function (point) {
  29690. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  29691. var newPoint = new IndexedVector2(point, _this.elements.length);
  29692. result.push(newPoint);
  29693. _this.elements.push(newPoint);
  29694. }
  29695. });
  29696. return result;
  29697. };
  29698. PolygonPoints.prototype.computeBounds = function () {
  29699. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29700. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29701. this.elements.forEach(function (point) {
  29702. // x
  29703. if (point.x < lmin.x) {
  29704. lmin.x = point.x;
  29705. }
  29706. else if (point.x > lmax.x) {
  29707. lmax.x = point.x;
  29708. }
  29709. // y
  29710. if (point.y < lmin.y) {
  29711. lmin.y = point.y;
  29712. }
  29713. else if (point.y > lmax.y) {
  29714. lmax.y = point.y;
  29715. }
  29716. });
  29717. return {
  29718. min: lmin,
  29719. max: lmax,
  29720. width: lmax.x - lmin.x,
  29721. height: lmax.y - lmin.y
  29722. };
  29723. };
  29724. return PolygonPoints;
  29725. })();
  29726. var Polygon = (function () {
  29727. function Polygon() {
  29728. }
  29729. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29730. return [
  29731. new BABYLON.Vector2(xmin, ymin),
  29732. new BABYLON.Vector2(xmax, ymin),
  29733. new BABYLON.Vector2(xmax, ymax),
  29734. new BABYLON.Vector2(xmin, ymax)
  29735. ];
  29736. };
  29737. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29738. if (cx === void 0) { cx = 0; }
  29739. if (cy === void 0) { cy = 0; }
  29740. if (numberOfSides === void 0) { numberOfSides = 32; }
  29741. var result = new Array();
  29742. var angle = 0;
  29743. var increment = (Math.PI * 2) / numberOfSides;
  29744. for (var i = 0; i < numberOfSides; i++) {
  29745. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29746. angle -= increment;
  29747. }
  29748. return result;
  29749. };
  29750. Polygon.Parse = function (input) {
  29751. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29752. var i, result = [];
  29753. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29754. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  29755. }
  29756. return result;
  29757. };
  29758. Polygon.StartingAt = function (x, y) {
  29759. return BABYLON.Path2.StartingAt(x, y);
  29760. };
  29761. return Polygon;
  29762. })();
  29763. BABYLON.Polygon = Polygon;
  29764. var PolygonMeshBuilder = (function () {
  29765. function PolygonMeshBuilder(name, contours, scene) {
  29766. this._points = new PolygonPoints();
  29767. if (!("poly2tri" in window)) {
  29768. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29769. }
  29770. this._name = name;
  29771. this._scene = scene;
  29772. var points;
  29773. if (contours instanceof BABYLON.Path2) {
  29774. points = contours.getPoints();
  29775. }
  29776. else {
  29777. points = contours;
  29778. }
  29779. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29780. }
  29781. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29782. this._swctx.addHole(this._points.add(hole));
  29783. return this;
  29784. };
  29785. PolygonMeshBuilder.prototype.build = function (updatable) {
  29786. if (updatable === void 0) { updatable = false; }
  29787. var result = new BABYLON.Mesh(this._name, this._scene);
  29788. var normals = [];
  29789. var positions = [];
  29790. var uvs = [];
  29791. var bounds = this._points.computeBounds();
  29792. this._points.elements.forEach(function (p) {
  29793. normals.push(0, 1.0, 0);
  29794. positions.push(p.x, 0, p.y);
  29795. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29796. });
  29797. var indices = [];
  29798. this._swctx.triangulate();
  29799. this._swctx.getTriangles().forEach(function (triangle) {
  29800. triangle.getPoints().forEach(function (point) {
  29801. indices.push(point.index);
  29802. });
  29803. });
  29804. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  29805. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  29806. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  29807. result.setIndices(indices);
  29808. return result;
  29809. };
  29810. return PolygonMeshBuilder;
  29811. })();
  29812. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  29813. })(BABYLON || (BABYLON = {}));
  29814. //# sourceMappingURL=babylon.polygonMesh.js.map
  29815. var BABYLON;
  29816. (function (BABYLON) {
  29817. var SimplificationSettings = (function () {
  29818. function SimplificationSettings(quality, distance, optimizeMesh) {
  29819. this.quality = quality;
  29820. this.distance = distance;
  29821. this.optimizeMesh = optimizeMesh;
  29822. }
  29823. return SimplificationSettings;
  29824. })();
  29825. BABYLON.SimplificationSettings = SimplificationSettings;
  29826. var SimplificationQueue = (function () {
  29827. function SimplificationQueue() {
  29828. this.running = false;
  29829. this._simplificationArray = [];
  29830. }
  29831. SimplificationQueue.prototype.addTask = function (task) {
  29832. this._simplificationArray.push(task);
  29833. };
  29834. SimplificationQueue.prototype.executeNext = function () {
  29835. var task = this._simplificationArray.pop();
  29836. if (task) {
  29837. this.running = true;
  29838. this.runSimplification(task);
  29839. }
  29840. else {
  29841. this.running = false;
  29842. }
  29843. };
  29844. SimplificationQueue.prototype.runSimplification = function (task) {
  29845. var _this = this;
  29846. if (task.parallelProcessing) {
  29847. //parallel simplifier
  29848. task.settings.forEach(function (setting) {
  29849. var simplifier = _this.getSimplifier(task);
  29850. simplifier.simplify(setting, function (newMesh) {
  29851. task.mesh.addLODLevel(setting.distance, newMesh);
  29852. newMesh.isVisible = true;
  29853. //check if it is the last
  29854. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29855. //all done, run the success callback.
  29856. task.successCallback();
  29857. }
  29858. _this.executeNext();
  29859. });
  29860. });
  29861. }
  29862. else {
  29863. //single simplifier.
  29864. var simplifier = this.getSimplifier(task);
  29865. var runDecimation = function (setting, callback) {
  29866. simplifier.simplify(setting, function (newMesh) {
  29867. task.mesh.addLODLevel(setting.distance, newMesh);
  29868. newMesh.isVisible = true;
  29869. //run the next quality level
  29870. callback();
  29871. });
  29872. };
  29873. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29874. runDecimation(task.settings[loop.index], function () {
  29875. loop.executeNext();
  29876. });
  29877. }, function () {
  29878. //execution ended, run the success callback.
  29879. if (task.successCallback) {
  29880. task.successCallback();
  29881. }
  29882. _this.executeNext();
  29883. });
  29884. }
  29885. };
  29886. SimplificationQueue.prototype.getSimplifier = function (task) {
  29887. switch (task.simplificationType) {
  29888. case 0 /* QUADRATIC */:
  29889. default:
  29890. return new QuadraticErrorSimplification(task.mesh);
  29891. }
  29892. };
  29893. return SimplificationQueue;
  29894. })();
  29895. BABYLON.SimplificationQueue = SimplificationQueue;
  29896. /**
  29897. * The implemented types of simplification.
  29898. * At the moment only Quadratic Error Decimation is implemented.
  29899. */
  29900. (function (SimplificationType) {
  29901. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29902. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29903. var SimplificationType = BABYLON.SimplificationType;
  29904. var DecimationTriangle = (function () {
  29905. function DecimationTriangle(vertices) {
  29906. this.vertices = vertices;
  29907. this.error = new Array(4);
  29908. this.deleted = false;
  29909. this.isDirty = false;
  29910. this.deletePending = false;
  29911. this.borderFactor = 0;
  29912. }
  29913. return DecimationTriangle;
  29914. })();
  29915. BABYLON.DecimationTriangle = DecimationTriangle;
  29916. var DecimationVertex = (function () {
  29917. function DecimationVertex(position, id) {
  29918. this.position = position;
  29919. this.id = id;
  29920. this.isBorder = true;
  29921. this.q = new QuadraticMatrix();
  29922. this.triangleCount = 0;
  29923. this.triangleStart = 0;
  29924. this.originalOffsets = [];
  29925. }
  29926. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29927. this.position.copyFrom(newPosition);
  29928. };
  29929. return DecimationVertex;
  29930. })();
  29931. BABYLON.DecimationVertex = DecimationVertex;
  29932. var QuadraticMatrix = (function () {
  29933. function QuadraticMatrix(data) {
  29934. this.data = new Array(10);
  29935. for (var i = 0; i < 10; ++i) {
  29936. if (data && data[i]) {
  29937. this.data[i] = data[i];
  29938. }
  29939. else {
  29940. this.data[i] = 0;
  29941. }
  29942. }
  29943. }
  29944. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29945. 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];
  29946. return det;
  29947. };
  29948. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29949. for (var i = 0; i < 10; ++i) {
  29950. this.data[i] += matrix.data[i];
  29951. }
  29952. };
  29953. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29954. for (var i = 0; i < 10; ++i) {
  29955. this.data[i] += data[i];
  29956. }
  29957. };
  29958. QuadraticMatrix.prototype.add = function (matrix) {
  29959. var m = new QuadraticMatrix();
  29960. for (var i = 0; i < 10; ++i) {
  29961. m.data[i] = this.data[i] + matrix.data[i];
  29962. }
  29963. return m;
  29964. };
  29965. QuadraticMatrix.FromData = function (a, b, c, d) {
  29966. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29967. };
  29968. //returning an array to avoid garbage collection
  29969. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29970. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29971. };
  29972. return QuadraticMatrix;
  29973. })();
  29974. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29975. var Reference = (function () {
  29976. function Reference(vertexId, triangleId) {
  29977. this.vertexId = vertexId;
  29978. this.triangleId = triangleId;
  29979. }
  29980. return Reference;
  29981. })();
  29982. BABYLON.Reference = Reference;
  29983. /**
  29984. * An implementation of the Quadratic Error simplification algorithm.
  29985. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29986. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29987. * @author RaananW
  29988. */
  29989. var QuadraticErrorSimplification = (function () {
  29990. function QuadraticErrorSimplification(_mesh) {
  29991. this._mesh = _mesh;
  29992. this.initialized = false;
  29993. this.syncIterations = 5000;
  29994. this.aggressiveness = 7;
  29995. this.decimationIterations = 100;
  29996. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29997. }
  29998. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29999. var _this = this;
  30000. this.initDecimatedMesh();
  30001. //iterating through the submeshes array, one after the other.
  30002. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30003. _this.initWithMesh(loop.index, function () {
  30004. _this.runDecimation(settings, loop.index, function () {
  30005. loop.executeNext();
  30006. });
  30007. }, settings.optimizeMesh);
  30008. }, function () {
  30009. setTimeout(function () {
  30010. successCallback(_this._reconstructedMesh);
  30011. }, 0);
  30012. });
  30013. };
  30014. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30015. var _this = this;
  30016. var gCount = 0;
  30017. triangle.vertices.forEach(function (vertex) {
  30018. var count = 0;
  30019. var vPos = vertex.position;
  30020. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30021. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30022. ++count;
  30023. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30024. ++count;
  30025. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30026. ++count;
  30027. if (count > 1) {
  30028. ++gCount;
  30029. }
  30030. ;
  30031. });
  30032. if (gCount > 1) {
  30033. console.log(triangle, gCount);
  30034. }
  30035. return gCount > 1;
  30036. };
  30037. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30038. var _this = this;
  30039. var targetCount = ~~(this.triangles.length * settings.quality);
  30040. var deletedTriangles = 0;
  30041. var triangleCount = this.triangles.length;
  30042. var iterationFunction = function (iteration, callback) {
  30043. setTimeout(function () {
  30044. if (iteration % 5 === 0) {
  30045. _this.updateMesh(iteration === 0);
  30046. }
  30047. for (var i = 0; i < _this.triangles.length; ++i) {
  30048. _this.triangles[i].isDirty = false;
  30049. }
  30050. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30051. var trianglesIterator = function (i) {
  30052. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30053. var t = _this.triangles[tIdx];
  30054. if (!t)
  30055. return;
  30056. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30057. return;
  30058. }
  30059. for (var j = 0; j < 3; ++j) {
  30060. if (t.error[j] < threshold) {
  30061. var deleted0 = [];
  30062. var deleted1 = [];
  30063. var v0 = t.vertices[j];
  30064. var v1 = t.vertices[(j + 1) % 3];
  30065. if (v0.isBorder !== v1.isBorder)
  30066. continue;
  30067. var p = BABYLON.Vector3.Zero();
  30068. var n = BABYLON.Vector3.Zero();
  30069. var uv = BABYLON.Vector2.Zero();
  30070. var color = new BABYLON.Color4(0, 0, 0, 1);
  30071. _this.calculateError(v0, v1, p, n, uv, color);
  30072. var delTr = [];
  30073. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30074. continue;
  30075. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30076. continue;
  30077. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30078. continue;
  30079. var uniqueArray = [];
  30080. delTr.forEach(function (deletedT) {
  30081. if (uniqueArray.indexOf(deletedT) === -1) {
  30082. deletedT.deletePending = true;
  30083. uniqueArray.push(deletedT);
  30084. }
  30085. });
  30086. if (uniqueArray.length % 2 != 0) {
  30087. continue;
  30088. }
  30089. v0.q = v1.q.add(v0.q);
  30090. v0.updatePosition(p);
  30091. var tStart = _this.references.length;
  30092. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30093. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30094. var tCount = _this.references.length - tStart;
  30095. if (tCount <= v0.triangleCount) {
  30096. if (tCount) {
  30097. for (var c = 0; c < tCount; c++) {
  30098. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30099. }
  30100. }
  30101. }
  30102. else {
  30103. v0.triangleStart = tStart;
  30104. }
  30105. v0.triangleCount = tCount;
  30106. break;
  30107. }
  30108. }
  30109. };
  30110. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30111. return (triangleCount - deletedTriangles <= targetCount);
  30112. });
  30113. }, 0);
  30114. };
  30115. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30116. if (triangleCount - deletedTriangles <= targetCount)
  30117. loop.breakLoop();
  30118. else {
  30119. iterationFunction(loop.index, function () {
  30120. loop.executeNext();
  30121. });
  30122. }
  30123. }, function () {
  30124. setTimeout(function () {
  30125. //reconstruct this part of the mesh
  30126. _this.reconstructMesh(submeshIndex);
  30127. successCallback();
  30128. }, 0);
  30129. });
  30130. };
  30131. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30132. var _this = this;
  30133. this.vertices = [];
  30134. this.triangles = [];
  30135. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30136. var indices = this._mesh.getIndices();
  30137. var submesh = this._mesh.subMeshes[submeshIndex];
  30138. var findInVertices = function (positionToSearch) {
  30139. if (optimizeMesh) {
  30140. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30141. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30142. return _this.vertices[ii];
  30143. }
  30144. }
  30145. }
  30146. return null;
  30147. };
  30148. var vertexReferences = [];
  30149. var vertexInit = function (i) {
  30150. var offset = i + submesh.verticesStart;
  30151. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30152. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30153. vertex.originalOffsets.push(offset);
  30154. if (vertex.id == _this.vertices.length) {
  30155. _this.vertices.push(vertex);
  30156. }
  30157. vertexReferences.push(vertex.id);
  30158. };
  30159. //var totalVertices = mesh.getTotalVertices();
  30160. var totalVertices = submesh.verticesCount;
  30161. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30162. var indicesInit = function (i) {
  30163. var offset = (submesh.indexStart / 3) + i;
  30164. var pos = (offset * 3);
  30165. var i0 = indices[pos + 0];
  30166. var i1 = indices[pos + 1];
  30167. var i2 = indices[pos + 2];
  30168. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30169. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30170. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30171. var triangle = new DecimationTriangle([v0, v1, v2]);
  30172. triangle.originalOffset = pos;
  30173. _this.triangles.push(triangle);
  30174. };
  30175. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30176. _this.init(callback);
  30177. });
  30178. });
  30179. };
  30180. QuadraticErrorSimplification.prototype.init = function (callback) {
  30181. var _this = this;
  30182. var triangleInit1 = function (i) {
  30183. var t = _this.triangles[i];
  30184. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30185. for (var j = 0; j < 3; j++) {
  30186. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  30187. }
  30188. };
  30189. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30190. var triangleInit2 = function (i) {
  30191. var t = _this.triangles[i];
  30192. for (var j = 0; j < 3; ++j) {
  30193. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30194. }
  30195. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30196. };
  30197. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30198. _this.initialized = true;
  30199. callback();
  30200. });
  30201. });
  30202. };
  30203. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30204. var newTriangles = [];
  30205. var i;
  30206. for (i = 0; i < this.vertices.length; ++i) {
  30207. this.vertices[i].triangleCount = 0;
  30208. }
  30209. var t;
  30210. var j;
  30211. for (i = 0; i < this.triangles.length; ++i) {
  30212. if (!this.triangles[i].deleted) {
  30213. t = this.triangles[i];
  30214. for (j = 0; j < 3; ++j) {
  30215. t.vertices[j].triangleCount = 1;
  30216. }
  30217. newTriangles.push(t);
  30218. }
  30219. }
  30220. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30221. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30222. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30223. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30224. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30225. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30226. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30227. var vertexCount = 0;
  30228. for (i = 0; i < this.vertices.length; ++i) {
  30229. var vertex = this.vertices[i];
  30230. vertex.id = vertexCount;
  30231. if (vertex.triangleCount) {
  30232. vertex.originalOffsets.forEach(function (originalOffset) {
  30233. newPositionData.push(vertex.position.x);
  30234. newPositionData.push(vertex.position.y);
  30235. newPositionData.push(vertex.position.z);
  30236. newNormalData.push(normalData[originalOffset * 3]);
  30237. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30238. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30239. if (uvs && uvs.length) {
  30240. newUVsData.push(uvs[(originalOffset * 2)]);
  30241. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30242. }
  30243. else if (colorsData && colorsData.length) {
  30244. newColorsData.push(colorsData[(originalOffset * 4)]);
  30245. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30246. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30247. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30248. }
  30249. ++vertexCount;
  30250. });
  30251. }
  30252. }
  30253. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30254. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30255. var submeshesArray = this._reconstructedMesh.subMeshes;
  30256. this._reconstructedMesh.subMeshes = [];
  30257. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30258. var originalIndices = this._mesh.getIndices();
  30259. for (i = 0; i < newTriangles.length; ++i) {
  30260. var t = newTriangles[i];
  30261. //now get the new referencing point for each vertex
  30262. [0, 1, 2].forEach(function (idx) {
  30263. var id = originalIndices[t.originalOffset + idx];
  30264. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30265. if (offset < 0)
  30266. offset = 0;
  30267. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30268. });
  30269. }
  30270. //overwriting the old vertex buffers and indices.
  30271. this._reconstructedMesh.setIndices(newIndicesArray);
  30272. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30273. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30274. if (newUVsData.length > 0)
  30275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30276. if (newColorsData.length > 0)
  30277. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30278. //create submesh
  30279. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30280. if (submeshIndex > 0) {
  30281. this._reconstructedMesh.subMeshes = [];
  30282. submeshesArray.forEach(function (submesh) {
  30283. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30284. });
  30285. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30286. }
  30287. };
  30288. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30289. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30290. this._reconstructedMesh.material = this._mesh.material;
  30291. this._reconstructedMesh.parent = this._mesh.parent;
  30292. this._reconstructedMesh.isVisible = false;
  30293. };
  30294. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30295. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30296. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30297. if (t.deleted)
  30298. continue;
  30299. var s = this.references[vertex1.triangleStart + i].vertexId;
  30300. var v1 = t.vertices[(s + 1) % 3];
  30301. var v2 = t.vertices[(s + 2) % 3];
  30302. if ((v1 === vertex2 || v2 === vertex2)) {
  30303. deletedArray[i] = true;
  30304. delTr.push(t);
  30305. continue;
  30306. }
  30307. var d1 = v1.position.subtract(point);
  30308. d1 = d1.normalize();
  30309. var d2 = v2.position.subtract(point);
  30310. d2 = d2.normalize();
  30311. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30312. return true;
  30313. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30314. deletedArray[i] = false;
  30315. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30316. return true;
  30317. }
  30318. return false;
  30319. };
  30320. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30321. var newDeleted = deletedTriangles;
  30322. for (var i = 0; i < vertex.triangleCount; ++i) {
  30323. var ref = this.references[vertex.triangleStart + i];
  30324. var t = this.triangles[ref.triangleId];
  30325. if (t.deleted)
  30326. continue;
  30327. if (deletedArray[i] && t.deletePending) {
  30328. t.deleted = true;
  30329. newDeleted++;
  30330. continue;
  30331. }
  30332. t.vertices[ref.vertexId] = origVertex;
  30333. t.isDirty = true;
  30334. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30335. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30336. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30337. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30338. this.references.push(ref);
  30339. }
  30340. return newDeleted;
  30341. };
  30342. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30343. for (var i = 0; i < this.vertices.length; ++i) {
  30344. var vCount = [];
  30345. var vId = [];
  30346. var v = this.vertices[i];
  30347. var j;
  30348. for (j = 0; j < v.triangleCount; ++j) {
  30349. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30350. for (var ii = 0; ii < 3; ii++) {
  30351. var ofs = 0;
  30352. var vv = triangle.vertices[ii];
  30353. while (ofs < vCount.length) {
  30354. if (vId[ofs] === vv.id)
  30355. break;
  30356. ++ofs;
  30357. }
  30358. if (ofs === vCount.length) {
  30359. vCount.push(1);
  30360. vId.push(vv.id);
  30361. }
  30362. else {
  30363. vCount[ofs]++;
  30364. }
  30365. }
  30366. }
  30367. for (j = 0; j < vCount.length; ++j) {
  30368. if (vCount[j] === 1) {
  30369. this.vertices[vId[j]].isBorder = true;
  30370. }
  30371. else {
  30372. this.vertices[vId[j]].isBorder = false;
  30373. }
  30374. }
  30375. }
  30376. };
  30377. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30378. if (identifyBorders === void 0) { identifyBorders = false; }
  30379. var i;
  30380. if (!identifyBorders) {
  30381. var newTrianglesVector = [];
  30382. for (i = 0; i < this.triangles.length; ++i) {
  30383. if (!this.triangles[i].deleted) {
  30384. newTrianglesVector.push(this.triangles[i]);
  30385. }
  30386. }
  30387. this.triangles = newTrianglesVector;
  30388. }
  30389. for (i = 0; i < this.vertices.length; ++i) {
  30390. this.vertices[i].triangleCount = 0;
  30391. this.vertices[i].triangleStart = 0;
  30392. }
  30393. var t;
  30394. var j;
  30395. var v;
  30396. for (i = 0; i < this.triangles.length; ++i) {
  30397. t = this.triangles[i];
  30398. for (j = 0; j < 3; ++j) {
  30399. v = t.vertices[j];
  30400. v.triangleCount++;
  30401. }
  30402. }
  30403. var tStart = 0;
  30404. for (i = 0; i < this.vertices.length; ++i) {
  30405. this.vertices[i].triangleStart = tStart;
  30406. tStart += this.vertices[i].triangleCount;
  30407. this.vertices[i].triangleCount = 0;
  30408. }
  30409. var newReferences = new Array(this.triangles.length * 3);
  30410. for (i = 0; i < this.triangles.length; ++i) {
  30411. t = this.triangles[i];
  30412. for (j = 0; j < 3; ++j) {
  30413. v = t.vertices[j];
  30414. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30415. v.triangleCount++;
  30416. }
  30417. }
  30418. this.references = newReferences;
  30419. if (identifyBorders) {
  30420. this.identifyBorder();
  30421. }
  30422. };
  30423. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30424. var x = point.x;
  30425. var y = point.y;
  30426. var z = point.z;
  30427. 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];
  30428. };
  30429. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30430. var q = vertex1.q.add(vertex2.q);
  30431. var border = vertex1.isBorder && vertex2.isBorder;
  30432. var error = 0;
  30433. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30434. if (qDet !== 0 && !border) {
  30435. if (!pointResult) {
  30436. pointResult = BABYLON.Vector3.Zero();
  30437. }
  30438. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30439. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30440. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30441. error = this.vertexError(q, pointResult);
  30442. }
  30443. else {
  30444. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30445. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30446. var error1 = this.vertexError(q, vertex1.position);
  30447. var error2 = this.vertexError(q, vertex2.position);
  30448. var error3 = this.vertexError(q, p3);
  30449. error = Math.min(error1, error2, error3);
  30450. if (error === error1) {
  30451. if (pointResult) {
  30452. pointResult.copyFrom(vertex1.position);
  30453. }
  30454. }
  30455. else if (error === error2) {
  30456. if (pointResult) {
  30457. pointResult.copyFrom(vertex2.position);
  30458. }
  30459. }
  30460. else {
  30461. if (pointResult) {
  30462. pointResult.copyFrom(p3);
  30463. }
  30464. }
  30465. }
  30466. return error;
  30467. };
  30468. return QuadraticErrorSimplification;
  30469. })();
  30470. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30471. })(BABYLON || (BABYLON = {}));
  30472. //# sourceMappingURL=babylon.meshSimplification.js.map
  30473. var BABYLON;
  30474. (function (BABYLON) {
  30475. var Analyser = (function () {
  30476. function Analyser(scene) {
  30477. this.SMOOTHING = 0.75;
  30478. this.FFT_SIZE = 512;
  30479. this.BARGRAPHAMPLITUDE = 256;
  30480. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30481. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30482. this._scene = scene;
  30483. this._audioEngine = BABYLON.Engine.audioEngine;
  30484. if (this._audioEngine.canUseWebAudio) {
  30485. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30486. this._webAudioAnalyser.minDecibels = -140;
  30487. this._webAudioAnalyser.maxDecibels = 0;
  30488. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30489. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30490. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30491. }
  30492. }
  30493. Analyser.prototype.getFrequencyBinCount = function () {
  30494. if (this._audioEngine.canUseWebAudio) {
  30495. return this._webAudioAnalyser.frequencyBinCount;
  30496. }
  30497. else {
  30498. return 0;
  30499. }
  30500. };
  30501. Analyser.prototype.getByteFrequencyData = function () {
  30502. if (this._audioEngine.canUseWebAudio) {
  30503. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30504. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30505. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30506. }
  30507. return this._byteFreqs;
  30508. };
  30509. Analyser.prototype.getByteTimeDomainData = function () {
  30510. if (this._audioEngine.canUseWebAudio) {
  30511. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30512. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30513. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30514. }
  30515. return this._byteTime;
  30516. };
  30517. Analyser.prototype.getFloatFrequencyData = function () {
  30518. if (this._audioEngine.canUseWebAudio) {
  30519. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30520. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30521. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30522. }
  30523. return this._floatFreqs;
  30524. };
  30525. Analyser.prototype.drawDebugCanvas = function () {
  30526. var _this = this;
  30527. if (this._audioEngine.canUseWebAudio) {
  30528. if (!this._debugCanvas) {
  30529. this._debugCanvas = document.createElement("canvas");
  30530. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30531. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30532. this._debugCanvas.style.position = "absolute";
  30533. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30534. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30535. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30536. document.body.appendChild(this._debugCanvas);
  30537. this._registerFunc = function () {
  30538. _this.drawDebugCanvas();
  30539. };
  30540. this._scene.registerBeforeRender(this._registerFunc);
  30541. }
  30542. if (this._registerFunc) {
  30543. var workingArray = this.getByteFrequencyData();
  30544. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30545. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30546. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30547. var value = workingArray[i];
  30548. var percent = value / this.BARGRAPHAMPLITUDE;
  30549. var height = this.DEBUGCANVASSIZE.height * percent;
  30550. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30551. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30552. var hue = i / this.getFrequencyBinCount() * 360;
  30553. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30554. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30555. }
  30556. }
  30557. }
  30558. };
  30559. Analyser.prototype.stopDebugCanvas = function () {
  30560. if (this._debugCanvas) {
  30561. this._scene.unregisterBeforeRender(this._registerFunc);
  30562. this._registerFunc = null;
  30563. document.body.removeChild(this._debugCanvas);
  30564. this._debugCanvas = null;
  30565. this._debugCanvasContext = null;
  30566. }
  30567. };
  30568. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30569. if (this._audioEngine.canUseWebAudio) {
  30570. inputAudioNode.connect(this._webAudioAnalyser);
  30571. this._webAudioAnalyser.connect(outputAudioNode);
  30572. }
  30573. };
  30574. Analyser.prototype.dispose = function () {
  30575. if (this._audioEngine.canUseWebAudio) {
  30576. this._webAudioAnalyser.disconnect();
  30577. }
  30578. };
  30579. return Analyser;
  30580. })();
  30581. BABYLON.Analyser = Analyser;
  30582. })(BABYLON || (BABYLON = {}));
  30583. //# sourceMappingURL=babylon.analyser.js.map
  30584. var BABYLON;
  30585. (function (BABYLON) {
  30586. var DepthRenderer = (function () {
  30587. function DepthRenderer(scene, type) {
  30588. var _this = this;
  30589. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30590. this._viewMatrix = BABYLON.Matrix.Zero();
  30591. this._projectionMatrix = BABYLON.Matrix.Zero();
  30592. this._transformMatrix = BABYLON.Matrix.Zero();
  30593. this._worldViewProjection = BABYLON.Matrix.Zero();
  30594. this._scene = scene;
  30595. var engine = scene.getEngine();
  30596. // Render target
  30597. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30598. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30599. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30600. this._depthMap.refreshRate = 1;
  30601. this._depthMap.renderParticles = false;
  30602. this._depthMap.renderList = null;
  30603. // set default depth value to 1.0 (far away)
  30604. this._depthMap.onClear = function (engine) {
  30605. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30606. };
  30607. // Custom render function
  30608. var renderSubMesh = function (subMesh) {
  30609. var mesh = subMesh.getRenderingMesh();
  30610. var scene = _this._scene;
  30611. var engine = scene.getEngine();
  30612. // Culling
  30613. engine.setState(subMesh.getMaterial().backFaceCulling);
  30614. // Managing instances
  30615. var batch = mesh._getInstancesRenderList(subMesh._id);
  30616. if (batch.mustReturn) {
  30617. return;
  30618. }
  30619. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30620. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30621. engine.enableEffect(_this._effect);
  30622. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30623. var material = subMesh.getMaterial();
  30624. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30625. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30626. // Alpha test
  30627. if (material && material.needAlphaTesting()) {
  30628. var alphaTexture = material.getAlphaTestTexture();
  30629. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30630. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30631. }
  30632. // Bones
  30633. if (mesh.useBones) {
  30634. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30635. }
  30636. // Draw
  30637. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30638. }
  30639. };
  30640. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30641. var index;
  30642. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30643. renderSubMesh(opaqueSubMeshes.data[index]);
  30644. }
  30645. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30646. renderSubMesh(alphaTestSubMeshes.data[index]);
  30647. }
  30648. };
  30649. }
  30650. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30651. var defines = [];
  30652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30653. var mesh = subMesh.getMesh();
  30654. var scene = mesh.getScene();
  30655. var material = subMesh.getMaterial();
  30656. // Alpha test
  30657. if (material && material.needAlphaTesting()) {
  30658. defines.push("#define ALPHATEST");
  30659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30660. attribs.push(BABYLON.VertexBuffer.UVKind);
  30661. defines.push("#define UV1");
  30662. }
  30663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30664. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30665. defines.push("#define UV2");
  30666. }
  30667. }
  30668. // Bones
  30669. if (mesh.useBones) {
  30670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30672. defines.push("#define BONES");
  30673. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30674. }
  30675. // Instances
  30676. if (useInstances) {
  30677. defines.push("#define INSTANCES");
  30678. attribs.push("world0");
  30679. attribs.push("world1");
  30680. attribs.push("world2");
  30681. attribs.push("world3");
  30682. }
  30683. // Get correct effect
  30684. var join = defines.join("\n");
  30685. if (this._cachedDefines !== join) {
  30686. this._cachedDefines = join;
  30687. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30688. }
  30689. return this._effect.isReady();
  30690. };
  30691. DepthRenderer.prototype.getDepthMap = function () {
  30692. return this._depthMap;
  30693. };
  30694. // Methods
  30695. DepthRenderer.prototype.dispose = function () {
  30696. this._depthMap.dispose();
  30697. };
  30698. return DepthRenderer;
  30699. })();
  30700. BABYLON.DepthRenderer = DepthRenderer;
  30701. })(BABYLON || (BABYLON = {}));
  30702. //# sourceMappingURL=babylon.depthRenderer.js.map
  30703. var __extends = this.__extends || function (d, b) {
  30704. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30705. function __() { this.constructor = d; }
  30706. __.prototype = b.prototype;
  30707. d.prototype = new __();
  30708. };
  30709. var BABYLON;
  30710. (function (BABYLON) {
  30711. var SSAORenderingPipeline = (function (_super) {
  30712. __extends(SSAORenderingPipeline, _super);
  30713. /**
  30714. * @constructor
  30715. * @param {string} name - The rendering pipeline name
  30716. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30717. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  30718. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30719. */
  30720. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30721. var _this = this;
  30722. _super.call(this, scene.getEngine(), name);
  30723. // Members
  30724. /**
  30725. * The PassPostProcess id in the pipeline that contains the original scene color
  30726. * @type {string}
  30727. */
  30728. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30729. /**
  30730. * The SSAO PostProcess id in the pipeline
  30731. * @type {string}
  30732. */
  30733. this.SSAORenderEffect = "SSAORenderEffect";
  30734. /**
  30735. * The horizontal blur PostProcess id in the pipeline
  30736. * @type {string}
  30737. */
  30738. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30739. /**
  30740. * The vertical blur PostProcess id in the pipeline
  30741. * @type {string}
  30742. */
  30743. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30744. /**
  30745. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30746. * @type {string}
  30747. */
  30748. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30749. /**
  30750. * The output strength of the SSAO post-process. Default value is 1.0.
  30751. * @type {number}
  30752. */
  30753. this.totalStrength = 1.0;
  30754. /**
  30755. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30756. * @type {number}
  30757. */
  30758. this.radius = 0.0002;
  30759. /**
  30760. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30761. * Must not be equal to fallOff and superior to fallOff.
  30762. * Default value is 0.0075
  30763. * @type {number}
  30764. */
  30765. this.area = 0.0075;
  30766. /**
  30767. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30768. * Must not be equal to area and inferior to area.
  30769. * Default value is 0.0002
  30770. * @type {number}
  30771. */
  30772. this.fallOff = 0.0002;
  30773. this._firstUpdate = true;
  30774. this._scene = scene;
  30775. // Set up assets
  30776. this._createRandomTexture();
  30777. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30778. var ssaoRatio = ratio.ssaoRatio || ratio;
  30779. var combineRatio = ratio.combineRatio || ratio;
  30780. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30781. this._createSSAOPostProcess(ssaoRatio);
  30782. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30783. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30784. this._createSSAOCombinePostProcess(combineRatio);
  30785. // Set up pipeline
  30786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  30787. return _this._originalColorPostProcess;
  30788. }, true));
  30789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  30790. return _this._ssaoPostProcess;
  30791. }, true));
  30792. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  30793. return _this._blurHPostProcess;
  30794. }, true));
  30795. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  30796. return _this._blurVPostProcess;
  30797. }, true));
  30798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  30799. return _this._ssaoCombinePostProcess;
  30800. }, true));
  30801. // Finish
  30802. scene.postProcessRenderPipelineManager.addPipeline(this);
  30803. if (cameras)
  30804. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30805. }
  30806. // Public Methods
  30807. /**
  30808. * Returns the horizontal blur PostProcess
  30809. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  30810. */
  30811. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  30812. return this._blurHPostProcess;
  30813. };
  30814. /**
  30815. * Returns the vertical blur PostProcess
  30816. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  30817. */
  30818. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  30819. return this._blurVPostProcess;
  30820. };
  30821. /**
  30822. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  30823. */
  30824. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30825. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30826. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30827. this._originalColorPostProcess = undefined;
  30828. this._ssaoPostProcess = undefined;
  30829. this._blurHPostProcess = undefined;
  30830. this._blurVPostProcess = undefined;
  30831. this._ssaoCombinePostProcess = undefined;
  30832. this._randomTexture.dispose();
  30833. if (disableDepthRender)
  30834. this._scene.disableDepthRenderer();
  30835. };
  30836. // Private Methods
  30837. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  30838. var _this = this;
  30839. var sampleSphere = [
  30840. 0.5381,
  30841. 0.1856,
  30842. -0.4319,
  30843. 0.1379,
  30844. 0.2486,
  30845. 0.4430,
  30846. 0.3371,
  30847. 0.5679,
  30848. -0.0057,
  30849. -0.6999,
  30850. -0.0451,
  30851. -0.0019,
  30852. 0.0689,
  30853. -0.1598,
  30854. -0.8547,
  30855. 0.0560,
  30856. 0.0069,
  30857. -0.1843,
  30858. -0.0146,
  30859. 0.1402,
  30860. 0.0762,
  30861. 0.0100,
  30862. -0.1924,
  30863. -0.0344,
  30864. -0.3577,
  30865. -0.5301,
  30866. -0.4358,
  30867. -0.3169,
  30868. 0.1063,
  30869. 0.0158,
  30870. 0.0103,
  30871. -0.5869,
  30872. 0.0046,
  30873. -0.0897,
  30874. -0.4940,
  30875. 0.3287,
  30876. 0.7119,
  30877. -0.0154,
  30878. -0.0918,
  30879. -0.0533,
  30880. 0.0596,
  30881. -0.5411,
  30882. 0.0352,
  30883. -0.0631,
  30884. 0.5460,
  30885. -0.4776,
  30886. 0.2847,
  30887. -0.0271
  30888. ];
  30889. var samplesFactor = 1.0 / 16.0;
  30890. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30891. this._ssaoPostProcess.onApply = function (effect) {
  30892. if (_this._firstUpdate) {
  30893. effect.setArray3("sampleSphere", sampleSphere);
  30894. effect.setFloat("samplesFactor", samplesFactor);
  30895. effect.setFloat("randTextureTiles", 4.0 / ratio);
  30896. _this._firstUpdate = false;
  30897. }
  30898. effect.setFloat("totalStrength", _this.totalStrength);
  30899. effect.setFloat("radius", _this.radius);
  30900. effect.setFloat("area", _this.area);
  30901. effect.setFloat("fallOff", _this.fallOff);
  30902. effect.setTexture("textureSampler", _this._depthTexture);
  30903. effect.setTexture("randomSampler", _this._randomTexture);
  30904. };
  30905. };
  30906. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  30907. var _this = this;
  30908. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30909. this._ssaoCombinePostProcess.onApply = function (effect) {
  30910. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  30911. };
  30912. };
  30913. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  30914. var size = 512;
  30915. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30916. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30917. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30918. var context = this._randomTexture.getContext();
  30919. var rand = function (min, max) {
  30920. return Math.random() * (max - min) + min;
  30921. };
  30922. for (var x = 0; x < size; x++) {
  30923. for (var y = 0; y < size; y++) {
  30924. var randVector = BABYLON.Vector3.Zero();
  30925. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  30926. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  30927. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  30928. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  30929. context.fillRect(x, y, 1, 1);
  30930. }
  30931. }
  30932. this._randomTexture.update(false);
  30933. };
  30934. return SSAORenderingPipeline;
  30935. })(BABYLON.PostProcessRenderPipeline);
  30936. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  30937. })(BABYLON || (BABYLON = {}));
  30938. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  30939. var __extends = this.__extends || function (d, b) {
  30940. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30941. function __() { this.constructor = d; }
  30942. __.prototype = b.prototype;
  30943. d.prototype = new __();
  30944. };
  30945. var BABYLON;
  30946. (function (BABYLON) {
  30947. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  30948. var VolumetricLightScatteringPostProcess = (function (_super) {
  30949. __extends(VolumetricLightScatteringPostProcess, _super);
  30950. /**
  30951. * @constructor
  30952. * @param {string} name - The post-process name
  30953. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  30954. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  30955. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  30956. * @param {number} samples - The post-process quality, default 100
  30957. * @param {number} samplingMode - The post-process filtering mode
  30958. * @param {BABYLON.Engine} engine - The babylon engine
  30959. * @param {boolean} reusable - If the post-process is reusable
  30960. */
  30961. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  30962. var _this = this;
  30963. if (samples === void 0) { samples = 100; }
  30964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  30965. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  30966. this._screenCoordinates = BABYLON.Vector2.Zero();
  30967. /**
  30968. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30969. * @type {boolean}
  30970. */
  30971. this.useCustomMeshPosition = false;
  30972. /**
  30973. * If the post-process should inverse the light scattering direction
  30974. * @type {boolean}
  30975. */
  30976. this.invert = true;
  30977. /**
  30978. * Array containing the excluded meshes not rendered in the internal pass
  30979. */
  30980. this.excludedMeshes = new Array();
  30981. this.exposure = 0.3;
  30982. this.decay = 0.96815;
  30983. this.weight = 0.58767;
  30984. this.density = 0.926;
  30985. var scene = camera.getScene();
  30986. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30987. // Configure mesh
  30988. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30989. // Configure
  30990. this._createPass(scene, ratio.passRatio || ratio);
  30991. this.onApply = function (effect) {
  30992. _this._updateMeshScreenCoordinates(scene);
  30993. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30994. effect.setFloat("exposure", _this.exposure);
  30995. effect.setFloat("decay", _this.decay);
  30996. effect.setFloat("weight", _this.weight);
  30997. effect.setFloat("density", _this.density);
  30998. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30999. };
  31000. }
  31001. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31002. var mesh = subMesh.getMesh();
  31003. var defines = [];
  31004. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31005. var material = subMesh.getMaterial();
  31006. var needUV = false;
  31007. // Render this.mesh as default
  31008. if (mesh === this.mesh) {
  31009. defines.push("#define BASIC_RENDER");
  31010. defines.push("#define NEED_UV");
  31011. needUV = true;
  31012. }
  31013. // Alpha test
  31014. if (material) {
  31015. if (material.needAlphaTesting() || mesh === this.mesh)
  31016. defines.push("#define ALPHATEST");
  31017. if (material.opacityTexture !== undefined) {
  31018. defines.push("#define OPACITY");
  31019. if (material.opacityTexture.getAlphaFromRGB)
  31020. defines.push("#define OPACITYRGB");
  31021. if (!needUV)
  31022. defines.push("#define NEED_UV");
  31023. }
  31024. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31025. attribs.push(BABYLON.VertexBuffer.UVKind);
  31026. defines.push("#define UV1");
  31027. }
  31028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31030. defines.push("#define UV2");
  31031. }
  31032. }
  31033. // Bones
  31034. if (mesh.useBones) {
  31035. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31036. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31037. defines.push("#define BONES");
  31038. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31039. }
  31040. // Instances
  31041. if (useInstances) {
  31042. defines.push("#define INSTANCES");
  31043. attribs.push("world0");
  31044. attribs.push("world1");
  31045. attribs.push("world2");
  31046. attribs.push("world3");
  31047. }
  31048. // Get correct effect
  31049. var join = defines.join("\n");
  31050. if (this._cachedDefines !== join) {
  31051. this._cachedDefines = join;
  31052. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31053. }
  31054. return this._volumetricLightScatteringPass.isReady();
  31055. };
  31056. /**
  31057. * Sets the new light position for light scattering effect
  31058. * @param {BABYLON.Vector3} The new custom light position
  31059. */
  31060. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31061. this._customMeshPosition = position;
  31062. };
  31063. /**
  31064. * Returns the light position for light scattering effect
  31065. * @return {BABYLON.Vector3} The custom light position
  31066. */
  31067. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31068. return this._customMeshPosition;
  31069. };
  31070. /**
  31071. * Disposes the internal assets and detaches the post-process from the camera
  31072. */
  31073. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31074. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31075. if (rttIndex !== -1) {
  31076. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31077. }
  31078. this._volumetricLightScatteringRTT.dispose();
  31079. _super.prototype.dispose.call(this, camera);
  31080. };
  31081. /**
  31082. * Returns the render target texture used by the post-process
  31083. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31084. */
  31085. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31086. return this._volumetricLightScatteringRTT;
  31087. };
  31088. // Private methods
  31089. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31090. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31091. return true;
  31092. }
  31093. return false;
  31094. };
  31095. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31096. var _this = this;
  31097. var engine = scene.getEngine();
  31098. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31099. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31100. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31101. this._volumetricLightScatteringRTT.renderList = null;
  31102. this._volumetricLightScatteringRTT.renderParticles = false;
  31103. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31104. // Custom render function for submeshes
  31105. var renderSubMesh = function (subMesh) {
  31106. var mesh = subMesh.getRenderingMesh();
  31107. if (_this._meshExcluded(mesh)) {
  31108. return;
  31109. }
  31110. var scene = mesh.getScene();
  31111. var engine = scene.getEngine();
  31112. // Culling
  31113. engine.setState(subMesh.getMaterial().backFaceCulling);
  31114. // Managing instances
  31115. var batch = mesh._getInstancesRenderList(subMesh._id);
  31116. if (batch.mustReturn) {
  31117. return;
  31118. }
  31119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31120. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31121. engine.enableEffect(_this._volumetricLightScatteringPass);
  31122. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31123. var material = subMesh.getMaterial();
  31124. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31125. // Alpha test
  31126. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31127. var alphaTexture = material.getAlphaTestTexture();
  31128. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31129. if (alphaTexture) {
  31130. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31131. }
  31132. if (material.opacityTexture !== undefined) {
  31133. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31134. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31135. }
  31136. }
  31137. // Bones
  31138. if (mesh.useBones) {
  31139. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31140. }
  31141. // Draw
  31142. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31143. }
  31144. };
  31145. // Render target texture callbacks
  31146. var savedSceneClearColor;
  31147. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31148. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31149. savedSceneClearColor = scene.clearColor;
  31150. scene.clearColor = sceneClearColor;
  31151. };
  31152. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31153. scene.clearColor = savedSceneClearColor;
  31154. };
  31155. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31156. var engine = scene.getEngine();
  31157. var index;
  31158. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31159. renderSubMesh(opaqueSubMeshes.data[index]);
  31160. }
  31161. engine.setAlphaTesting(true);
  31162. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31163. renderSubMesh(alphaTestSubMeshes.data[index]);
  31164. }
  31165. engine.setAlphaTesting(false);
  31166. if (transparentSubMeshes.length) {
  31167. for (index = 0; index < transparentSubMeshes.length; index++) {
  31168. var submesh = transparentSubMeshes.data[index];
  31169. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31170. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31171. }
  31172. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31173. sortedArray.sort(function (a, b) {
  31174. // Alpha index first
  31175. if (a._alphaIndex > b._alphaIndex) {
  31176. return 1;
  31177. }
  31178. if (a._alphaIndex < b._alphaIndex) {
  31179. return -1;
  31180. }
  31181. // Then distance to camera
  31182. if (a._distanceToCamera < b._distanceToCamera) {
  31183. return 1;
  31184. }
  31185. if (a._distanceToCamera > b._distanceToCamera) {
  31186. return -1;
  31187. }
  31188. return 0;
  31189. });
  31190. // Render sub meshes
  31191. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31192. for (index = 0; index < sortedArray.length; index++) {
  31193. renderSubMesh(sortedArray[index]);
  31194. }
  31195. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31196. }
  31197. };
  31198. };
  31199. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31200. var transform = scene.getTransformMatrix();
  31201. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31202. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31203. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31204. if (this.invert)
  31205. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31206. };
  31207. // Static methods
  31208. /**
  31209. * Creates a default mesh for the Volumeric Light Scattering post-process
  31210. * @param {string} The mesh name
  31211. * @param {BABYLON.Scene} The scene where to create the mesh
  31212. * @return {BABYLON.Mesh} the default mesh
  31213. */
  31214. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31215. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31216. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31217. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31218. return mesh;
  31219. };
  31220. return VolumetricLightScatteringPostProcess;
  31221. })(BABYLON.PostProcess);
  31222. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31223. })(BABYLON || (BABYLON = {}));
  31224. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31225. var __extends = this.__extends || function (d, b) {
  31226. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31227. function __() { this.constructor = d; }
  31228. __.prototype = b.prototype;
  31229. d.prototype = new __();
  31230. };
  31231. var BABYLON;
  31232. (function (BABYLON) {
  31233. var LensRenderingPipeline = (function (_super) {
  31234. __extends(LensRenderingPipeline, _super);
  31235. /**
  31236. * @constructor
  31237. *
  31238. * Effect parameters are as follow:
  31239. * {
  31240. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31241. * edge_blur: number; // from 0 to x (1 for realism)
  31242. * distortion: number; // from 0 to x (1 for realism)
  31243. * grain_amount: number; // from 0 to 1
  31244. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31245. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31246. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31247. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31248. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31249. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31250. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31251. * }
  31252. * Note: if an effect parameter is unset, effect is disabled
  31253. *
  31254. * @param {string} name - The rendering pipeline name
  31255. * @param {object} parameters - An object containing all parameters (see above)
  31256. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31257. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  31258. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31259. */
  31260. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31261. var _this = this;
  31262. if (ratio === void 0) { ratio = 1.0; }
  31263. _super.call(this, scene.getEngine(), name);
  31264. // Lens effects can be of the following:
  31265. // - chromatic aberration (slight shift of RGB colors)
  31266. // - blur on the edge of the lens
  31267. // - lens distortion
  31268. // - depth-of-field blur & highlights enhancing
  31269. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31270. // - grain effect (noise or custom texture)
  31271. // Two additional texture samplers are needed:
  31272. // - depth map (for depth-of-field)
  31273. // - grain texture
  31274. /**
  31275. * The chromatic aberration PostProcess id in the pipeline
  31276. * @type {string}
  31277. */
  31278. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31279. /**
  31280. * The highlights enhancing PostProcess id in the pipeline
  31281. * @type {string}
  31282. */
  31283. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31284. /**
  31285. * The depth-of-field PostProcess id in the pipeline
  31286. * @type {string}
  31287. */
  31288. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31289. this._scene = scene;
  31290. // Fetch texture samplers
  31291. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31292. if (parameters.grain_texture) {
  31293. this._grainTexture = parameters.grain_texture;
  31294. }
  31295. else {
  31296. this._createGrainTexture();
  31297. }
  31298. // save parameters
  31299. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31300. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31301. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31302. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31303. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31304. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31305. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31306. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31307. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31308. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31309. // Create effects
  31310. this._createChromaticAberrationPostProcess(ratio);
  31311. this._createHighlightsPostProcess(ratio);
  31312. this._createDepthOfFieldPostProcess(ratio);
  31313. // Set up pipeline
  31314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31315. return _this._chromaticAberrationPostProcess;
  31316. }, true));
  31317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31318. return _this._highlightsPostProcess;
  31319. }, true));
  31320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31321. return _this._depthOfFieldPostProcess;
  31322. }, true));
  31323. if (this._highlightsGain == -1) {
  31324. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31325. }
  31326. // Finish
  31327. scene.postProcessRenderPipelineManager.addPipeline(this);
  31328. if (cameras) {
  31329. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31330. }
  31331. }
  31332. // public methods (self explanatory)
  31333. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31334. this._edgeBlur = amount;
  31335. };
  31336. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31337. this._edgeBlur = 0;
  31338. };
  31339. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31340. this._grainAmount = amount;
  31341. };
  31342. LensRenderingPipeline.prototype.disableGrain = function () {
  31343. this._grainAmount = 0;
  31344. };
  31345. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31346. this._chromaticAberration = amount;
  31347. };
  31348. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31349. this._chromaticAberration = 0;
  31350. };
  31351. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31352. this._distortion = amount;
  31353. };
  31354. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31355. this._distortion = 0;
  31356. };
  31357. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31358. this._dofDepth = amount;
  31359. };
  31360. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31361. this._dofDepth = -1;
  31362. };
  31363. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31364. this._dofAperture = amount;
  31365. };
  31366. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31367. this._dofPentagon = true;
  31368. };
  31369. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31370. this._dofPentagon = false;
  31371. };
  31372. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31373. this._blurNoise = true;
  31374. };
  31375. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31376. this._blurNoise = false;
  31377. };
  31378. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31379. this._highlightsGain = amount;
  31380. };
  31381. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31382. if (this._highlightsGain == -1) {
  31383. this._highlightsGain = 1.0;
  31384. }
  31385. this._highlightsThreshold = amount;
  31386. };
  31387. LensRenderingPipeline.prototype.disableHighlights = function () {
  31388. this._highlightsGain = -1;
  31389. };
  31390. /**
  31391. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31392. */
  31393. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31394. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31395. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31396. this._chromaticAberrationPostProcess = undefined;
  31397. this._highlightsPostProcess = undefined;
  31398. this._depthOfFieldPostProcess = undefined;
  31399. this._grainTexture.dispose();
  31400. if (disableDepthRender)
  31401. this._scene.disableDepthRenderer();
  31402. };
  31403. // colors shifting and distortion
  31404. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31405. var _this = this;
  31406. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31407. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31408. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31409. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31410. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31411. };
  31412. };
  31413. // highlights enhancing
  31414. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31415. var _this = this;
  31416. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31417. this._highlightsPostProcess.onApply = function (effect) {
  31418. effect.setFloat('gain', _this._highlightsGain);
  31419. effect.setFloat('threshold', _this._highlightsThreshold);
  31420. effect.setBool('pentagon', _this._dofPentagon);
  31421. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31422. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31423. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31424. };
  31425. };
  31426. // colors shifting and distortion
  31427. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31428. var _this = this;
  31429. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31430. "focus_depth",
  31431. "aperture",
  31432. "pentagon",
  31433. "maxZ",
  31434. "edge_blur",
  31435. "chromatic_aberration",
  31436. "distortion",
  31437. "blur_noise",
  31438. "grain_amount",
  31439. "screen_width",
  31440. "screen_height",
  31441. "highlights"
  31442. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31443. this._depthOfFieldPostProcess.onApply = function (effect) {
  31444. effect.setBool('blur_noise', _this._blurNoise);
  31445. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31446. effect.setFloat('grain_amount', _this._grainAmount);
  31447. effect.setTexture("depthSampler", _this._depthTexture);
  31448. effect.setTexture("grainSampler", _this._grainTexture);
  31449. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31450. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31451. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31452. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31453. effect.setFloat('distortion', _this._distortion);
  31454. effect.setFloat('focus_depth', _this._dofDepth);
  31455. effect.setFloat('aperture', _this._dofAperture);
  31456. effect.setFloat('edge_blur', _this._edgeBlur);
  31457. effect.setBool('highlights', (_this._highlightsGain != -1));
  31458. };
  31459. };
  31460. // creates a black and white random noise texture, 512x512
  31461. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31462. var size = 512;
  31463. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31464. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31465. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31466. var context = this._grainTexture.getContext();
  31467. var rand = function (min, max) {
  31468. return Math.random() * (max - min) + min;
  31469. };
  31470. var value;
  31471. for (var x = 0; x < size; x++) {
  31472. for (var y = 0; y < size; y++) {
  31473. value = Math.floor(rand(0.42, 0.58) * 255);
  31474. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31475. context.fillRect(x, y, 1, 1);
  31476. }
  31477. }
  31478. this._grainTexture.update(false);
  31479. };
  31480. return LensRenderingPipeline;
  31481. })(BABYLON.PostProcessRenderPipeline);
  31482. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31483. })(BABYLON || (BABYLON = {}));
  31484. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31485. //
  31486. // This post-process allows the modification of rendered colors by using
  31487. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31488. //
  31489. // The object needs to be provided an url to a texture containing the color
  31490. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31491. // Use an image editing software to tweak the LUT to match your needs.
  31492. //
  31493. // For an example of a color LUT, see here:
  31494. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31495. // For explanations on color grading, see here:
  31496. // http://udn.epicgames.com/Three/ColorGrading.html
  31497. //
  31498. var __extends = this.__extends || function (d, b) {
  31499. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31500. function __() { this.constructor = d; }
  31501. __.prototype = b.prototype;
  31502. d.prototype = new __();
  31503. };
  31504. var BABYLON;
  31505. (function (BABYLON) {
  31506. var ColorCorrectionPostProcess = (function (_super) {
  31507. __extends(ColorCorrectionPostProcess, _super);
  31508. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31509. var _this = this;
  31510. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31511. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31512. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31513. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31514. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31515. this.onApply = function (effect) {
  31516. effect.setTexture("colorTable", _this._colorTableTexture);
  31517. };
  31518. }
  31519. return ColorCorrectionPostProcess;
  31520. })(BABYLON.PostProcess);
  31521. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31522. })(BABYLON || (BABYLON = {}));
  31523. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31524. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","oculusDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  31525. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var i=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=i;var e=function(){function i(i,e,r){this.collider=i,this._collisionCache=e,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return i.prototype.collideWithWorld=function(o,i,e,r){var t=.01;if(this.collider.retry>=e)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,i,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&this.collider._getResponse(o,i),i.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,i,e,r))):void o.addToRef(i,this.finalPosition)},i.prototype.checkCollision=function(i){if(this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var e=o.Matrix.FromArray(i.worldMatrixFromCache);e.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,i)}},i.prototype.processCollisionsForSubMeshes=function(o,i){var e,r;if(r=i.subMeshes,e=r.length,!i.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(i.geometryId);if(!t)return void console.log(\"couldn't find geometry\",i.geometryId);for(var s=0;e>s;s++){var l=r[s];e>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},i.prototype.collideForSubMesh=function(i,e,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!i._lastColliderWorldVertices||!i._lastColliderTransformMatrix.equals(e)){i._lastColliderTransformMatrix=e.clone(),i._lastColliderWorldVertices=[],i._trianglePlanes=[];for(var n=i.verticesStart,a=i.verticesStart+i.verticesCount,t=n;a>t;t++)i._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],e))}this.collider._collide(i._trianglePlanes,i._lastColliderWorldVertices,r.indices,i.indexStart,i.indexStart+i.indexCount,i.verticesStart,i.hasMaterial)},i.prototype.checkSubmeshCollision=function(i){return this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))},i}();o.CollideWorker=e;var r=function(){function r(){}return r.prototype.onInit=function(o){this._collisionCache=new i;var e={error:0,taskType:0};postMessage(e,void 0)},r.prototype.onUpdate=function(o){for(var i in o.updatedGeometries)o.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(o.updatedGeometries[i]);for(var e in o.updatedMeshes)o.updatedMeshes.hasOwnProperty(e)&&this._collisionCache.addMesh(o.updatedMeshes[e]);var r={error:0,taskType:1};postMessage(r,void 0)},r.prototype.onCollision=function(i){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(i.collider.radius);var s=new e(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(i.collider.position),o.Vector3.FromArray(i.collider.velocity),i.maximumRetry,i.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:i.collisionId,newPosition:r.asArray()},n={error:0,taskType:2,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(o){var i=o.data;switch(i.taskType){case 0:t.onInit(i.payload);break;case 2:t.onCollision(i.payload);break;case 1:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var o=(e.WorkerReplyType,function(){function o(){var i=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){i._addUpdateMeshesList[e.uniqueId]=o.SerializeMesh(e)},this.onGeometryUpdated=function(e){i._addUpdateGeometriesList[e.id]=o.SerializeGeometry(e)},this._afterRender=function(){if(i._init&&!(0==i._toRemoveGeometryArray.length&&0==i._toRemoveMeshesArray.length&&0==Object.keys(i._addUpdateGeometriesList).length&&0==Object.keys(i._addUpdateMeshesList).length||i._runningUpdated>4)){++i._runningUpdated;var e={updatedMeshes:i._addUpdateMeshesList,updatedGeometries:i._addUpdateGeometriesList,removedGeometries:i._toRemoveGeometryArray,removedMeshes:i._toRemoveMeshesArray},o={payload:e,taskType:1},t=[];for(var r in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(r)&&(t.push(o.payload.updatedGeometries[r].indices.buffer),t.push(o.payload.updatedGeometries[r].normals.buffer),t.push(o.payload.updatedGeometries[r].positions.buffer));i._worker.postMessage(o,t),i._addUpdateMeshesList={},i._addUpdateGeometriesList={},i._toRemoveGeometryArray=[],i._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(o){var t=o.data;if(0!=t.error)return void e.Tools.Warn(\"error returned from worker!\");switch(t.taskType){case 0:i._init=!0,i._scene.meshes.forEach(function(e){i.onMeshAdded(e)}),i._scene.getGeometries().forEach(function(e){i.onGeometryAdded(e)});break;case 1:i._runningUpdated--;break;case 2:i._runningCollisionTask=!1;var r=t.payload;if(!i._collisionsCallbackArray[r.collisionId])return;i._collisionsCallbackArray[r.collisionId](r.collisionId,e.Vector3.FromArray(r.newPosition),i._scene.getMeshByUniqueID(r.collidedMeshUniqueId)),i._collisionsCallbackArray[r.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){if(this._init&&!this._collisionsCallbackArray[n]&&!this._collisionsCallbackArray[n+1e5]){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),this._collisionsCallbackArray[n]=s;var a={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:i.radius.asArray()},collisionId:n,excludedMeshUniqueId:r?r.uniqueId:null,maximumRetry:t},d={payload:a,taskType:2};this._worker.postMessage(d)}},o.prototype.init=function(o){this._scene=o,this._scene.registerAfterRender(this._afterRender);var i=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(i),this._worker.onmessage=this._onMessageFromWorker;var t={payload:{},taskType:0};this._worker.postMessage(t)},o.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},o.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},o.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},o.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},o.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},o.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.checkCollisions}},o.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},o}());e.CollisionCoordinatorWorker=o;var i=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=i}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function t(t,i){this.x=t,this.y=i}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.addVector3=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y)},t.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},t.prototype.multiply=function(i){return new t(this.x*i.x,this.y*i.y)},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},t.prototype.multiplyByFloats=function(i,o){return new t(this.x*i,this.y*o)},t.prototype.divide=function(i){return new t(this.x/i.x,this.y/i.y)},t.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},t.prototype.negate=function(){return new t(-this.x,-this.y)},t.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},t.prototype.scale=function(i){return new t(this.x*i,this.y*i)},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.Zero=function(){return new t(0,0)},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1])},t.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},t.CatmullRom=function(i,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-i.x+n.x)*s+(2*i.x-5*o.x+4*n.x-r.x)*e+(-i.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-i.y+n.y)*s+(2*i.y-5*o.y+4*n.y-r.y)*e+(-i.y+3*o.y-3*n.y+r.y)*a);return new t(h,u)},t.Clamp=function(i,o,n){var r=i.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=i.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new t(r,s)},t.Hermite=function(i,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=i.x*h+n.x*u+o.x*m+r.x*l,x=i.y*h+n.y*u+o.y*m+r.y*l;return new t(f,x)},t.Lerp=function(i,o,n){var r=i.x+(o.x-i.x)*n,s=i.y+(o.y-i.y)*n;return new t(r,s)},t.Dot=function(t,i){return t.x*i.x+t.y*i.y},t.Normalize=function(t){var i=t.clone();return i.normalize(),i},t.Minimize=function(i,o){var n=i.x<o.x?i.x:o.x,r=i.y<o.y?i.y:o.y;return new t(n,r)},t.Maximize=function(i,o){var n=i.x>o.x?i.x:o.x,r=i.y>o.y?i.y:o.y;return new t(n,r)},t.Transform=function(i,o){var n=i.x*o.m[0]+i.y*o.m[4],r=i.x*o.m[1]+i.y*o.m[5];return new t(n,r)},t.Distance=function(i,o){return Math.sqrt(t.DistanceSquared(i,o))},t.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},t}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),m=SIMD.float32x4.load(n.m,8),l=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,m),l));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),m=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,m)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=t.x*h+n.x*u+o.x*m+r.x*l,x=t.y*h+n.y*u+o.y*m+r.y*l,y=t.z*h+n.z*u+o.z*m+r.z*l;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),l=o.multiply(n).multiply(m);return i.TransformCoordinates(t,l)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),m=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(u=u.scale(1/m)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,i.y=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,i.z=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,i.w=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w,this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,m=o*n,l=i*i,f=o*o,x=l+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-m),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+m)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],m=n[2],l=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(l-u)*o,i.y=(e-m)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(l-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+m)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-m)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+l)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+m)/o,i.y=(u+l)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),m=Math.cos(s),l=Math.sin(e),f=Math.cos(e);n.x=f*u*h+l*m*a,n.y=l*m*h-f*u*a,n.z=f*m*a-l*u*h,n.w=f*m*h+l*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,r=h?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],m=this.m[9],l=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=l*p-f*c,M=m*p-f*y,w=m*c-l*y,d=u*p-f*x,I=u*c-l*x,D=u*y-m*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*l,q=e*f-h*m,E=e*l-a*m,Z=s*f-h*u,V=s*l-a*u,N=s*m-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*E)*R,t.m[7]=(i*L-n*Z+r*V)*R,t.m[11]=-(i*q-o*Z+r*N)*R,t.m[15]=(i*E-o*V+n*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,m,l=this.m,f=t.m,x=SIMD.float32x4.load(l,0),y=SIMD.float32x4.load(l,4),c=SIMD.float32x4.load(l,8),p=SIMD.float32x4.load(l,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),m=SIMD.float32x4.mul(i,e),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,2,3,0,1),m),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,1,0,3,2),m),s=SIMD.float32x4.reciprocalApproximation(m),m=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(m,SIMD.float32x4.mul(s,s))),m=SIMD.float32x4.swizzle(m,0,0,0,0),e=SIMD.float32x4.mul(m,e),a=SIMD.float32x4.mul(m,a),h=SIMD.float32x4.mul(m,h),u=SIMD.float32x4.mul(m,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],m=this.m[7],l=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=n*w+r*S+s*R+e*F,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+m*F,i[o+5]=a*d+h*v+u*_+m*P,i[o+6]=a*I+h*g+u*b+m*C,i[o+7]=a*D+h*T+u*A+m*L,i[o+8]=l*w+f*S+x*R+y*F,i[o+9]=l*d+f*v+x*_+y*P,i[o+10]=l*I+f*g+x*b+y*C,i[o+11]=l*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var l=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){\np.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=m,p.m[11]=l,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=m,z.m[10]=l,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);m=SIMD.float32x4.neg(m);var x=SIMD.float32x4.shuffle(m,l,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(m,l,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,m=t.y,l=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+m,s,1);return o.multiply(n).multiply(r).multiply(l)},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],m=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],l=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,m,l)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,m=s*u-e*h,l=e*a-r*u,f=r*h-s*a,x=Math.sqrt(m*m+l*l+f*f);return n=0!==x?1/x:0,this.normal.x=m*n,this.normal.y=l*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[10]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var l=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o=0,n=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),m=r.Unproject(new r(t,o,1),n,s,e,a,h),l=m.subtract(u);return l.normalize(),new i(u,l)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=l,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var m=h*h,l=m*h,f=s*l+e*m+a*h,x=1/(3*s*m+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=(t.Orientation,function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}());t.Angle=y;var c=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=y.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=y.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=y.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-h?0:1,this.angle=y.FromDegrees(0===this.orientation?h-m:m-h)}return t}();t.Arc2=c;var p=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=p;var z=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),m=new c(a,h,u),l=m.angle.radians()/e;0===m.orientation&&(l*=-1);for(var f=m.startAngle.radians()+l,x=0;e>x;x++){var y=Math.cos(f)*m.radius+m.centerPoint.x,p=Math.sin(f)*m.radius+m.centerPoint.y;this.addLineTo(y,p),f+=l}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),m=u.length()+r;if(o>=r&&m>=o){var l=u.normalize(),f=o-r;return new n(a.x+l.x*f,a.y+l.y*f)}r=m}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=z;var M=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,m=1;i>m;m++)s=this._getLastNonNullVector(m),i-1>m&&(e=this._getFirstNonNullVector(m),this._tangents[m]=s.add(e),this._tangents[m].normalize()),this._distances[m]=this._distances[m-1]+s.length(),a=this._tangents[m],h=this._normals[m-1],u=this._binormals[m-1],this._normals[m]=r.Cross(u,a),this._normals[m].normalize(),this._binormals[m]=r.Cross(a,this._normals[m]),this._binormals[m].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0==o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},t.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0==o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},t.prototype._normalVector=function(t,i,o){var n;if(void 0===o||null===o){var s;1!==i.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=M;var w=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,t.x,o.x,n.x),a(h/s,t.y,o.y,n.y),a(h/s,t.z,o.z,n.z)));return new i(e)},i.CreateCubicBezier=function(t,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,t.x,o.x,n.x,s.x),h(u/e,t.y,o.y,n.y,s.y),h(u/e,t.z,o.z,n.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,n,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,n,r,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new i(n);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=w;var d=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var I=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=I;var D=a.prototype.multiplyToArray,S=a.prototype.invertToRef,v=a.LookAtLHToRef,g=r.TransformCoordinatesToRef,T=r.TransformCoordinatesFromFloatsToRef,R=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=D,a.prototype.invertToRef=S,a.LookAtLHToRef=v,r.TransformCoordinatesToRef=g,r.TransformCoordinatesFromFloatsToRef=T,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=R,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&R.EnableSIMD()}(BABYLON||(BABYLON={}));";