babylon.2.1-beta.debug.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947
  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. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  306. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  307. };
  308. // Properties
  309. Vector2.prototype.length = function () {
  310. return Math.sqrt(this.x * this.x + this.y * this.y);
  311. };
  312. Vector2.prototype.lengthSquared = function () {
  313. return (this.x * this.x + this.y * this.y);
  314. };
  315. // Methods
  316. Vector2.prototype.normalize = function () {
  317. var len = this.length();
  318. if (len === 0)
  319. return this;
  320. var num = 1.0 / len;
  321. this.x *= num;
  322. this.y *= num;
  323. return this;
  324. };
  325. Vector2.prototype.clone = function () {
  326. return new Vector2(this.x, this.y);
  327. };
  328. // Statics
  329. Vector2.Zero = function () {
  330. return new Vector2(0, 0);
  331. };
  332. Vector2.FromArray = function (array, offset) {
  333. if (offset === void 0) { offset = 0; }
  334. return new Vector2(array[offset], array[offset + 1]);
  335. };
  336. Vector2.FromArrayToRef = function (array, offset, result) {
  337. result.x = array[offset];
  338. result.y = array[offset + 1];
  339. };
  340. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  341. var squared = amount * amount;
  342. var cubed = amount * squared;
  343. 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));
  344. 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));
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Clamp = function (value, min, max) {
  348. var x = value.x;
  349. x = (x > max.x) ? max.x : x;
  350. x = (x < min.x) ? min.x : x;
  351. var y = value.y;
  352. y = (y > max.y) ? max.y : y;
  353. y = (y < min.y) ? min.y : y;
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  357. var squared = amount * amount;
  358. var cubed = amount * squared;
  359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  361. var part3 = (cubed - (2.0 * squared)) + amount;
  362. var part4 = cubed - squared;
  363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  365. return new Vector2(x, y);
  366. };
  367. Vector2.Lerp = function (start, end, amount) {
  368. var x = start.x + ((end.x - start.x) * amount);
  369. var y = start.y + ((end.y - start.y) * amount);
  370. return new Vector2(x, y);
  371. };
  372. Vector2.Dot = function (left, right) {
  373. return left.x * right.x + left.y * right.y;
  374. };
  375. Vector2.Normalize = function (vector) {
  376. var newVector = vector.clone();
  377. newVector.normalize();
  378. return newVector;
  379. };
  380. Vector2.Minimize = function (left, right) {
  381. var x = (left.x < right.x) ? left.x : right.x;
  382. var y = (left.y < right.y) ? left.y : right.y;
  383. return new Vector2(x, y);
  384. };
  385. Vector2.Maximize = function (left, right) {
  386. var x = (left.x > right.x) ? left.x : right.x;
  387. var y = (left.y > right.y) ? left.y : right.y;
  388. return new Vector2(x, y);
  389. };
  390. Vector2.Transform = function (vector, transformation) {
  391. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  392. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  393. return new Vector2(x, y);
  394. };
  395. Vector2.Distance = function (value1, value2) {
  396. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  397. };
  398. Vector2.DistanceSquared = function (value1, value2) {
  399. var x = value1.x - value2.x;
  400. var y = value1.y - value2.y;
  401. return (x * x) + (y * y);
  402. };
  403. return Vector2;
  404. })();
  405. BABYLON.Vector2 = Vector2;
  406. var Vector3 = (function () {
  407. function Vector3(x, y, z) {
  408. this.x = x;
  409. this.y = y;
  410. this.z = z;
  411. }
  412. Vector3.prototype.toString = function () {
  413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  414. };
  415. // Operators
  416. Vector3.prototype.asArray = function () {
  417. var result = [];
  418. this.toArray(result, 0);
  419. return result;
  420. };
  421. Vector3.prototype.toArray = function (array, index) {
  422. if (index === void 0) { index = 0; }
  423. array[index] = this.x;
  424. array[index + 1] = this.y;
  425. array[index + 2] = this.z;
  426. return this;
  427. };
  428. Vector3.prototype.toQuaternion = function () {
  429. var result = new Quaternion(0, 0, 0, 1);
  430. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  431. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  432. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  433. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  434. var cosy = Math.cos(this.y * 0.5);
  435. var siny = Math.sin(this.y * 0.5);
  436. result.x = coszMinusx * siny;
  437. result.y = -sinzMinusx * siny;
  438. result.z = sinxPlusz * cosy;
  439. result.w = cosxPlusz * cosy;
  440. return result;
  441. };
  442. Vector3.prototype.addInPlace = function (otherVector) {
  443. this.x += otherVector.x;
  444. this.y += otherVector.y;
  445. this.z += otherVector.z;
  446. return this;
  447. };
  448. Vector3.prototype.add = function (otherVector) {
  449. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  450. };
  451. Vector3.prototype.addToRef = function (otherVector, result) {
  452. result.x = this.x + otherVector.x;
  453. result.y = this.y + otherVector.y;
  454. result.z = this.z + otherVector.z;
  455. return this;
  456. };
  457. Vector3.prototype.subtractInPlace = function (otherVector) {
  458. this.x -= otherVector.x;
  459. this.y -= otherVector.y;
  460. this.z -= otherVector.z;
  461. return this;
  462. };
  463. Vector3.prototype.subtract = function (otherVector) {
  464. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  465. };
  466. Vector3.prototype.subtractToRef = function (otherVector, result) {
  467. result.x = this.x - otherVector.x;
  468. result.y = this.y - otherVector.y;
  469. result.z = this.z - otherVector.z;
  470. return this;
  471. };
  472. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  473. return new Vector3(this.x - x, this.y - y, this.z - z);
  474. };
  475. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  476. result.x = this.x - x;
  477. result.y = this.y - y;
  478. result.z = this.z - z;
  479. return this;
  480. };
  481. Vector3.prototype.negate = function () {
  482. return new Vector3(-this.x, -this.y, -this.z);
  483. };
  484. Vector3.prototype.scaleInPlace = function (scale) {
  485. this.x *= scale;
  486. this.y *= scale;
  487. this.z *= scale;
  488. return this;
  489. };
  490. Vector3.prototype.scale = function (scale) {
  491. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  492. };
  493. Vector3.prototype.scaleToRef = function (scale, result) {
  494. result.x = this.x * scale;
  495. result.y = this.y * scale;
  496. result.z = this.z * scale;
  497. };
  498. Vector3.prototype.equals = function (otherVector) {
  499. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  500. };
  501. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  502. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  503. };
  504. Vector3.prototype.equalsToFloats = function (x, y, z) {
  505. return this.x === x && this.y === y && this.z === z;
  506. };
  507. Vector3.prototype.multiplyInPlace = function (otherVector) {
  508. this.x *= otherVector.x;
  509. this.y *= otherVector.y;
  510. this.z *= otherVector.z;
  511. return this;
  512. };
  513. Vector3.prototype.multiply = function (otherVector) {
  514. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  515. };
  516. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  517. result.x = this.x * otherVector.x;
  518. result.y = this.y * otherVector.y;
  519. result.z = this.z * otherVector.z;
  520. return this;
  521. };
  522. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  523. return new Vector3(this.x * x, this.y * y, this.z * z);
  524. };
  525. Vector3.prototype.divide = function (otherVector) {
  526. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  527. };
  528. Vector3.prototype.divideToRef = function (otherVector, result) {
  529. result.x = this.x / otherVector.x;
  530. result.y = this.y / otherVector.y;
  531. result.z = this.z / otherVector.z;
  532. return this;
  533. };
  534. Vector3.prototype.MinimizeInPlace = function (other) {
  535. if (other.x < this.x)
  536. this.x = other.x;
  537. if (other.y < this.y)
  538. this.y = other.y;
  539. if (other.z < this.z)
  540. this.z = other.z;
  541. return this;
  542. };
  543. Vector3.prototype.MaximizeInPlace = function (other) {
  544. if (other.x > this.x)
  545. this.x = other.x;
  546. if (other.y > this.y)
  547. this.y = other.y;
  548. if (other.z > this.z)
  549. this.z = other.z;
  550. return this;
  551. };
  552. // Properties
  553. Vector3.prototype.length = function () {
  554. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  555. };
  556. Vector3.prototype.lengthSquared = function () {
  557. return (this.x * this.x + this.y * this.y + this.z * this.z);
  558. };
  559. // Methods
  560. Vector3.prototype.normalize = function () {
  561. var len = this.length();
  562. if (len === 0)
  563. return this;
  564. var num = 1.0 / len;
  565. this.x *= num;
  566. this.y *= num;
  567. this.z *= num;
  568. return this;
  569. };
  570. Vector3.prototype.clone = function () {
  571. return new Vector3(this.x, this.y, this.z);
  572. };
  573. Vector3.prototype.copyFrom = function (source) {
  574. this.x = source.x;
  575. this.y = source.y;
  576. this.z = source.z;
  577. return this;
  578. };
  579. Vector3.prototype.copyFromFloats = function (x, y, z) {
  580. this.x = x;
  581. this.y = y;
  582. this.z = z;
  583. return this;
  584. };
  585. // Statics
  586. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  587. var d0 = Vector3.Dot(vector0, axis) - size;
  588. var d1 = Vector3.Dot(vector1, axis) - size;
  589. var s = d0 / (d0 - d1);
  590. return s;
  591. };
  592. Vector3.FromArray = function (array, offset) {
  593. if (!offset) {
  594. offset = 0;
  595. }
  596. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  597. };
  598. Vector3.FromArrayToRef = function (array, offset, result) {
  599. result.x = array[offset];
  600. result.y = array[offset + 1];
  601. result.z = array[offset + 2];
  602. };
  603. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  604. result.x = array[offset];
  605. result.y = array[offset + 1];
  606. result.z = array[offset + 2];
  607. };
  608. Vector3.FromFloatsToRef = function (x, y, z, result) {
  609. result.x = x;
  610. result.y = y;
  611. result.z = z;
  612. };
  613. Vector3.Zero = function () {
  614. return new Vector3(0, 0, 0);
  615. };
  616. Vector3.Up = function () {
  617. return new Vector3(0, 1.0, 0);
  618. };
  619. Vector3.TransformCoordinates = function (vector, transformation) {
  620. var result = Vector3.Zero();
  621. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  622. return result;
  623. };
  624. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  625. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  626. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  627. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  628. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  629. result.x = x / w;
  630. result.y = y / w;
  631. result.z = z / w;
  632. };
  633. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  634. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  635. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  636. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  637. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  638. result.x = rx / rw;
  639. result.y = ry / rw;
  640. result.z = rz / rw;
  641. };
  642. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  643. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  644. var m0 = SIMD.float32x4.load(transformation.m, 0);
  645. var m1 = SIMD.float32x4.load(transformation.m, 4);
  646. var m2 = SIMD.float32x4.load(transformation.m, 8);
  647. var m3 = SIMD.float32x4.load(transformation.m, 12);
  648. 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));
  649. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  650. SIMD.float32x4.storeXYZ(result._data, 0, r);
  651. };
  652. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  653. var v0 = SIMD.float32x4.splat(x);
  654. var v1 = SIMD.float32x4.splat(y);
  655. var v2 = SIMD.float32x4.splat(z);
  656. var m0 = SIMD.float32x4.load(transformation.m, 0);
  657. var m1 = SIMD.float32x4.load(transformation.m, 4);
  658. var m2 = SIMD.float32x4.load(transformation.m, 8);
  659. var m3 = SIMD.float32x4.load(transformation.m, 12);
  660. 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));
  661. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  662. SIMD.float32x4.storeXYZ(result._data, 0, r);
  663. };
  664. Vector3.TransformNormal = function (vector, transformation) {
  665. var result = Vector3.Zero();
  666. Vector3.TransformNormalToRef(vector, transformation, result);
  667. return result;
  668. };
  669. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  670. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  671. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  672. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  673. };
  674. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  675. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  676. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  677. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  678. };
  679. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  680. var squared = amount * amount;
  681. var cubed = amount * squared;
  682. 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));
  683. 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));
  684. 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));
  685. return new Vector3(x, y, z);
  686. };
  687. Vector3.Clamp = function (value, min, max) {
  688. var x = value.x;
  689. x = (x > max.x) ? max.x : x;
  690. x = (x < min.x) ? min.x : x;
  691. var y = value.y;
  692. y = (y > max.y) ? max.y : y;
  693. y = (y < min.y) ? min.y : y;
  694. var z = value.z;
  695. z = (z > max.z) ? max.z : z;
  696. z = (z < min.z) ? min.z : z;
  697. return new Vector3(x, y, z);
  698. };
  699. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  700. var squared = amount * amount;
  701. var cubed = amount * squared;
  702. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  703. var part2 = (-2.0 * cubed) + (3.0 * squared);
  704. var part3 = (cubed - (2.0 * squared)) + amount;
  705. var part4 = cubed - squared;
  706. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  707. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  708. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  709. return new Vector3(x, y, z);
  710. };
  711. Vector3.Lerp = function (start, end, amount) {
  712. var x = start.x + ((end.x - start.x) * amount);
  713. var y = start.y + ((end.y - start.y) * amount);
  714. var z = start.z + ((end.z - start.z) * amount);
  715. return new Vector3(x, y, z);
  716. };
  717. Vector3.Dot = function (left, right) {
  718. return (left.x * right.x + left.y * right.y + left.z * right.z);
  719. };
  720. Vector3.Cross = function (left, right) {
  721. var result = Vector3.Zero();
  722. Vector3.CrossToRef(left, right, result);
  723. return result;
  724. };
  725. Vector3.CrossToRef = function (left, right, result) {
  726. result.x = left.y * right.z - left.z * right.y;
  727. result.y = left.z * right.x - left.x * right.z;
  728. result.z = left.x * right.y - left.y * right.x;
  729. };
  730. Vector3.Normalize = function (vector) {
  731. var result = Vector3.Zero();
  732. Vector3.NormalizeToRef(vector, result);
  733. return result;
  734. };
  735. Vector3.NormalizeToRef = function (vector, result) {
  736. result.copyFrom(vector);
  737. result.normalize();
  738. };
  739. Vector3.Project = function (vector, world, transform, viewport) {
  740. var cw = viewport.width;
  741. var ch = viewport.height;
  742. var cx = viewport.x;
  743. var cy = viewport.y;
  744. 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);
  745. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  746. return Vector3.TransformCoordinates(vector, finalMatrix);
  747. };
  748. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  749. var matrix = world.multiply(transform);
  750. matrix.invert();
  751. source.x = source.x / viewportWidth * 2 - 1;
  752. source.y = -(source.y / viewportHeight * 2 - 1);
  753. var vector = Vector3.TransformCoordinates(source, matrix);
  754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  755. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  756. vector = vector.scale(1.0 / num);
  757. }
  758. return vector;
  759. };
  760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  761. var matrix = world.multiply(view).multiply(projection);
  762. matrix.invert();
  763. source.x = source.x / viewportWidth * 2 - 1;
  764. source.y = -(source.y / viewportHeight * 2 - 1);
  765. var vector = Vector3.TransformCoordinates(source, matrix);
  766. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  767. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  768. vector = vector.scale(1.0 / num);
  769. }
  770. return vector;
  771. };
  772. Vector3.Minimize = function (left, right) {
  773. var min = left.clone();
  774. min.MinimizeInPlace(right);
  775. return min;
  776. };
  777. Vector3.Maximize = function (left, right) {
  778. var max = left.clone();
  779. max.MaximizeInPlace(right);
  780. return max;
  781. };
  782. Vector3.Distance = function (value1, value2) {
  783. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  784. };
  785. Vector3.DistanceSquared = function (value1, value2) {
  786. var x = value1.x - value2.x;
  787. var y = value1.y - value2.y;
  788. var z = value1.z - value2.z;
  789. return (x * x) + (y * y) + (z * z);
  790. };
  791. Vector3.Center = function (value1, value2) {
  792. var center = value1.add(value2);
  793. center.scaleInPlace(0.5);
  794. return center;
  795. };
  796. /**
  797. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  798. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  799. * to something in order to rotate it from its local system to the given target system.
  800. */
  801. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  802. var u = Vector3.Normalize(axis1);
  803. var v = Vector3.Normalize(axis2);
  804. var w = Vector3.Normalize(axis3);
  805. // world axis
  806. var X = Axis.X;
  807. var Y = Axis.Y;
  808. var Z = Axis.Z;
  809. // equation unknowns and vars
  810. var yaw = 0.0;
  811. var pitch = 0.0;
  812. var roll = 0.0;
  813. var x = 0.0;
  814. var y = 0.0;
  815. var z = 0.0;
  816. var t = 0.0;
  817. var sign = -1.0;
  818. var pi = Math.PI;
  819. var nbRevert = 0;
  820. var cross;
  821. var dot = 0.0;
  822. // step 1 : rotation around w
  823. // Rv3(u) = u1, and u1 belongs to plane xOz
  824. // Rv3(w) = w1 = w invariant
  825. var u1;
  826. var v1;
  827. if (w.z == 0) {
  828. z = 1.0;
  829. }
  830. else if (w.x == 0) {
  831. x = 1.0;
  832. }
  833. else {
  834. t = w.z / w.x;
  835. x = -t * Math.sqrt(1 / (1 + t * t));
  836. z = Math.sqrt(1 / (1 + t * t));
  837. }
  838. u1 = new Vector3(x, y, z);
  839. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  840. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  841. if (Vector3.Dot(w, cross) < 0) {
  842. sign = 1;
  843. }
  844. dot = Vector3.Dot(u, u1);
  845. roll = Math.acos(dot) * sign;
  846. if (Vector3.Dot(u1, X) < 0) {
  847. roll = Math.PI + roll;
  848. u1 = u1.scaleInPlace(-1);
  849. v1 = v1.scaleInPlace(-1);
  850. nbRevert++;
  851. }
  852. // step 2 : rotate around u1
  853. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  854. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  855. var w2;
  856. var v2;
  857. x = 0.0;
  858. y = 0.0;
  859. z = 0.0;
  860. sign = -1;
  861. if (w.z == 0) {
  862. x = 1.0;
  863. }
  864. else {
  865. t = u1.z / u1.x;
  866. x = -t * Math.sqrt(1 / (1 + t * t));
  867. z = Math.sqrt(1 / (1 + t * t));
  868. }
  869. w2 = new BABYLON.Vector3(x, y, z);
  870. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  871. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  872. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  873. sign = 1;
  874. }
  875. dot = BABYLON.Vector3.Dot(w, w2);
  876. pitch = Math.acos(dot) * sign;
  877. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  878. pitch = Math.PI + pitch;
  879. v2 = v2.scaleInPlace(-1);
  880. w2 = w2.scaleInPlace(-1);
  881. nbRevert++;
  882. }
  883. // step 3 : rotate around v2
  884. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  885. sign = -1;
  886. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  887. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  888. sign = 1;
  889. }
  890. dot = BABYLON.Vector3.Dot(u1, X);
  891. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  892. if (dot < 0 && nbRevert < 2) {
  893. yaw = Math.PI + yaw;
  894. }
  895. return new BABYLON.Vector3(pitch, yaw, roll);
  896. };
  897. return Vector3;
  898. })();
  899. BABYLON.Vector3 = Vector3;
  900. //Vector4 class created for EulerAngle class conversion to Quaternion
  901. var Vector4 = (function () {
  902. function Vector4(x, y, z, w) {
  903. this.x = x;
  904. this.y = y;
  905. this.z = z;
  906. this.w = w;
  907. }
  908. Vector4.prototype.toString = function () {
  909. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  910. };
  911. // Operators
  912. Vector4.prototype.asArray = function () {
  913. var result = [];
  914. this.toArray(result, 0);
  915. return result;
  916. };
  917. Vector4.prototype.toArray = function (array, index) {
  918. if (index === undefined) {
  919. index = 0;
  920. }
  921. array[index] = this.x;
  922. array[index + 1] = this.y;
  923. array[index + 2] = this.z;
  924. array[index + 3] = this.w;
  925. return this;
  926. };
  927. Vector4.prototype.addInPlace = function (otherVector) {
  928. this.x += otherVector.x;
  929. this.y += otherVector.y;
  930. this.z += otherVector.z;
  931. this.w += otherVector.w;
  932. return this;
  933. };
  934. Vector4.prototype.add = function (otherVector) {
  935. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  936. };
  937. Vector4.prototype.addToRef = function (otherVector, result) {
  938. result.x = this.x + otherVector.x;
  939. result.y = this.y + otherVector.y;
  940. result.z = this.z + otherVector.z;
  941. result.w = this.w + otherVector.w;
  942. return this;
  943. };
  944. Vector4.prototype.subtractInPlace = function (otherVector) {
  945. this.x -= otherVector.x;
  946. this.y -= otherVector.y;
  947. this.z -= otherVector.z;
  948. this.w -= otherVector.w;
  949. return this;
  950. };
  951. Vector4.prototype.subtract = function (otherVector) {
  952. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  953. };
  954. Vector4.prototype.subtractToRef = function (otherVector, result) {
  955. result.x = this.x - otherVector.x;
  956. result.y = this.y - otherVector.y;
  957. result.z = this.z - otherVector.z;
  958. result.w = this.w - otherVector.w;
  959. return this;
  960. };
  961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  963. };
  964. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  965. result.x = this.x - x;
  966. result.y = this.y - y;
  967. result.z = this.z - z;
  968. result.w = this.w - w;
  969. return this;
  970. };
  971. Vector4.prototype.negate = function () {
  972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  973. };
  974. Vector4.prototype.scaleInPlace = function (scale) {
  975. this.x *= scale;
  976. this.y *= scale;
  977. this.z *= scale;
  978. this.w *= scale;
  979. return this;
  980. };
  981. Vector4.prototype.scale = function (scale) {
  982. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  983. };
  984. Vector4.prototype.scaleToRef = function (scale, result) {
  985. result.x = this.x * scale;
  986. result.y = this.y * scale;
  987. result.z = this.z * scale;
  988. result.w = this.w * scale;
  989. };
  990. Vector4.prototype.equals = function (otherVector) {
  991. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  992. };
  993. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  994. 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;
  995. };
  996. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  997. return this.x === x && this.y === y && this.z === z && this.w === w;
  998. };
  999. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1000. this.x *= otherVector.x;
  1001. this.y *= otherVector.y;
  1002. this.z *= otherVector.z;
  1003. this.w *= otherVector.w;
  1004. return this;
  1005. };
  1006. Vector4.prototype.multiply = function (otherVector) {
  1007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1008. };
  1009. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1010. result.x = this.x * otherVector.x;
  1011. result.y = this.y * otherVector.y;
  1012. result.z = this.z * otherVector.z;
  1013. result.w = this.w * otherVector.w;
  1014. return this;
  1015. };
  1016. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1017. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1018. };
  1019. Vector4.prototype.divide = function (otherVector) {
  1020. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1021. };
  1022. Vector4.prototype.divideToRef = function (otherVector, result) {
  1023. result.x = this.x / otherVector.x;
  1024. result.y = this.y / otherVector.y;
  1025. result.z = this.z / otherVector.z;
  1026. result.w = this.w / otherVector.w;
  1027. return this;
  1028. };
  1029. Vector4.prototype.MinimizeInPlace = function (other) {
  1030. if (other.x < this.x)
  1031. this.x = other.x;
  1032. if (other.y < this.y)
  1033. this.y = other.y;
  1034. if (other.z < this.z)
  1035. this.z = other.z;
  1036. if (other.w < this.w)
  1037. this.w = other.w;
  1038. return this;
  1039. };
  1040. Vector4.prototype.MaximizeInPlace = function (other) {
  1041. if (other.x > this.x)
  1042. this.x = other.x;
  1043. if (other.y > this.y)
  1044. this.y = other.y;
  1045. if (other.z > this.z)
  1046. this.z = other.z;
  1047. if (other.w > this.w)
  1048. this.w = other.w;
  1049. return this;
  1050. };
  1051. // Properties
  1052. Vector4.prototype.length = function () {
  1053. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1054. };
  1055. Vector4.prototype.lengthSquared = function () {
  1056. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1057. };
  1058. // Methods
  1059. Vector4.prototype.normalize = function () {
  1060. var len = this.length();
  1061. if (len === 0)
  1062. return this;
  1063. var num = 1.0 / len;
  1064. this.x *= num;
  1065. this.y *= num;
  1066. this.z *= num;
  1067. this.w *= num;
  1068. return this;
  1069. };
  1070. Vector4.prototype.clone = function () {
  1071. return new Vector4(this.x, this.y, this.z, this.w);
  1072. };
  1073. Vector4.prototype.copyFrom = function (source) {
  1074. this.x = source.x;
  1075. this.y = source.y;
  1076. this.z = source.z;
  1077. this.w = source.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1081. this.x = x;
  1082. this.y = y;
  1083. this.z = z;
  1084. this.w = w;
  1085. return this;
  1086. };
  1087. // Statics
  1088. Vector4.FromArray = function (array, offset) {
  1089. if (!offset) {
  1090. offset = 0;
  1091. }
  1092. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1093. };
  1094. Vector4.FromArrayToRef = function (array, offset, result) {
  1095. result.x = array[offset];
  1096. result.y = array[offset + 1];
  1097. result.z = array[offset + 2];
  1098. result.w = array[offset + 3];
  1099. };
  1100. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1101. result.x = array[offset];
  1102. result.y = array[offset + 1];
  1103. result.z = array[offset + 2];
  1104. result.w = array[offset + 3];
  1105. };
  1106. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1107. result.x = x;
  1108. result.y = y;
  1109. result.z = z;
  1110. result.w = w;
  1111. };
  1112. Vector4.Zero = function () {
  1113. return new Vector4(0, 0, 0, 0);
  1114. };
  1115. Vector4.Normalize = function (vector) {
  1116. var result = Vector4.Zero();
  1117. Vector4.NormalizeToRef(vector, result);
  1118. return result;
  1119. };
  1120. Vector4.NormalizeToRef = function (vector, result) {
  1121. result.copyFrom(vector);
  1122. result.normalize();
  1123. };
  1124. Vector4.Minimize = function (left, right) {
  1125. var min = left.clone();
  1126. min.MinimizeInPlace(right);
  1127. return min;
  1128. };
  1129. Vector4.Maximize = function (left, right) {
  1130. var max = left.clone();
  1131. max.MaximizeInPlace(right);
  1132. return max;
  1133. };
  1134. Vector4.Distance = function (value1, value2) {
  1135. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1136. };
  1137. Vector4.DistanceSquared = function (value1, value2) {
  1138. var x = value1.x - value2.x;
  1139. var y = value1.y - value2.y;
  1140. var z = value1.z - value2.z;
  1141. var w = value1.w - value2.w;
  1142. return (x * x) + (y * y) + (z * z) + (w * w);
  1143. };
  1144. Vector4.Center = function (value1, value2) {
  1145. var center = value1.add(value2);
  1146. center.scaleInPlace(0.5);
  1147. return center;
  1148. };
  1149. return Vector4;
  1150. })();
  1151. BABYLON.Vector4 = Vector4;
  1152. var Quaternion = (function () {
  1153. function Quaternion(x, y, z, w) {
  1154. if (x === void 0) { x = 0; }
  1155. if (y === void 0) { y = 0; }
  1156. if (z === void 0) { z = 0; }
  1157. if (w === void 0) { w = 1; }
  1158. this.x = x;
  1159. this.y = y;
  1160. this.z = z;
  1161. this.w = w;
  1162. }
  1163. Quaternion.prototype.toString = function () {
  1164. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1165. };
  1166. Quaternion.prototype.asArray = function () {
  1167. return [this.x, this.y, this.z, this.w];
  1168. };
  1169. Quaternion.prototype.equals = function (otherQuaternion) {
  1170. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1171. };
  1172. Quaternion.prototype.clone = function () {
  1173. return new Quaternion(this.x, this.y, this.z, this.w);
  1174. };
  1175. Quaternion.prototype.copyFrom = function (other) {
  1176. this.x = other.x;
  1177. this.y = other.y;
  1178. this.z = other.z;
  1179. this.w = other.w;
  1180. return this;
  1181. };
  1182. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1183. this.x = x;
  1184. this.y = y;
  1185. this.z = z;
  1186. this.w = w;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.add = function (other) {
  1190. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1191. };
  1192. Quaternion.prototype.subtract = function (other) {
  1193. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1194. };
  1195. Quaternion.prototype.scale = function (value) {
  1196. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1197. };
  1198. Quaternion.prototype.multiply = function (q1) {
  1199. var result = new Quaternion(0, 0, 0, 1.0);
  1200. this.multiplyToRef(q1, result);
  1201. return result;
  1202. };
  1203. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1204. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1205. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1206. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1207. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1208. result.copyFromFloats(x, y, z, w);
  1209. return this;
  1210. };
  1211. Quaternion.prototype.length = function () {
  1212. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1213. };
  1214. Quaternion.prototype.normalize = function () {
  1215. var length = 1.0 / this.length();
  1216. this.x *= length;
  1217. this.y *= length;
  1218. this.z *= length;
  1219. this.w *= length;
  1220. return this;
  1221. };
  1222. Quaternion.prototype.toEulerAngles = function () {
  1223. var result = Vector3.Zero();
  1224. this.toEulerAnglesToRef(result);
  1225. return result;
  1226. };
  1227. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1228. //result is an EulerAngles in the in the z-x-z convention
  1229. var qx = this.x;
  1230. var qy = this.y;
  1231. var qz = this.z;
  1232. var qw = this.w;
  1233. var qxy = qx * qy;
  1234. var qxz = qx * qz;
  1235. var qwy = qw * qy;
  1236. var qwz = qw * qz;
  1237. var qwx = qw * qx;
  1238. var qyz = qy * qz;
  1239. var sqx = qx * qx;
  1240. var sqy = qy * qy;
  1241. var determinant = sqx + sqy;
  1242. if (determinant !== 0.000 && determinant !== 1.000) {
  1243. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1244. result.y = Math.acos(1 - 2 * determinant);
  1245. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1246. }
  1247. else {
  1248. if (determinant === 0.0) {
  1249. result.x = 0.0;
  1250. result.y = 0.0;
  1251. 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)
  1252. }
  1253. else {
  1254. 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)
  1255. result.y = Math.PI;
  1256. result.z = 0.0;
  1257. }
  1258. }
  1259. return this;
  1260. };
  1261. Quaternion.prototype.toRotationMatrix = function (result) {
  1262. var xx = this.x * this.x;
  1263. var yy = this.y * this.y;
  1264. var zz = this.z * this.z;
  1265. var xy = this.x * this.y;
  1266. var zw = this.z * this.w;
  1267. var zx = this.z * this.x;
  1268. var yw = this.y * this.w;
  1269. var yz = this.y * this.z;
  1270. var xw = this.x * this.w;
  1271. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1272. result.m[1] = 2.0 * (xy + zw);
  1273. result.m[2] = 2.0 * (zx - yw);
  1274. result.m[3] = 0;
  1275. result.m[4] = 2.0 * (xy - zw);
  1276. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1277. result.m[6] = 2.0 * (yz + xw);
  1278. result.m[7] = 0;
  1279. result.m[8] = 2.0 * (zx + yw);
  1280. result.m[9] = 2.0 * (yz - xw);
  1281. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1282. result.m[11] = 0;
  1283. result.m[12] = 0;
  1284. result.m[13] = 0;
  1285. result.m[14] = 0;
  1286. result.m[15] = 1.0;
  1287. return this;
  1288. };
  1289. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1290. Quaternion.FromRotationMatrixToRef(matrix, this);
  1291. return this;
  1292. };
  1293. // Statics
  1294. Quaternion.FromRotationMatrix = function (matrix) {
  1295. var result = new Quaternion();
  1296. Quaternion.FromRotationMatrixToRef(matrix, result);
  1297. return result;
  1298. };
  1299. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1300. var data = matrix.m;
  1301. var m11 = data[0], m12 = data[4], m13 = data[8];
  1302. var m21 = data[1], m22 = data[5], m23 = data[9];
  1303. var m31 = data[2], m32 = data[6], m33 = data[10];
  1304. var trace = m11 + m22 + m33;
  1305. var s;
  1306. if (trace > 0) {
  1307. s = 0.5 / Math.sqrt(trace + 1.0);
  1308. result.w = 0.25 / s;
  1309. result.x = (m32 - m23) * s;
  1310. result.y = (m13 - m31) * s;
  1311. result.z = (m21 - m12) * s;
  1312. }
  1313. else if (m11 > m22 && m11 > m33) {
  1314. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1315. result.w = (m32 - m23) / s;
  1316. result.x = 0.25 * s;
  1317. result.y = (m12 + m21) / s;
  1318. result.z = (m13 + m31) / s;
  1319. }
  1320. else if (m22 > m33) {
  1321. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1322. result.w = (m13 - m31) / s;
  1323. result.x = (m12 + m21) / s;
  1324. result.y = 0.25 * s;
  1325. result.z = (m23 + m32) / s;
  1326. }
  1327. else {
  1328. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1329. result.w = (m21 - m12) / s;
  1330. result.x = (m13 + m31) / s;
  1331. result.y = (m23 + m32) / s;
  1332. result.z = 0.25 * s;
  1333. }
  1334. };
  1335. Quaternion.Inverse = function (q) {
  1336. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1337. };
  1338. Quaternion.Identity = function () {
  1339. return new Quaternion(0, 0, 0, 1);
  1340. };
  1341. Quaternion.RotationAxis = function (axis, angle) {
  1342. var result = new Quaternion();
  1343. var sin = Math.sin(angle / 2);
  1344. result.w = Math.cos(angle / 2);
  1345. result.x = axis.x * sin;
  1346. result.y = axis.y * sin;
  1347. result.z = axis.z * sin;
  1348. return result;
  1349. };
  1350. Quaternion.FromArray = function (array, offset) {
  1351. if (!offset) {
  1352. offset = 0;
  1353. }
  1354. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1355. };
  1356. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1357. var result = new Quaternion();
  1358. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1359. return result;
  1360. };
  1361. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1362. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1363. var halfRoll = roll * 0.5;
  1364. var halfPitch = pitch * 0.5;
  1365. var halfYaw = yaw * 0.5;
  1366. var sinRoll = Math.sin(halfRoll);
  1367. var cosRoll = Math.cos(halfRoll);
  1368. var sinPitch = Math.sin(halfPitch);
  1369. var cosPitch = Math.cos(halfPitch);
  1370. var sinYaw = Math.sin(halfYaw);
  1371. var cosYaw = Math.cos(halfYaw);
  1372. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1373. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1374. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1375. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1376. };
  1377. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1378. var result = new Quaternion();
  1379. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1380. return result;
  1381. };
  1382. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1383. // Produces a quaternion from Euler angles in the z-x-z orientation
  1384. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1385. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1386. var halfBeta = beta * 0.5;
  1387. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1388. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1389. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1390. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1391. };
  1392. Quaternion.Slerp = function (left, right, amount) {
  1393. var num2;
  1394. var num3;
  1395. var num = amount;
  1396. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1397. var flag = false;
  1398. if (num4 < 0) {
  1399. flag = true;
  1400. num4 = -num4;
  1401. }
  1402. if (num4 > 0.999999) {
  1403. num3 = 1 - num;
  1404. num2 = flag ? -num : num;
  1405. }
  1406. else {
  1407. var num5 = Math.acos(num4);
  1408. var num6 = (1.0 / Math.sin(num5));
  1409. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1410. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1411. }
  1412. 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));
  1413. };
  1414. return Quaternion;
  1415. })();
  1416. BABYLON.Quaternion = Quaternion;
  1417. var Matrix = (function () {
  1418. function Matrix() {
  1419. this.m = new Float32Array(16);
  1420. }
  1421. // Properties
  1422. Matrix.prototype.isIdentity = function () {
  1423. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1424. return false;
  1425. 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)
  1426. return false;
  1427. return true;
  1428. };
  1429. Matrix.prototype.determinant = function () {
  1430. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1431. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1432. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1433. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1434. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1435. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1436. 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))));
  1437. };
  1438. // Methods
  1439. Matrix.prototype.toArray = function () {
  1440. return this.m;
  1441. };
  1442. Matrix.prototype.asArray = function () {
  1443. return this.toArray();
  1444. };
  1445. Matrix.prototype.invert = function () {
  1446. this.invertToRef(this);
  1447. return this;
  1448. };
  1449. Matrix.prototype.invertToRef = function (other) {
  1450. var l1 = this.m[0];
  1451. var l2 = this.m[1];
  1452. var l3 = this.m[2];
  1453. var l4 = this.m[3];
  1454. var l5 = this.m[4];
  1455. var l6 = this.m[5];
  1456. var l7 = this.m[6];
  1457. var l8 = this.m[7];
  1458. var l9 = this.m[8];
  1459. var l10 = this.m[9];
  1460. var l11 = this.m[10];
  1461. var l12 = this.m[11];
  1462. var l13 = this.m[12];
  1463. var l14 = this.m[13];
  1464. var l15 = this.m[14];
  1465. var l16 = this.m[15];
  1466. var l17 = (l11 * l16) - (l12 * l15);
  1467. var l18 = (l10 * l16) - (l12 * l14);
  1468. var l19 = (l10 * l15) - (l11 * l14);
  1469. var l20 = (l9 * l16) - (l12 * l13);
  1470. var l21 = (l9 * l15) - (l11 * l13);
  1471. var l22 = (l9 * l14) - (l10 * l13);
  1472. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1473. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1474. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1475. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1476. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1477. var l28 = (l7 * l16) - (l8 * l15);
  1478. var l29 = (l6 * l16) - (l8 * l14);
  1479. var l30 = (l6 * l15) - (l7 * l14);
  1480. var l31 = (l5 * l16) - (l8 * l13);
  1481. var l32 = (l5 * l15) - (l7 * l13);
  1482. var l33 = (l5 * l14) - (l6 * l13);
  1483. var l34 = (l7 * l12) - (l8 * l11);
  1484. var l35 = (l6 * l12) - (l8 * l10);
  1485. var l36 = (l6 * l11) - (l7 * l10);
  1486. var l37 = (l5 * l12) - (l8 * l9);
  1487. var l38 = (l5 * l11) - (l7 * l9);
  1488. var l39 = (l5 * l10) - (l6 * l9);
  1489. other.m[0] = l23 * l27;
  1490. other.m[4] = l24 * l27;
  1491. other.m[8] = l25 * l27;
  1492. other.m[12] = l26 * l27;
  1493. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1494. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1495. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1496. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1497. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1498. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1499. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1500. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1501. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1502. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1503. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1504. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1505. return this;
  1506. };
  1507. Matrix.prototype.invertToRefSIMD = function (other) {
  1508. var src = this.m;
  1509. var dest = other.m;
  1510. var row0, row1, row2, row3;
  1511. var tmp1;
  1512. var minor0, minor1, minor2, minor3;
  1513. var det;
  1514. // Load the 4 rows
  1515. var src0 = SIMD.float32x4.load(src, 0);
  1516. var src1 = SIMD.float32x4.load(src, 4);
  1517. var src2 = SIMD.float32x4.load(src, 8);
  1518. var src3 = SIMD.float32x4.load(src, 12);
  1519. // Transpose the source matrix. Sort of. Not a true transpose operation
  1520. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1521. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1522. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1523. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1524. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1525. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1526. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1527. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1528. // This is a true transposition, but it will lead to an incorrect result
  1529. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1530. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1531. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1532. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1533. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1534. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1535. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1536. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1537. // ----
  1538. tmp1 = SIMD.float32x4.mul(row2, row3);
  1539. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1540. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1541. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1542. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1543. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1544. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1545. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1546. // ----
  1547. tmp1 = SIMD.float32x4.mul(row1, row2);
  1548. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1549. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1550. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1551. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1552. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1553. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1554. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1555. // ----
  1556. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1557. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1558. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1559. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1560. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1561. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1562. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1563. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1564. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1565. // ----
  1566. tmp1 = SIMD.float32x4.mul(row0, row1);
  1567. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1568. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1569. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1570. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1571. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1572. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1573. // ----
  1574. tmp1 = SIMD.float32x4.mul(row0, row3);
  1575. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1576. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1577. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1578. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1579. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1580. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1581. // ----
  1582. tmp1 = SIMD.float32x4.mul(row0, row2);
  1583. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1584. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1585. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1586. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1587. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1588. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1589. // Compute determinant
  1590. det = SIMD.float32x4.mul(row0, minor0);
  1591. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1592. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1593. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1594. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1595. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1596. // These shuffles aren't necessary if the faulty transposition is done
  1597. // up at the top of this function.
  1598. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1599. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1600. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1601. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1602. // Compute final values by multiplying with 1/det
  1603. minor0 = SIMD.float32x4.mul(det, minor0);
  1604. minor1 = SIMD.float32x4.mul(det, minor1);
  1605. minor2 = SIMD.float32x4.mul(det, minor2);
  1606. minor3 = SIMD.float32x4.mul(det, minor3);
  1607. SIMD.float32x4.store(dest, 0, minor0);
  1608. SIMD.float32x4.store(dest, 4, minor1);
  1609. SIMD.float32x4.store(dest, 8, minor2);
  1610. SIMD.float32x4.store(dest, 12, minor3);
  1611. return this;
  1612. };
  1613. Matrix.prototype.setTranslation = function (vector3) {
  1614. this.m[12] = vector3.x;
  1615. this.m[13] = vector3.y;
  1616. this.m[14] = vector3.z;
  1617. return this;
  1618. };
  1619. Matrix.prototype.multiply = function (other) {
  1620. var result = new Matrix();
  1621. this.multiplyToRef(other, result);
  1622. return result;
  1623. };
  1624. Matrix.prototype.copyFrom = function (other) {
  1625. for (var index = 0; index < 16; index++) {
  1626. this.m[index] = other.m[index];
  1627. }
  1628. return this;
  1629. };
  1630. Matrix.prototype.copyToArray = function (array, offset) {
  1631. if (offset === void 0) { offset = 0; }
  1632. for (var index = 0; index < 16; index++) {
  1633. array[offset + index] = this.m[index];
  1634. }
  1635. return this;
  1636. };
  1637. Matrix.prototype.multiplyToRef = function (other, result) {
  1638. this.multiplyToArray(other, result.m, 0);
  1639. return this;
  1640. };
  1641. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1642. var tm0 = this.m[0];
  1643. var tm1 = this.m[1];
  1644. var tm2 = this.m[2];
  1645. var tm3 = this.m[3];
  1646. var tm4 = this.m[4];
  1647. var tm5 = this.m[5];
  1648. var tm6 = this.m[6];
  1649. var tm7 = this.m[7];
  1650. var tm8 = this.m[8];
  1651. var tm9 = this.m[9];
  1652. var tm10 = this.m[10];
  1653. var tm11 = this.m[11];
  1654. var tm12 = this.m[12];
  1655. var tm13 = this.m[13];
  1656. var tm14 = this.m[14];
  1657. var tm15 = this.m[15];
  1658. var om0 = other.m[0];
  1659. var om1 = other.m[1];
  1660. var om2 = other.m[2];
  1661. var om3 = other.m[3];
  1662. var om4 = other.m[4];
  1663. var om5 = other.m[5];
  1664. var om6 = other.m[6];
  1665. var om7 = other.m[7];
  1666. var om8 = other.m[8];
  1667. var om9 = other.m[9];
  1668. var om10 = other.m[10];
  1669. var om11 = other.m[11];
  1670. var om12 = other.m[12];
  1671. var om13 = other.m[13];
  1672. var om14 = other.m[14];
  1673. var om15 = other.m[15];
  1674. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1675. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1676. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1677. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1678. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1679. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1680. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1681. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1682. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1683. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1684. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1685. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1686. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1687. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1688. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1689. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1690. return this;
  1691. };
  1692. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1693. if (offset === void 0) { offset = 0; }
  1694. var tm = this.m;
  1695. var om = other.m;
  1696. var om0 = SIMD.float32x4.load(om, 0);
  1697. var om1 = SIMD.float32x4.load(om, 4);
  1698. var om2 = SIMD.float32x4.load(om, 8);
  1699. var om3 = SIMD.float32x4.load(om, 12);
  1700. var tm0 = SIMD.float32x4.load(tm, 0);
  1701. 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)))));
  1702. var tm1 = SIMD.float32x4.load(tm, 4);
  1703. 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)))));
  1704. var tm2 = SIMD.float32x4.load(tm, 8);
  1705. 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)))));
  1706. var tm3 = SIMD.float32x4.load(tm, 12);
  1707. 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)))));
  1708. };
  1709. Matrix.prototype.equals = function (value) {
  1710. 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]);
  1711. };
  1712. Matrix.prototype.clone = function () {
  1713. 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]);
  1714. };
  1715. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1716. translation.x = this.m[12];
  1717. translation.y = this.m[13];
  1718. translation.z = this.m[14];
  1719. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1720. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1721. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1722. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1723. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1724. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1725. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1726. rotation.x = 0;
  1727. rotation.y = 0;
  1728. rotation.z = 0;
  1729. rotation.w = 1;
  1730. return false;
  1731. }
  1732. 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);
  1733. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1734. return true;
  1735. };
  1736. // Statics
  1737. Matrix.FromArray = function (array, offset) {
  1738. var result = new Matrix();
  1739. if (!offset) {
  1740. offset = 0;
  1741. }
  1742. Matrix.FromArrayToRef(array, offset, result);
  1743. return result;
  1744. };
  1745. Matrix.FromArrayToRef = function (array, offset, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset];
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var s = Math.sin(-angle);
  1887. var c = Math.cos(-angle);
  1888. var c1 = 1 - c;
  1889. axis.normalize();
  1890. var result = Matrix.Zero();
  1891. result.m[0] = (axis.x * axis.x) * c1 + c;
  1892. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1893. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1894. result.m[3] = 0.0;
  1895. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1896. result.m[5] = (axis.y * axis.y) * c1 + c;
  1897. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1898. result.m[7] = 0.0;
  1899. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1900. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1901. result.m[10] = (axis.z * axis.z) * c1 + c;
  1902. result.m[11] = 0.0;
  1903. result.m[15] = 1.0;
  1904. return result;
  1905. };
  1906. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1907. var result = new Matrix();
  1908. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1909. return result;
  1910. };
  1911. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1912. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1913. this._tempQuaternion.toRotationMatrix(result);
  1914. };
  1915. Matrix.Scaling = function (x, y, z) {
  1916. var result = Matrix.Zero();
  1917. Matrix.ScalingToRef(x, y, z, result);
  1918. return result;
  1919. };
  1920. Matrix.ScalingToRef = function (x, y, z, result) {
  1921. result.m[0] = x;
  1922. result.m[1] = 0;
  1923. result.m[2] = 0;
  1924. result.m[3] = 0;
  1925. result.m[4] = 0;
  1926. result.m[5] = y;
  1927. result.m[6] = 0;
  1928. result.m[7] = 0;
  1929. result.m[8] = 0;
  1930. result.m[9] = 0;
  1931. result.m[10] = z;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. result.m[15] = 1.0;
  1937. };
  1938. Matrix.Translation = function (x, y, z) {
  1939. var result = Matrix.Identity();
  1940. Matrix.TranslationToRef(x, y, z, result);
  1941. return result;
  1942. };
  1943. Matrix.TranslationToRef = function (x, y, z, result) {
  1944. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1945. };
  1946. Matrix.LookAtLH = function (eye, target, up) {
  1947. var result = Matrix.Zero();
  1948. Matrix.LookAtLHToRef(eye, target, up, result);
  1949. return result;
  1950. };
  1951. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1952. // Z axis
  1953. target.subtractToRef(eye, this._zAxis);
  1954. this._zAxis.normalize();
  1955. // X axis
  1956. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1957. this._xAxis.normalize();
  1958. // Y axis
  1959. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1960. this._yAxis.normalize();
  1961. // Eye angles
  1962. var ex = -Vector3.Dot(this._xAxis, eye);
  1963. var ey = -Vector3.Dot(this._yAxis, eye);
  1964. var ez = -Vector3.Dot(this._zAxis, eye);
  1965. 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);
  1966. };
  1967. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1968. var out = result.m;
  1969. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1970. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1971. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1972. // cc.kmVec3Subtract(f, pCenter, pEye);
  1973. var f = SIMD.float32x4.sub(center, eye);
  1974. // cc.kmVec3Normalize(f, f);
  1975. var tmp = SIMD.float32x4.mul(f, f);
  1976. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1977. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1978. // cc.kmVec3Assign(up, pUp);
  1979. // cc.kmVec3Normalize(up, up);
  1980. tmp = SIMD.float32x4.mul(up, up);
  1981. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1982. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1983. // cc.kmVec3Cross(s, f, up);
  1984. 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)));
  1985. // cc.kmVec3Normalize(s, s);
  1986. tmp = SIMD.float32x4.mul(s, s);
  1987. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1988. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1989. // cc.kmVec3Cross(u, s, f);
  1990. 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)));
  1991. // cc.kmVec3Normalize(s, s);
  1992. tmp = SIMD.float32x4.mul(s, s);
  1993. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1994. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1995. var zero = SIMD.float32x4.splat(0.0);
  1996. s = SIMD.float32x4.neg(s);
  1997. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1998. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1999. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2000. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2001. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2002. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2003. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2004. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2005. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2006. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2007. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2008. var b3 = SIMD.float32x4.neg(eye);
  2009. b3 = SIMD.float32x4.withW(b3, 1.0);
  2010. 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)))));
  2011. 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)))));
  2012. 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)))));
  2013. 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)))));
  2014. };
  2015. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2016. var matrix = Matrix.Zero();
  2017. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2018. return matrix;
  2019. };
  2020. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2021. var hw = 2.0 / width;
  2022. var hh = 2.0 / height;
  2023. var id = 1.0 / (zfar - znear);
  2024. var nid = znear / (znear - zfar);
  2025. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2026. };
  2027. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2028. var matrix = Matrix.Zero();
  2029. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2030. return matrix;
  2031. };
  2032. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2033. result.m[0] = 2.0 / (right - left);
  2034. result.m[1] = result.m[2] = result.m[3] = 0;
  2035. result.m[5] = 2.0 / (top - bottom);
  2036. result.m[4] = result.m[6] = result.m[7] = 0;
  2037. result.m[10] = -1.0 / (znear - zfar);
  2038. result.m[8] = result.m[9] = result.m[11] = 0;
  2039. result.m[12] = (left + right) / (left - right);
  2040. result.m[13] = (top + bottom) / (bottom - top);
  2041. result.m[14] = znear / (znear - zfar);
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2045. var matrix = Matrix.Zero();
  2046. matrix.m[0] = (2.0 * znear) / width;
  2047. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2048. matrix.m[5] = (2.0 * znear) / height;
  2049. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2050. matrix.m[10] = -zfar / (znear - zfar);
  2051. matrix.m[8] = matrix.m[9] = 0.0;
  2052. matrix.m[11] = 1.0;
  2053. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2054. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2055. return matrix;
  2056. };
  2057. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2058. var matrix = Matrix.Zero();
  2059. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2060. return matrix;
  2061. };
  2062. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2063. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2064. var tan = 1.0 / (Math.tan(fov * 0.5));
  2065. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2066. if (v_fixed) {
  2067. result.m[0] = tan / aspect;
  2068. }
  2069. else {
  2070. result.m[0] = tan;
  2071. }
  2072. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2073. if (v_fixed) {
  2074. result.m[5] = tan;
  2075. }
  2076. else {
  2077. result.m[5] = tan * aspect;
  2078. }
  2079. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2080. result.m[8] = result.m[9] = 0.0;
  2081. result.m[10] = -zfar / (znear - zfar);
  2082. result.m[11] = 1.0;
  2083. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2084. result.m[14] = (znear * zfar) / (znear - zfar);
  2085. };
  2086. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2087. var cw = viewport.width;
  2088. var ch = viewport.height;
  2089. var cx = viewport.x;
  2090. var cy = viewport.y;
  2091. 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);
  2092. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2093. };
  2094. Matrix.Transpose = function (matrix) {
  2095. var result = new Matrix();
  2096. result.m[0] = matrix.m[0];
  2097. result.m[1] = matrix.m[4];
  2098. result.m[2] = matrix.m[8];
  2099. result.m[3] = matrix.m[12];
  2100. result.m[4] = matrix.m[1];
  2101. result.m[5] = matrix.m[5];
  2102. result.m[6] = matrix.m[9];
  2103. result.m[7] = matrix.m[13];
  2104. result.m[8] = matrix.m[2];
  2105. result.m[9] = matrix.m[6];
  2106. result.m[10] = matrix.m[10];
  2107. result.m[11] = matrix.m[14];
  2108. result.m[12] = matrix.m[3];
  2109. result.m[13] = matrix.m[7];
  2110. result.m[14] = matrix.m[11];
  2111. result.m[15] = matrix.m[15];
  2112. return result;
  2113. };
  2114. Matrix.Reflection = function (plane) {
  2115. var matrix = new Matrix();
  2116. Matrix.ReflectionToRef(plane, matrix);
  2117. return matrix;
  2118. };
  2119. Matrix.ReflectionToRef = function (plane, result) {
  2120. plane.normalize();
  2121. var x = plane.normal.x;
  2122. var y = plane.normal.y;
  2123. var z = plane.normal.z;
  2124. var temp = -2 * x;
  2125. var temp2 = -2 * y;
  2126. var temp3 = -2 * z;
  2127. result.m[0] = (temp * x) + 1;
  2128. result.m[1] = temp2 * x;
  2129. result.m[2] = temp3 * x;
  2130. result.m[3] = 0.0;
  2131. result.m[4] = temp * y;
  2132. result.m[5] = (temp2 * y) + 1;
  2133. result.m[6] = temp3 * y;
  2134. result.m[7] = 0.0;
  2135. result.m[8] = temp * z;
  2136. result.m[9] = temp2 * z;
  2137. result.m[10] = (temp3 * z) + 1;
  2138. result.m[11] = 0.0;
  2139. result.m[12] = temp * plane.d;
  2140. result.m[13] = temp2 * plane.d;
  2141. result.m[14] = temp3 * plane.d;
  2142. result.m[15] = 1.0;
  2143. };
  2144. Matrix._tempQuaternion = new Quaternion();
  2145. Matrix._xAxis = Vector3.Zero();
  2146. Matrix._yAxis = Vector3.Zero();
  2147. Matrix._zAxis = Vector3.Zero();
  2148. return Matrix;
  2149. })();
  2150. BABYLON.Matrix = Matrix;
  2151. var Plane = (function () {
  2152. function Plane(a, b, c, d) {
  2153. this.normal = new Vector3(a, b, c);
  2154. this.d = d;
  2155. }
  2156. Plane.prototype.asArray = function () {
  2157. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2158. };
  2159. // Methods
  2160. Plane.prototype.clone = function () {
  2161. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2162. };
  2163. Plane.prototype.normalize = function () {
  2164. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2165. var magnitude = 0;
  2166. if (norm !== 0) {
  2167. magnitude = 1.0 / norm;
  2168. }
  2169. this.normal.x *= magnitude;
  2170. this.normal.y *= magnitude;
  2171. this.normal.z *= magnitude;
  2172. this.d *= magnitude;
  2173. return this;
  2174. };
  2175. Plane.prototype.transform = function (transformation) {
  2176. var transposedMatrix = Matrix.Transpose(transformation);
  2177. var x = this.normal.x;
  2178. var y = this.normal.y;
  2179. var z = this.normal.z;
  2180. var d = this.d;
  2181. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2182. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2183. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2184. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2185. return new Plane(normalX, normalY, normalZ, finalD);
  2186. };
  2187. Plane.prototype.dotCoordinate = function (point) {
  2188. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2189. };
  2190. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2191. var x1 = point2.x - point1.x;
  2192. var y1 = point2.y - point1.y;
  2193. var z1 = point2.z - point1.z;
  2194. var x2 = point3.x - point1.x;
  2195. var y2 = point3.y - point1.y;
  2196. var z2 = point3.z - point1.z;
  2197. var yz = (y1 * z2) - (z1 * y2);
  2198. var xz = (z1 * x2) - (x1 * z2);
  2199. var xy = (x1 * y2) - (y1 * x2);
  2200. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2201. var invPyth;
  2202. if (pyth !== 0) {
  2203. invPyth = 1.0 / pyth;
  2204. }
  2205. else {
  2206. invPyth = 0;
  2207. }
  2208. this.normal.x = yz * invPyth;
  2209. this.normal.y = xz * invPyth;
  2210. this.normal.z = xy * invPyth;
  2211. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2212. return this;
  2213. };
  2214. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2215. var dot = Vector3.Dot(this.normal, direction);
  2216. return (dot <= epsilon);
  2217. };
  2218. Plane.prototype.signedDistanceTo = function (point) {
  2219. return Vector3.Dot(point, this.normal) + this.d;
  2220. };
  2221. // Statics
  2222. Plane.FromArray = function (array) {
  2223. return new Plane(array[0], array[1], array[2], array[3]);
  2224. };
  2225. Plane.FromPoints = function (point1, point2, point3) {
  2226. var result = new Plane(0, 0, 0, 0);
  2227. result.copyFromPoints(point1, point2, point3);
  2228. return result;
  2229. };
  2230. Plane.FromPositionAndNormal = function (origin, normal) {
  2231. var result = new Plane(0, 0, 0, 0);
  2232. normal.normalize();
  2233. result.normal = normal;
  2234. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2235. return result;
  2236. };
  2237. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2238. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2239. return Vector3.Dot(point, normal) + d;
  2240. };
  2241. return Plane;
  2242. })();
  2243. BABYLON.Plane = Plane;
  2244. var Viewport = (function () {
  2245. function Viewport(x, y, width, height) {
  2246. this.x = x;
  2247. this.y = y;
  2248. this.width = width;
  2249. this.height = height;
  2250. }
  2251. Viewport.prototype.toGlobal = function (engine) {
  2252. var width = engine.getRenderWidth();
  2253. var height = engine.getRenderHeight();
  2254. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2255. };
  2256. return Viewport;
  2257. })();
  2258. BABYLON.Viewport = Viewport;
  2259. var Frustum = (function () {
  2260. function Frustum() {
  2261. }
  2262. Frustum.GetPlanes = function (transform) {
  2263. var frustumPlanes = [];
  2264. for (var index = 0; index < 6; index++) {
  2265. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2266. }
  2267. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2268. return frustumPlanes;
  2269. };
  2270. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2271. // Near
  2272. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2273. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2274. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2275. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2276. frustumPlanes[0].normalize();
  2277. // Far
  2278. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2279. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2280. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2281. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2282. frustumPlanes[1].normalize();
  2283. // Left
  2284. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2285. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2286. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2287. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2288. frustumPlanes[2].normalize();
  2289. // Right
  2290. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2291. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2292. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2293. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2294. frustumPlanes[3].normalize();
  2295. // Top
  2296. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2297. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2298. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2299. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2300. frustumPlanes[4].normalize();
  2301. // Bottom
  2302. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2303. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2304. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2305. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2306. frustumPlanes[5].normalize();
  2307. };
  2308. return Frustum;
  2309. })();
  2310. BABYLON.Frustum = Frustum;
  2311. var Ray = (function () {
  2312. function Ray(origin, direction, length) {
  2313. if (length === void 0) { length = Number.MAX_VALUE; }
  2314. this.origin = origin;
  2315. this.direction = direction;
  2316. this.length = length;
  2317. }
  2318. // Methods
  2319. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2320. var d = 0.0;
  2321. var maxValue = Number.MAX_VALUE;
  2322. if (Math.abs(this.direction.x) < 0.0000001) {
  2323. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2324. return false;
  2325. }
  2326. }
  2327. else {
  2328. var inv = 1.0 / this.direction.x;
  2329. var min = (minimum.x - this.origin.x) * inv;
  2330. var max = (maximum.x - this.origin.x) * inv;
  2331. if (max === -Infinity) {
  2332. max = Infinity;
  2333. }
  2334. if (min > max) {
  2335. var temp = min;
  2336. min = max;
  2337. max = temp;
  2338. }
  2339. d = Math.max(min, d);
  2340. maxValue = Math.min(max, maxValue);
  2341. if (d > maxValue) {
  2342. return false;
  2343. }
  2344. }
  2345. if (Math.abs(this.direction.y) < 0.0000001) {
  2346. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2347. return false;
  2348. }
  2349. }
  2350. else {
  2351. inv = 1.0 / this.direction.y;
  2352. min = (minimum.y - this.origin.y) * inv;
  2353. max = (maximum.y - this.origin.y) * inv;
  2354. if (max === -Infinity) {
  2355. max = Infinity;
  2356. }
  2357. if (min > max) {
  2358. temp = min;
  2359. min = max;
  2360. max = temp;
  2361. }
  2362. d = Math.max(min, d);
  2363. maxValue = Math.min(max, maxValue);
  2364. if (d > maxValue) {
  2365. return false;
  2366. }
  2367. }
  2368. if (Math.abs(this.direction.z) < 0.0000001) {
  2369. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2370. return false;
  2371. }
  2372. }
  2373. else {
  2374. inv = 1.0 / this.direction.z;
  2375. min = (minimum.z - this.origin.z) * inv;
  2376. max = (maximum.z - this.origin.z) * inv;
  2377. if (max === -Infinity) {
  2378. max = Infinity;
  2379. }
  2380. if (min > max) {
  2381. temp = min;
  2382. min = max;
  2383. max = temp;
  2384. }
  2385. d = Math.max(min, d);
  2386. maxValue = Math.min(max, maxValue);
  2387. if (d > maxValue) {
  2388. return false;
  2389. }
  2390. }
  2391. return true;
  2392. };
  2393. Ray.prototype.intersectsBox = function (box) {
  2394. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2395. };
  2396. Ray.prototype.intersectsSphere = function (sphere) {
  2397. var x = sphere.center.x - this.origin.x;
  2398. var y = sphere.center.y - this.origin.y;
  2399. var z = sphere.center.z - this.origin.z;
  2400. var pyth = (x * x) + (y * y) + (z * z);
  2401. var rr = sphere.radius * sphere.radius;
  2402. if (pyth <= rr) {
  2403. return true;
  2404. }
  2405. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2406. if (dot < 0.0) {
  2407. return false;
  2408. }
  2409. var temp = pyth - (dot * dot);
  2410. return temp <= rr;
  2411. };
  2412. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2413. if (!this._edge1) {
  2414. this._edge1 = Vector3.Zero();
  2415. this._edge2 = Vector3.Zero();
  2416. this._pvec = Vector3.Zero();
  2417. this._tvec = Vector3.Zero();
  2418. this._qvec = Vector3.Zero();
  2419. }
  2420. vertex1.subtractToRef(vertex0, this._edge1);
  2421. vertex2.subtractToRef(vertex0, this._edge2);
  2422. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2423. var det = Vector3.Dot(this._edge1, this._pvec);
  2424. if (det === 0) {
  2425. return null;
  2426. }
  2427. var invdet = 1 / det;
  2428. this.origin.subtractToRef(vertex0, this._tvec);
  2429. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2430. if (bu < 0 || bu > 1.0) {
  2431. return null;
  2432. }
  2433. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2434. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2435. if (bv < 0 || bu + bv > 1.0) {
  2436. return null;
  2437. }
  2438. //check if the distance is longer than the predefined length.
  2439. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2440. if (distance > this.length) {
  2441. return null;
  2442. }
  2443. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2444. };
  2445. // Statics
  2446. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2447. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2448. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2449. var direction = end.subtract(start);
  2450. direction.normalize();
  2451. return new Ray(start, direction);
  2452. };
  2453. /**
  2454. * 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
  2455. * transformed to the given world matrix.
  2456. * @param origin The origin point
  2457. * @param end The end point
  2458. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2459. */
  2460. Ray.CreateNewFromTo = function (origin, end, world) {
  2461. if (world === void 0) { world = Matrix.Identity(); }
  2462. var direction = end.subtract(origin);
  2463. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2464. direction.normalize();
  2465. return Ray.Transform(new Ray(origin, direction, length), world);
  2466. };
  2467. Ray.Transform = function (ray, matrix) {
  2468. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2469. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2470. return new Ray(newOrigin, newDirection, ray.length);
  2471. };
  2472. return Ray;
  2473. })();
  2474. BABYLON.Ray = Ray;
  2475. (function (Space) {
  2476. Space[Space["LOCAL"] = 0] = "LOCAL";
  2477. Space[Space["WORLD"] = 1] = "WORLD";
  2478. })(BABYLON.Space || (BABYLON.Space = {}));
  2479. var Space = BABYLON.Space;
  2480. var Axis = (function () {
  2481. function Axis() {
  2482. }
  2483. Axis.X = new Vector3(1, 0, 0);
  2484. Axis.Y = new Vector3(0, 1, 0);
  2485. Axis.Z = new Vector3(0, 0, 1);
  2486. return Axis;
  2487. })();
  2488. BABYLON.Axis = Axis;
  2489. ;
  2490. var BezierCurve = (function () {
  2491. function BezierCurve() {
  2492. }
  2493. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2494. // Extract X (which is equal to time here)
  2495. var f0 = 1 - 3 * x2 + 3 * x1;
  2496. var f1 = 3 * x2 - 6 * x1;
  2497. var f2 = 3 * x1;
  2498. var refinedT = t;
  2499. for (var i = 0; i < 5; i++) {
  2500. var refinedT2 = refinedT * refinedT;
  2501. var refinedT3 = refinedT2 * refinedT;
  2502. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2503. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2504. refinedT -= (x - t) * slope;
  2505. refinedT = Math.min(1, Math.max(0, refinedT));
  2506. }
  2507. // Resolve cubic bezier for the given x
  2508. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2509. };
  2510. return BezierCurve;
  2511. })();
  2512. BABYLON.BezierCurve = BezierCurve;
  2513. (function (Orientation) {
  2514. Orientation[Orientation["CW"] = 0] = "CW";
  2515. Orientation[Orientation["CCW"] = 1] = "CCW";
  2516. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2517. var Orientation = BABYLON.Orientation;
  2518. var Angle = (function () {
  2519. function Angle(radians) {
  2520. var _this = this;
  2521. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2522. this.radians = function () { return _this._radians; };
  2523. this._radians = radians;
  2524. if (this._radians < 0)
  2525. this._radians += (2 * Math.PI);
  2526. }
  2527. Angle.BetweenTwoPoints = function (a, b) {
  2528. var delta = b.subtract(a);
  2529. var theta = Math.atan2(delta.y, delta.x);
  2530. return new Angle(theta);
  2531. };
  2532. Angle.FromRadians = function (radians) {
  2533. return new Angle(radians);
  2534. };
  2535. Angle.FromDegrees = function (degrees) {
  2536. return new Angle(degrees * Math.PI / 180);
  2537. };
  2538. return Angle;
  2539. })();
  2540. BABYLON.Angle = Angle;
  2541. var Arc2 = (function () {
  2542. function Arc2(startPoint, midPoint, endPoint) {
  2543. this.startPoint = startPoint;
  2544. this.midPoint = midPoint;
  2545. this.endPoint = endPoint;
  2546. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2547. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2548. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2549. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2550. 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);
  2551. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2552. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2553. var a1 = this.startAngle.degrees();
  2554. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2555. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2556. // angles correction
  2557. if (a2 - a1 > +180.0)
  2558. a2 -= 360.0;
  2559. if (a2 - a1 < -180.0)
  2560. a2 += 360.0;
  2561. if (a3 - a2 > +180.0)
  2562. a3 -= 360.0;
  2563. if (a3 - a2 < -180.0)
  2564. a3 += 360.0;
  2565. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2566. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2567. }
  2568. return Arc2;
  2569. })();
  2570. BABYLON.Arc2 = Arc2;
  2571. var PathCursor = (function () {
  2572. function PathCursor(path) {
  2573. this.path = path;
  2574. this._onchange = new Array();
  2575. this.value = 0;
  2576. this.animations = new Array();
  2577. }
  2578. PathCursor.prototype.getPoint = function () {
  2579. var point = this.path.getPointAtLengthPosition(this.value);
  2580. return new Vector3(point.x, 0, point.y);
  2581. };
  2582. PathCursor.prototype.moveAhead = function (step) {
  2583. if (step === void 0) { step = 0.002; }
  2584. this.move(step);
  2585. return this;
  2586. };
  2587. PathCursor.prototype.moveBack = function (step) {
  2588. if (step === void 0) { step = 0.002; }
  2589. this.move(-step);
  2590. return this;
  2591. };
  2592. PathCursor.prototype.move = function (step) {
  2593. if (Math.abs(step) > 1) {
  2594. throw "step size should be less than 1.";
  2595. }
  2596. this.value += step;
  2597. this.ensureLimits();
  2598. this.raiseOnChange();
  2599. return this;
  2600. };
  2601. PathCursor.prototype.ensureLimits = function () {
  2602. while (this.value > 1) {
  2603. this.value -= 1;
  2604. }
  2605. while (this.value < 0) {
  2606. this.value += 1;
  2607. }
  2608. return this;
  2609. };
  2610. // used by animation engine
  2611. PathCursor.prototype.markAsDirty = function (propertyName) {
  2612. this.ensureLimits();
  2613. this.raiseOnChange();
  2614. return this;
  2615. };
  2616. PathCursor.prototype.raiseOnChange = function () {
  2617. var _this = this;
  2618. this._onchange.forEach(function (f) { return f(_this); });
  2619. return this;
  2620. };
  2621. PathCursor.prototype.onchange = function (f) {
  2622. this._onchange.push(f);
  2623. return this;
  2624. };
  2625. return PathCursor;
  2626. })();
  2627. BABYLON.PathCursor = PathCursor;
  2628. var Path2 = (function () {
  2629. function Path2(x, y) {
  2630. this._points = new Array();
  2631. this._length = 0;
  2632. this.closed = false;
  2633. this._points.push(new Vector2(x, y));
  2634. }
  2635. Path2.prototype.addLineTo = function (x, y) {
  2636. if (closed) {
  2637. BABYLON.Tools.Error("cannot add lines to closed paths");
  2638. return this;
  2639. }
  2640. var newPoint = new Vector2(x, y);
  2641. var previousPoint = this._points[this._points.length - 1];
  2642. this._points.push(newPoint);
  2643. this._length += newPoint.subtract(previousPoint).length();
  2644. return this;
  2645. };
  2646. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2647. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2648. if (closed) {
  2649. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2650. return this;
  2651. }
  2652. var startPoint = this._points[this._points.length - 1];
  2653. var midPoint = new Vector2(midX, midY);
  2654. var endPoint = new Vector2(endX, endY);
  2655. var arc = new Arc2(startPoint, midPoint, endPoint);
  2656. var increment = arc.angle.radians() / numberOfSegments;
  2657. if (arc.orientation === 0 /* CW */)
  2658. increment *= -1;
  2659. var currentAngle = arc.startAngle.radians() + increment;
  2660. for (var i = 0; i < numberOfSegments; i++) {
  2661. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2662. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2663. this.addLineTo(x, y);
  2664. currentAngle += increment;
  2665. }
  2666. return this;
  2667. };
  2668. Path2.prototype.close = function () {
  2669. this.closed = true;
  2670. return this;
  2671. };
  2672. Path2.prototype.length = function () {
  2673. var result = this._length;
  2674. if (!this.closed) {
  2675. var lastPoint = this._points[this._points.length - 1];
  2676. var firstPoint = this._points[0];
  2677. result += (firstPoint.subtract(lastPoint).length());
  2678. }
  2679. return result;
  2680. };
  2681. Path2.prototype.getPoints = function () {
  2682. return this._points;
  2683. };
  2684. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2685. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2686. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2687. return Vector2.Zero();
  2688. }
  2689. var lengthPosition = normalizedLengthPosition * this.length();
  2690. var previousOffset = 0;
  2691. for (var i = 0; i < this._points.length; i++) {
  2692. var j = (i + 1) % this._points.length;
  2693. var a = this._points[i];
  2694. var b = this._points[j];
  2695. var bToA = b.subtract(a);
  2696. var nextOffset = (bToA.length() + previousOffset);
  2697. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2698. var dir = bToA.normalize();
  2699. var localOffset = lengthPosition - previousOffset;
  2700. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2701. }
  2702. previousOffset = nextOffset;
  2703. }
  2704. BABYLON.Tools.Error("internal error");
  2705. return Vector2.Zero();
  2706. };
  2707. Path2.StartingAt = function (x, y) {
  2708. return new Path2(x, y);
  2709. };
  2710. return Path2;
  2711. })();
  2712. BABYLON.Path2 = Path2;
  2713. var Path3D = (function () {
  2714. function Path3D(path, firstNormal) {
  2715. this.path = path;
  2716. this._curve = new Array();
  2717. this._distances = new Array();
  2718. this._tangents = new Array();
  2719. this._normals = new Array();
  2720. this._binormals = new Array();
  2721. for (var p = 0; p < path.length; p++) {
  2722. this._curve[p] = path[p].clone(); // hard copy
  2723. }
  2724. this._compute(firstNormal);
  2725. }
  2726. Path3D.prototype.getCurve = function () {
  2727. return this._curve;
  2728. };
  2729. Path3D.prototype.getTangents = function () {
  2730. return this._tangents;
  2731. };
  2732. Path3D.prototype.getNormals = function () {
  2733. return this._normals;
  2734. };
  2735. Path3D.prototype.getBinormals = function () {
  2736. return this._binormals;
  2737. };
  2738. Path3D.prototype.getDistances = function () {
  2739. return this._distances;
  2740. };
  2741. Path3D.prototype.update = function (path, firstNormal) {
  2742. for (var p = 0; p < path.length; p++) {
  2743. this._curve[p].x = path[p].x;
  2744. this._curve[p].y = path[p].y;
  2745. this._curve[p].z = path[p].z;
  2746. }
  2747. this._compute(firstNormal);
  2748. return this;
  2749. };
  2750. // private function compute() : computes tangents, normals and binormals
  2751. Path3D.prototype._compute = function (firstNormal) {
  2752. var l = this._curve.length;
  2753. // first and last tangents
  2754. this._tangents[0] = this._getFirstNonNullVector(0);
  2755. this._tangents[0].normalize();
  2756. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2757. this._tangents[l - 1].normalize();
  2758. // normals and binormals at first point : arbitrary vector with _normalVector()
  2759. var tg0 = this._tangents[0];
  2760. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2761. this._normals[0] = pp0;
  2762. this._normals[0].normalize();
  2763. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2764. this._binormals[0].normalize();
  2765. this._distances[0] = 0;
  2766. // normals and binormals : next points
  2767. var prev; // previous vector (segment)
  2768. var cur; // current vector (segment)
  2769. var curTang; // current tangent
  2770. var prevNorm; // previous normal
  2771. var prevBinor; // previous binormal
  2772. for (var i = 1; i < l; i++) {
  2773. // tangents
  2774. prev = this._getLastNonNullVector(i);
  2775. if (i < l - 1) {
  2776. cur = this._getFirstNonNullVector(i);
  2777. this._tangents[i] = prev.add(cur);
  2778. this._tangents[i].normalize();
  2779. }
  2780. this._distances[i] = this._distances[i - 1] + prev.length();
  2781. // normals and binormals
  2782. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2783. curTang = this._tangents[i];
  2784. prevNorm = this._normals[i - 1];
  2785. prevBinor = this._binormals[i - 1];
  2786. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2787. this._normals[i].normalize();
  2788. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2789. this._binormals[i].normalize();
  2790. }
  2791. };
  2792. // private function getFirstNonNullVector(index)
  2793. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2794. Path3D.prototype._getFirstNonNullVector = function (index) {
  2795. var i = 1;
  2796. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2797. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2798. i++;
  2799. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2800. }
  2801. return nNVector;
  2802. };
  2803. // private function getLastNonNullVector(index)
  2804. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2805. Path3D.prototype._getLastNonNullVector = function (index) {
  2806. var i = 1;
  2807. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2808. while (nLVector.length() == 0 && index > i + 1) {
  2809. i++;
  2810. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2811. }
  2812. return nLVector;
  2813. };
  2814. // private function normalVector(v0, vt, va) :
  2815. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2816. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2817. Path3D.prototype._normalVector = function (v0, vt, va) {
  2818. var normal0;
  2819. if (va === undefined || va === null) {
  2820. var point;
  2821. if (vt.y !== 1) {
  2822. point = new Vector3(0, -1, 0);
  2823. }
  2824. else if (vt.x !== 1) {
  2825. point = new Vector3(1, 0, 0);
  2826. }
  2827. else if (vt.z !== 1) {
  2828. point = new Vector3(0, 0, 1);
  2829. }
  2830. normal0 = Vector3.Cross(vt, point);
  2831. }
  2832. else {
  2833. normal0 = Vector3.Cross(vt, va);
  2834. Vector3.CrossToRef(normal0, vt, normal0);
  2835. }
  2836. normal0.normalize();
  2837. return normal0;
  2838. };
  2839. return Path3D;
  2840. })();
  2841. BABYLON.Path3D = Path3D;
  2842. var Curve3 = (function () {
  2843. function Curve3(points) {
  2844. this._length = 0;
  2845. this._points = points;
  2846. this._length = this._computeLength(points);
  2847. }
  2848. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2849. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2850. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2851. var bez = new Array();
  2852. var equation = function (t, val0, val1, val2) {
  2853. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2854. return res;
  2855. };
  2856. for (var i = 0; i <= nbPoints; i++) {
  2857. 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)));
  2858. }
  2859. return new Curve3(bez);
  2860. };
  2861. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2862. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2863. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2864. var bez = new Array();
  2865. var equation = function (t, val0, val1, val2, val3) {
  2866. 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;
  2867. return res;
  2868. };
  2869. for (var i = 0; i <= nbPoints; i++) {
  2870. 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)));
  2871. }
  2872. return new Curve3(bez);
  2873. };
  2874. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2875. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2876. var hermite = new Array();
  2877. var step = 1 / nbPoints;
  2878. for (var i = 0; i <= nbPoints; i++) {
  2879. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2880. }
  2881. return new Curve3(hermite);
  2882. };
  2883. Curve3.prototype.getPoints = function () {
  2884. return this._points;
  2885. };
  2886. Curve3.prototype.length = function () {
  2887. return this._length;
  2888. };
  2889. Curve3.prototype.continue = function (curve) {
  2890. var lastPoint = this._points[this._points.length - 1];
  2891. var continuedPoints = this._points.slice();
  2892. var curvePoints = curve.getPoints();
  2893. for (var i = 1; i < curvePoints.length; i++) {
  2894. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2895. }
  2896. var continuedCurve = new Curve3(continuedPoints);
  2897. return continuedCurve;
  2898. };
  2899. Curve3.prototype._computeLength = function (path) {
  2900. var l = 0;
  2901. for (var i = 1; i < path.length; i++) {
  2902. l += (path[i].subtract(path[i - 1])).length();
  2903. }
  2904. return l;
  2905. };
  2906. return Curve3;
  2907. })();
  2908. BABYLON.Curve3 = Curve3;
  2909. // Vertex formats
  2910. var PositionNormalVertex = (function () {
  2911. function PositionNormalVertex(position, normal) {
  2912. if (position === void 0) { position = Vector3.Zero(); }
  2913. if (normal === void 0) { normal = Vector3.Up(); }
  2914. this.position = position;
  2915. this.normal = normal;
  2916. }
  2917. PositionNormalVertex.prototype.clone = function () {
  2918. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2919. };
  2920. return PositionNormalVertex;
  2921. })();
  2922. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2923. var PositionNormalTextureVertex = (function () {
  2924. function PositionNormalTextureVertex(position, normal, uv) {
  2925. if (position === void 0) { position = Vector3.Zero(); }
  2926. if (normal === void 0) { normal = Vector3.Up(); }
  2927. if (uv === void 0) { uv = Vector2.Zero(); }
  2928. this.position = position;
  2929. this.normal = normal;
  2930. this.uv = uv;
  2931. }
  2932. PositionNormalTextureVertex.prototype.clone = function () {
  2933. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2934. };
  2935. return PositionNormalTextureVertex;
  2936. })();
  2937. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2938. // SIMD
  2939. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2940. var previousInvertToRef = Matrix.prototype.invertToRef;
  2941. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2942. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2943. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2944. var SIMDHelper = (function () {
  2945. function SIMDHelper() {
  2946. }
  2947. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2948. get: function () {
  2949. return SIMDHelper._isEnabled;
  2950. },
  2951. enumerable: true,
  2952. configurable: true
  2953. });
  2954. SIMDHelper.DisableSIMD = function () {
  2955. // Replace functions
  2956. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2957. Matrix.prototype.invertToRef = previousInvertToRef;
  2958. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2959. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2960. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2961. SIMDHelper._isEnabled = false;
  2962. };
  2963. SIMDHelper.EnableSIMD = function () {
  2964. if (window.SIMD === undefined) {
  2965. return;
  2966. }
  2967. // Replace functions
  2968. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2969. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2970. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2971. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2972. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2973. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2974. get: function () {
  2975. return this._data[0];
  2976. },
  2977. set: function (value) {
  2978. if (!this._data) {
  2979. this._data = new Float32Array(3);
  2980. }
  2981. this._data[0] = value;
  2982. }
  2983. });
  2984. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2985. get: function () {
  2986. return this._data[1];
  2987. },
  2988. set: function (value) {
  2989. this._data[1] = value;
  2990. }
  2991. });
  2992. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2993. get: function () {
  2994. return this._data[2];
  2995. },
  2996. set: function (value) {
  2997. this._data[2] = value;
  2998. }
  2999. });
  3000. SIMDHelper._isEnabled = true;
  3001. };
  3002. SIMDHelper._isEnabled = false;
  3003. return SIMDHelper;
  3004. })();
  3005. BABYLON.SIMDHelper = SIMDHelper;
  3006. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3007. SIMDHelper.EnableSIMD();
  3008. }
  3009. })(BABYLON || (BABYLON = {}));
  3010. //# sourceMappingURL=babylon.math.js.map
  3011. var BABYLON;
  3012. (function (BABYLON) {
  3013. var Database = (function () {
  3014. function Database(urlToScene, callbackManifestChecked) {
  3015. // Handling various flavors of prefixed version of IndexedDB
  3016. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3017. this.callbackManifestChecked = callbackManifestChecked;
  3018. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  3019. this.db = null;
  3020. this.enableSceneOffline = false;
  3021. this.enableTexturesOffline = false;
  3022. this.manifestVersionFound = 0;
  3023. this.mustUpdateRessources = false;
  3024. this.hasReachedQuota = false;
  3025. this.checkManifestFile();
  3026. }
  3027. Database.prototype.checkManifestFile = function () {
  3028. var _this = this;
  3029. function noManifestFile() {
  3030. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  3031. that.enableSceneOffline = false;
  3032. that.enableTexturesOffline = false;
  3033. that.callbackManifestChecked(false);
  3034. }
  3035. var that = this;
  3036. var manifestURL = this.currentSceneUrl + ".manifest";
  3037. var xhr = new XMLHttpRequest();
  3038. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3039. xhr.open("GET", manifestURLTimeStamped, true);
  3040. xhr.addEventListener("load", function () {
  3041. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3042. try {
  3043. var manifestFile = JSON.parse(xhr.response);
  3044. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3045. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3046. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3047. _this.manifestVersionFound = manifestFile.version;
  3048. }
  3049. if (_this.callbackManifestChecked) {
  3050. _this.callbackManifestChecked(true);
  3051. }
  3052. }
  3053. catch (ex) {
  3054. noManifestFile();
  3055. }
  3056. }
  3057. else {
  3058. noManifestFile();
  3059. }
  3060. }, false);
  3061. xhr.addEventListener("error", function (event) {
  3062. noManifestFile();
  3063. }, false);
  3064. try {
  3065. xhr.send();
  3066. }
  3067. catch (ex) {
  3068. BABYLON.Tools.Error("Error on XHR send request.");
  3069. that.callbackManifestChecked(false);
  3070. }
  3071. };
  3072. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3073. var _this = this;
  3074. function handleError() {
  3075. that.isSupported = false;
  3076. if (errorCallback)
  3077. errorCallback();
  3078. }
  3079. var that = this;
  3080. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3081. // Your browser doesn't support IndexedDB
  3082. this.isSupported = false;
  3083. if (errorCallback)
  3084. errorCallback();
  3085. }
  3086. else {
  3087. // If the DB hasn't been opened or created yet
  3088. if (!this.db) {
  3089. this.hasReachedQuota = false;
  3090. this.isSupported = true;
  3091. var request = this.idbFactory.open("babylonjs", 1);
  3092. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3093. request.onerror = function (event) {
  3094. handleError();
  3095. };
  3096. // executes when a version change transaction cannot complete due to other active transactions
  3097. request.onblocked = function (event) {
  3098. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3099. handleError();
  3100. };
  3101. // DB has been opened successfully
  3102. request.onsuccess = function (event) {
  3103. _this.db = request.result;
  3104. successCallback();
  3105. };
  3106. // Initialization of the DB. Creating Scenes & Textures stores
  3107. request.onupgradeneeded = function (event) {
  3108. _this.db = (event.target).result;
  3109. try {
  3110. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3111. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3112. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3113. }
  3114. catch (ex) {
  3115. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3116. handleError();
  3117. }
  3118. };
  3119. }
  3120. else {
  3121. if (successCallback)
  3122. successCallback();
  3123. }
  3124. }
  3125. };
  3126. Database.prototype.loadImageFromDB = function (url, image) {
  3127. var _this = this;
  3128. var completeURL = Database.ReturnFullUrlLocation(url);
  3129. var saveAndLoadImage = function () {
  3130. if (!_this.hasReachedQuota && _this.db !== null) {
  3131. // the texture is not yet in the DB, let's try to save it
  3132. _this._saveImageIntoDBAsync(completeURL, image);
  3133. }
  3134. else {
  3135. image.src = url;
  3136. }
  3137. };
  3138. if (!this.mustUpdateRessources) {
  3139. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3140. }
  3141. else {
  3142. saveAndLoadImage();
  3143. }
  3144. };
  3145. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3146. if (this.isSupported && this.db !== null) {
  3147. var texture;
  3148. var transaction = this.db.transaction(["textures"]);
  3149. transaction.onabort = function (event) {
  3150. image.src = url;
  3151. };
  3152. transaction.oncomplete = function (event) {
  3153. var blobTextureURL;
  3154. if (texture) {
  3155. var URL = window.URL || window.webkitURL;
  3156. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3157. image.onerror = function () {
  3158. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3159. image.src = url;
  3160. };
  3161. image.src = blobTextureURL;
  3162. }
  3163. else {
  3164. notInDBCallback();
  3165. }
  3166. };
  3167. var getRequest = transaction.objectStore("textures").get(url);
  3168. getRequest.onsuccess = function (event) {
  3169. texture = (event.target).result;
  3170. };
  3171. getRequest.onerror = function (event) {
  3172. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3173. image.src = url;
  3174. };
  3175. }
  3176. else {
  3177. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3178. image.src = url;
  3179. }
  3180. };
  3181. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3182. var _this = this;
  3183. if (this.isSupported) {
  3184. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3185. var generateBlobUrl = function () {
  3186. var blobTextureURL;
  3187. if (blob) {
  3188. var URL = window.URL || window.webkitURL;
  3189. try {
  3190. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3191. }
  3192. catch (ex) {
  3193. blobTextureURL = URL.createObjectURL(blob);
  3194. }
  3195. }
  3196. image.src = blobTextureURL;
  3197. };
  3198. if (Database.isUASupportingBlobStorage) {
  3199. var xhr = new XMLHttpRequest(), blob;
  3200. xhr.open("GET", url, true);
  3201. xhr.responseType = "blob";
  3202. xhr.addEventListener("load", function () {
  3203. if (xhr.status === 200) {
  3204. // Blob as response (XHR2)
  3205. blob = xhr.response;
  3206. var transaction = _this.db.transaction(["textures"], "readwrite");
  3207. // the transaction could abort because of a QuotaExceededError error
  3208. transaction.onabort = function (event) {
  3209. try {
  3210. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3211. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3212. this.hasReachedQuota = true;
  3213. }
  3214. }
  3215. catch (ex) {
  3216. }
  3217. generateBlobUrl();
  3218. };
  3219. transaction.oncomplete = function (event) {
  3220. generateBlobUrl();
  3221. };
  3222. var newTexture = { textureUrl: url, data: blob };
  3223. try {
  3224. // Put the blob into the dabase
  3225. var addRequest = transaction.objectStore("textures").put(newTexture);
  3226. addRequest.onsuccess = function (event) {
  3227. };
  3228. addRequest.onerror = function (event) {
  3229. generateBlobUrl();
  3230. };
  3231. }
  3232. catch (ex) {
  3233. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3234. if (ex.code === 25) {
  3235. Database.isUASupportingBlobStorage = false;
  3236. }
  3237. image.src = url;
  3238. }
  3239. }
  3240. else {
  3241. image.src = url;
  3242. }
  3243. }, false);
  3244. xhr.addEventListener("error", function (event) {
  3245. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3246. image.src = url;
  3247. }, false);
  3248. xhr.send();
  3249. }
  3250. else {
  3251. image.src = url;
  3252. }
  3253. }
  3254. else {
  3255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3256. image.src = url;
  3257. }
  3258. };
  3259. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3260. var _this = this;
  3261. var updateVersion = function (event) {
  3262. // the version is not yet in the DB or we need to update it
  3263. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3264. };
  3265. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3266. };
  3267. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3268. var _this = this;
  3269. if (this.isSupported) {
  3270. var version;
  3271. try {
  3272. var transaction = this.db.transaction(["versions"]);
  3273. transaction.oncomplete = function (event) {
  3274. if (version) {
  3275. // If the version in the JSON file is > than the version in DB
  3276. if (_this.manifestVersionFound > version.data) {
  3277. _this.mustUpdateRessources = true;
  3278. updateInDBCallback();
  3279. }
  3280. else {
  3281. callback(version.data);
  3282. }
  3283. }
  3284. else {
  3285. _this.mustUpdateRessources = true;
  3286. updateInDBCallback();
  3287. }
  3288. };
  3289. transaction.onabort = function (event) {
  3290. callback(-1);
  3291. };
  3292. var getRequest = transaction.objectStore("versions").get(url);
  3293. getRequest.onsuccess = function (event) {
  3294. version = (event.target).result;
  3295. };
  3296. getRequest.onerror = function (event) {
  3297. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3298. callback(-1);
  3299. };
  3300. }
  3301. catch (ex) {
  3302. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3303. callback(-1);
  3304. }
  3305. }
  3306. else {
  3307. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3308. callback(-1);
  3309. }
  3310. };
  3311. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3312. var _this = this;
  3313. if (this.isSupported && !this.hasReachedQuota) {
  3314. try {
  3315. // Open a transaction to the database
  3316. var transaction = this.db.transaction(["versions"], "readwrite");
  3317. // the transaction could abort because of a QuotaExceededError error
  3318. transaction.onabort = function (event) {
  3319. try {
  3320. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3321. _this.hasReachedQuota = true;
  3322. }
  3323. }
  3324. catch (ex) {
  3325. }
  3326. callback(-1);
  3327. };
  3328. transaction.oncomplete = function (event) {
  3329. callback(_this.manifestVersionFound);
  3330. };
  3331. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3332. // Put the scene into the database
  3333. var addRequest = transaction.objectStore("versions").put(newVersion);
  3334. addRequest.onsuccess = function (event) {
  3335. };
  3336. addRequest.onerror = function (event) {
  3337. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3338. };
  3339. }
  3340. catch (ex) {
  3341. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3342. callback(-1);
  3343. }
  3344. }
  3345. else {
  3346. callback(-1);
  3347. }
  3348. };
  3349. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3350. var _this = this;
  3351. var completeUrl = Database.ReturnFullUrlLocation(url);
  3352. var saveAndLoadFile = function (event) {
  3353. // the scene is not yet in the DB, let's try to save it
  3354. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3355. };
  3356. this._checkVersionFromDB(completeUrl, function (version) {
  3357. if (version !== -1) {
  3358. if (!_this.mustUpdateRessources) {
  3359. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3360. }
  3361. else {
  3362. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3363. }
  3364. }
  3365. else {
  3366. errorCallback();
  3367. }
  3368. });
  3369. };
  3370. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3371. if (this.isSupported) {
  3372. var targetStore;
  3373. if (url.indexOf(".babylon") !== -1) {
  3374. targetStore = "scenes";
  3375. }
  3376. else {
  3377. targetStore = "textures";
  3378. }
  3379. var file;
  3380. var transaction = this.db.transaction([targetStore]);
  3381. transaction.oncomplete = function (event) {
  3382. if (file) {
  3383. callback(file.data);
  3384. }
  3385. else {
  3386. notInDBCallback();
  3387. }
  3388. };
  3389. transaction.onabort = function (event) {
  3390. notInDBCallback();
  3391. };
  3392. var getRequest = transaction.objectStore(targetStore).get(url);
  3393. getRequest.onsuccess = function (event) {
  3394. file = (event.target).result;
  3395. };
  3396. getRequest.onerror = function (event) {
  3397. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3398. notInDBCallback();
  3399. };
  3400. }
  3401. else {
  3402. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3403. callback();
  3404. }
  3405. };
  3406. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3407. var _this = this;
  3408. if (this.isSupported) {
  3409. var targetStore;
  3410. if (url.indexOf(".babylon") !== -1) {
  3411. targetStore = "scenes";
  3412. }
  3413. else {
  3414. targetStore = "textures";
  3415. }
  3416. // Create XHR
  3417. var xhr = new XMLHttpRequest(), fileData;
  3418. xhr.open("GET", url, true);
  3419. if (useArrayBuffer) {
  3420. xhr.responseType = "arraybuffer";
  3421. }
  3422. xhr.onprogress = progressCallback;
  3423. xhr.addEventListener("load", function () {
  3424. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3425. // Blob as response (XHR2)
  3426. //fileData = xhr.responseText;
  3427. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3428. if (!_this.hasReachedQuota) {
  3429. // Open a transaction to the database
  3430. var transaction = _this.db.transaction([targetStore], "readwrite");
  3431. // the transaction could abort because of a QuotaExceededError error
  3432. transaction.onabort = function (event) {
  3433. try {
  3434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3435. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3436. this.hasReachedQuota = true;
  3437. }
  3438. }
  3439. catch (ex) {
  3440. }
  3441. callback(fileData);
  3442. };
  3443. transaction.oncomplete = function (event) {
  3444. callback(fileData);
  3445. };
  3446. var newFile;
  3447. if (targetStore === "scenes") {
  3448. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3449. }
  3450. else {
  3451. newFile = { textureUrl: url, data: fileData };
  3452. }
  3453. try {
  3454. // Put the scene into the database
  3455. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3456. addRequest.onsuccess = function (event) {
  3457. };
  3458. addRequest.onerror = function (event) {
  3459. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3460. };
  3461. }
  3462. catch (ex) {
  3463. callback(fileData);
  3464. }
  3465. }
  3466. else {
  3467. callback(fileData);
  3468. }
  3469. }
  3470. else {
  3471. callback();
  3472. }
  3473. }, false);
  3474. xhr.addEventListener("error", function (event) {
  3475. BABYLON.Tools.Error("error on XHR request.");
  3476. callback();
  3477. }, false);
  3478. xhr.send();
  3479. }
  3480. else {
  3481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3482. callback();
  3483. }
  3484. };
  3485. Database.isUASupportingBlobStorage = true;
  3486. Database.parseURL = function (url) {
  3487. var a = document.createElement('a');
  3488. a.href = url;
  3489. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3490. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3491. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3492. return absLocation;
  3493. };
  3494. Database.ReturnFullUrlLocation = function (url) {
  3495. if (url.indexOf("http:/") === -1) {
  3496. return (BABYLON.Database.parseURL(window.location.href) + url);
  3497. }
  3498. else {
  3499. return url;
  3500. }
  3501. };
  3502. return Database;
  3503. })();
  3504. BABYLON.Database = Database;
  3505. })(BABYLON || (BABYLON = {}));
  3506. //# sourceMappingURL=babylon.database.js.map
  3507. var BABYLON;
  3508. (function (BABYLON) {
  3509. var Internals;
  3510. (function (Internals) {
  3511. /*
  3512. * Based on jsTGALoader - Javascript loader for TGA file
  3513. * By Vincent Thibault
  3514. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3515. */
  3516. var TGATools = (function () {
  3517. function TGATools() {
  3518. }
  3519. TGATools.GetTGAHeader = function (data) {
  3520. var offset = 0;
  3521. var header = {
  3522. id_length: data[offset++],
  3523. colormap_type: data[offset++],
  3524. image_type: data[offset++],
  3525. colormap_index: data[offset++] | data[offset++] << 8,
  3526. colormap_length: data[offset++] | data[offset++] << 8,
  3527. colormap_size: data[offset++],
  3528. origin: [
  3529. data[offset++] | data[offset++] << 8,
  3530. data[offset++] | data[offset++] << 8
  3531. ],
  3532. width: data[offset++] | data[offset++] << 8,
  3533. height: data[offset++] | data[offset++] << 8,
  3534. pixel_size: data[offset++],
  3535. flags: data[offset++]
  3536. };
  3537. return header;
  3538. };
  3539. TGATools.UploadContent = function (gl, data) {
  3540. // Not enough data to contain header ?
  3541. if (data.length < 19) {
  3542. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3543. return;
  3544. }
  3545. // Read Header
  3546. var offset = 18;
  3547. var header = TGATools.GetTGAHeader(data);
  3548. // Assume it's a valid Targa file.
  3549. if (header.id_length + offset > data.length) {
  3550. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3551. return;
  3552. }
  3553. // Skip not needed data
  3554. offset += header.id_length;
  3555. var use_rle = false;
  3556. var use_pal = false;
  3557. var use_rgb = false;
  3558. var use_grey = false;
  3559. switch (header.image_type) {
  3560. case TGATools._TYPE_RLE_INDEXED:
  3561. use_rle = true;
  3562. case TGATools._TYPE_INDEXED:
  3563. use_pal = true;
  3564. break;
  3565. case TGATools._TYPE_RLE_RGB:
  3566. use_rle = true;
  3567. case TGATools._TYPE_RGB:
  3568. use_rgb = true;
  3569. break;
  3570. case TGATools._TYPE_RLE_GREY:
  3571. use_rle = true;
  3572. case TGATools._TYPE_GREY:
  3573. use_grey = true;
  3574. break;
  3575. }
  3576. var pixel_data;
  3577. var numAlphaBits = header.flags & 0xf;
  3578. var pixel_size = header.pixel_size >> 3;
  3579. var pixel_total = header.width * header.height * pixel_size;
  3580. // Read palettes
  3581. var palettes;
  3582. if (use_pal) {
  3583. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3584. }
  3585. // Read LRE
  3586. if (use_rle) {
  3587. pixel_data = new Uint8Array(pixel_total);
  3588. var c, count, i;
  3589. var localOffset = 0;
  3590. var pixels = new Uint8Array(pixel_size);
  3591. while (offset < pixel_total && localOffset < pixel_total) {
  3592. c = data[offset++];
  3593. count = (c & 0x7f) + 1;
  3594. // RLE pixels
  3595. if (c & 0x80) {
  3596. for (i = 0; i < pixel_size; ++i) {
  3597. pixels[i] = data[offset++];
  3598. }
  3599. for (i = 0; i < count; ++i) {
  3600. pixel_data.set(pixels, localOffset + i * pixel_size);
  3601. }
  3602. localOffset += pixel_size * count;
  3603. }
  3604. else {
  3605. count *= pixel_size;
  3606. for (i = 0; i < count; ++i) {
  3607. pixel_data[localOffset + i] = data[offset++];
  3608. }
  3609. localOffset += count;
  3610. }
  3611. }
  3612. }
  3613. else {
  3614. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3615. }
  3616. // Load to texture
  3617. var x_start, y_start, x_step, y_step, y_end, x_end;
  3618. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3619. default:
  3620. case TGATools._ORIGIN_UL:
  3621. x_start = 0;
  3622. x_step = 1;
  3623. x_end = header.width;
  3624. y_start = 0;
  3625. y_step = 1;
  3626. y_end = header.height;
  3627. break;
  3628. case TGATools._ORIGIN_BL:
  3629. x_start = 0;
  3630. x_step = 1;
  3631. x_end = header.width;
  3632. y_start = header.height - 1;
  3633. y_step = -1;
  3634. y_end = -1;
  3635. break;
  3636. case TGATools._ORIGIN_UR:
  3637. x_start = header.width - 1;
  3638. x_step = -1;
  3639. x_end = -1;
  3640. y_start = 0;
  3641. y_step = 1;
  3642. y_end = header.height;
  3643. break;
  3644. case TGATools._ORIGIN_BR:
  3645. x_start = header.width - 1;
  3646. x_step = -1;
  3647. x_end = -1;
  3648. y_start = header.height - 1;
  3649. y_step = -1;
  3650. y_end = -1;
  3651. break;
  3652. }
  3653. // Load the specify method
  3654. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3655. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3656. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3657. };
  3658. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3659. var image = pixel_data, colormap = palettes;
  3660. var width = header.width, height = header.height;
  3661. var color, i = 0, x, y;
  3662. var imageData = new Uint8Array(width * height * 4);
  3663. for (y = y_start; y !== y_end; y += y_step) {
  3664. for (x = x_start; x !== x_end; x += x_step, i++) {
  3665. color = image[i];
  3666. imageData[(x + width * y) * 4 + 3] = 255;
  3667. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3668. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3669. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3670. }
  3671. }
  3672. return imageData;
  3673. };
  3674. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3675. var image = pixel_data;
  3676. var width = header.width, height = header.height;
  3677. var color, i = 0, x, y;
  3678. var imageData = new Uint8Array(width * height * 4);
  3679. for (y = y_start; y !== y_end; y += y_step) {
  3680. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3681. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3682. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3683. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3684. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3685. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3686. }
  3687. }
  3688. return imageData;
  3689. };
  3690. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3691. var image = pixel_data;
  3692. var width = header.width, height = header.height;
  3693. var i = 0, x, y;
  3694. var imageData = new Uint8Array(width * height * 4);
  3695. for (y = y_start; y !== y_end; y += y_step) {
  3696. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3697. imageData[(x + width * y) * 4 + 3] = 255;
  3698. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3699. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3700. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3701. }
  3702. }
  3703. return imageData;
  3704. };
  3705. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3706. var image = pixel_data;
  3707. var width = header.width, height = header.height;
  3708. var i = 0, x, y;
  3709. var imageData = new Uint8Array(width * height * 4);
  3710. for (y = y_start; y !== y_end; y += y_step) {
  3711. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3712. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3713. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3714. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3715. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3716. }
  3717. }
  3718. return imageData;
  3719. };
  3720. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3721. var image = pixel_data;
  3722. var width = header.width, height = header.height;
  3723. var color, i = 0, x, y;
  3724. var imageData = new Uint8Array(width * height * 4);
  3725. for (y = y_start; y !== y_end; y += y_step) {
  3726. for (x = x_start; x !== x_end; x += x_step, i++) {
  3727. color = image[i];
  3728. imageData[(x + width * y) * 4 + 0] = color;
  3729. imageData[(x + width * y) * 4 + 1] = color;
  3730. imageData[(x + width * y) * 4 + 2] = color;
  3731. imageData[(x + width * y) * 4 + 3] = 255;
  3732. }
  3733. }
  3734. return imageData;
  3735. };
  3736. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3737. var image = pixel_data;
  3738. var width = header.width, height = header.height;
  3739. var i = 0, x, y;
  3740. var imageData = new Uint8Array(width * height * 4);
  3741. for (y = y_start; y !== y_end; y += y_step) {
  3742. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3743. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3744. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3745. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3746. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3747. }
  3748. }
  3749. return imageData;
  3750. };
  3751. TGATools._TYPE_NO_DATA = 0;
  3752. TGATools._TYPE_INDEXED = 1;
  3753. TGATools._TYPE_RGB = 2;
  3754. TGATools._TYPE_GREY = 3;
  3755. TGATools._TYPE_RLE_INDEXED = 9;
  3756. TGATools._TYPE_RLE_RGB = 10;
  3757. TGATools._TYPE_RLE_GREY = 11;
  3758. TGATools._ORIGIN_MASK = 0x30;
  3759. TGATools._ORIGIN_SHIFT = 0x04;
  3760. TGATools._ORIGIN_BL = 0x00;
  3761. TGATools._ORIGIN_BR = 0x01;
  3762. TGATools._ORIGIN_UL = 0x02;
  3763. TGATools._ORIGIN_UR = 0x03;
  3764. return TGATools;
  3765. })();
  3766. Internals.TGATools = TGATools;
  3767. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3768. })(BABYLON || (BABYLON = {}));
  3769. //# sourceMappingURL=babylon.tools.tga.js.map
  3770. var BABYLON;
  3771. (function (BABYLON) {
  3772. var Internals;
  3773. (function (Internals) {
  3774. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3775. // All values and structures referenced from:
  3776. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3777. var DDS_MAGIC = 0x20534444;
  3778. 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;
  3779. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3780. 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;
  3781. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3782. function FourCCToInt32(value) {
  3783. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  3784. }
  3785. function Int32ToFourCC(value) {
  3786. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3787. }
  3788. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3789. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3790. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3791. var headerLengthInt = 31; // The header length in 32 bit ints
  3792. // Offsets into the header array
  3793. var off_magic = 0;
  3794. var off_size = 1;
  3795. var off_flags = 2;
  3796. var off_height = 3;
  3797. var off_width = 4;
  3798. var off_mipmapCount = 7;
  3799. var off_pfFlags = 20;
  3800. var off_pfFourCC = 21;
  3801. var off_RGBbpp = 22;
  3802. var off_RMask = 23;
  3803. var off_GMask = 24;
  3804. var off_BMask = 25;
  3805. var off_AMask = 26;
  3806. var off_caps1 = 27;
  3807. var off_caps2 = 28;
  3808. ;
  3809. var DDSTools = (function () {
  3810. function DDSTools() {
  3811. }
  3812. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3813. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3814. var mipmapCount = 1;
  3815. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3816. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3817. }
  3818. return {
  3819. width: header[off_width],
  3820. height: header[off_height],
  3821. mipmapCount: mipmapCount,
  3822. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3823. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3824. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3825. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3826. };
  3827. };
  3828. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3829. var byteArray = new Uint8Array(dataLength);
  3830. var srcData = new Uint8Array(arrayBuffer);
  3831. var index = 0;
  3832. for (var y = height - 1; y >= 0; y--) {
  3833. for (var x = 0; x < width; x++) {
  3834. var srcPos = dataOffset + (x + y * width) * 4;
  3835. byteArray[index + 2] = srcData[srcPos];
  3836. byteArray[index + 1] = srcData[srcPos + 1];
  3837. byteArray[index] = srcData[srcPos + 2];
  3838. byteArray[index + 3] = srcData[srcPos + 3];
  3839. index += 4;
  3840. }
  3841. }
  3842. return byteArray;
  3843. };
  3844. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3845. var byteArray = new Uint8Array(dataLength);
  3846. var srcData = new Uint8Array(arrayBuffer);
  3847. var index = 0;
  3848. for (var y = height - 1; y >= 0; y--) {
  3849. for (var x = 0; x < width; x++) {
  3850. var srcPos = dataOffset + (x + y * width) * 3;
  3851. byteArray[index + 2] = srcData[srcPos];
  3852. byteArray[index + 1] = srcData[srcPos + 1];
  3853. byteArray[index] = srcData[srcPos + 2];
  3854. index += 3;
  3855. }
  3856. }
  3857. return byteArray;
  3858. };
  3859. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3860. var byteArray = new Uint8Array(dataLength);
  3861. var srcData = new Uint8Array(arrayBuffer);
  3862. var index = 0;
  3863. for (var y = height - 1; y >= 0; y--) {
  3864. for (var x = 0; x < width; x++) {
  3865. var srcPos = dataOffset + (x + y * width);
  3866. byteArray[index] = srcData[srcPos];
  3867. index++;
  3868. }
  3869. }
  3870. return byteArray;
  3871. };
  3872. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3873. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3874. if (header[off_magic] != DDS_MAGIC) {
  3875. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3876. return;
  3877. }
  3878. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3879. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3880. return;
  3881. }
  3882. if (info.isFourCC) {
  3883. fourCC = header[off_pfFourCC];
  3884. switch (fourCC) {
  3885. case FOURCC_DXT1:
  3886. blockBytes = 8;
  3887. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3888. break;
  3889. case FOURCC_DXT3:
  3890. blockBytes = 16;
  3891. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3892. break;
  3893. case FOURCC_DXT5:
  3894. blockBytes = 16;
  3895. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3896. break;
  3897. default:
  3898. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3899. return;
  3900. }
  3901. }
  3902. mipmapCount = 1;
  3903. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3904. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3905. }
  3906. var bpp = header[off_RGBbpp];
  3907. for (var face = 0; face < faces; face++) {
  3908. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3909. width = header[off_width];
  3910. height = header[off_height];
  3911. dataOffset = header[off_size] + 4;
  3912. for (i = 0; i < mipmapCount; ++i) {
  3913. if (info.isRGB) {
  3914. if (bpp == 24) {
  3915. dataLength = width * height * 3;
  3916. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3917. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3918. }
  3919. else {
  3920. dataLength = width * height * 4;
  3921. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3922. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3923. }
  3924. }
  3925. else if (info.isLuminance) {
  3926. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3927. var unpaddedRowSize = width;
  3928. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3929. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3930. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3931. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3932. }
  3933. else {
  3934. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3935. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3936. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3937. }
  3938. dataOffset += dataLength;
  3939. width *= 0.5;
  3940. height *= 0.5;
  3941. width = Math.max(1.0, width);
  3942. height = Math.max(1.0, height);
  3943. }
  3944. }
  3945. };
  3946. return DDSTools;
  3947. })();
  3948. Internals.DDSTools = DDSTools;
  3949. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3950. })(BABYLON || (BABYLON = {}));
  3951. //# sourceMappingURL=babylon.tools.dds.js.map
  3952. var BABYLON;
  3953. (function (BABYLON) {
  3954. var SmartArray = (function () {
  3955. function SmartArray(capacity) {
  3956. this.length = 0;
  3957. this._duplicateId = 0;
  3958. this.data = new Array(capacity);
  3959. this._id = SmartArray._GlobalId++;
  3960. }
  3961. SmartArray.prototype.push = function (value) {
  3962. this.data[this.length++] = value;
  3963. if (this.length > this.data.length) {
  3964. this.data.length *= 2;
  3965. }
  3966. if (!value.__smartArrayFlags) {
  3967. value.__smartArrayFlags = {};
  3968. }
  3969. value.__smartArrayFlags[this._id] = this._duplicateId;
  3970. };
  3971. SmartArray.prototype.pushNoDuplicate = function (value) {
  3972. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3973. return;
  3974. }
  3975. this.push(value);
  3976. };
  3977. SmartArray.prototype.sort = function (compareFn) {
  3978. this.data.sort(compareFn);
  3979. };
  3980. SmartArray.prototype.reset = function () {
  3981. this.length = 0;
  3982. this._duplicateId++;
  3983. };
  3984. SmartArray.prototype.concat = function (array) {
  3985. if (array.length === 0) {
  3986. return;
  3987. }
  3988. if (this.length + array.length > this.data.length) {
  3989. this.data.length = (this.length + array.length) * 2;
  3990. }
  3991. for (var index = 0; index < array.length; index++) {
  3992. this.data[this.length++] = (array.data || array)[index];
  3993. }
  3994. };
  3995. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3996. if (array.length === 0) {
  3997. return;
  3998. }
  3999. if (this.length + array.length > this.data.length) {
  4000. this.data.length = (this.length + array.length) * 2;
  4001. }
  4002. for (var index = 0; index < array.length; index++) {
  4003. var item = (array.data || array)[index];
  4004. this.pushNoDuplicate(item);
  4005. }
  4006. };
  4007. SmartArray.prototype.indexOf = function (value) {
  4008. var position = this.data.indexOf(value);
  4009. if (position >= this.length) {
  4010. return -1;
  4011. }
  4012. return position;
  4013. };
  4014. // Statics
  4015. SmartArray._GlobalId = 0;
  4016. return SmartArray;
  4017. })();
  4018. BABYLON.SmartArray = SmartArray;
  4019. })(BABYLON || (BABYLON = {}));
  4020. //# sourceMappingURL=babylon.smartArray.js.map
  4021. var BABYLON;
  4022. (function (BABYLON) {
  4023. var SmartCollection = (function () {
  4024. function SmartCollection(capacity) {
  4025. if (capacity === void 0) { capacity = 10; }
  4026. this.count = 0;
  4027. this._initialCapacity = capacity;
  4028. this.items = {};
  4029. this._keys = new Array(this._initialCapacity);
  4030. }
  4031. SmartCollection.prototype.add = function (key, item) {
  4032. if (this.items[key] != undefined) {
  4033. return -1;
  4034. }
  4035. this.items[key] = item;
  4036. //literal keys are always strings, but we keep source type of key in _keys array
  4037. this._keys[this.count++] = key;
  4038. if (this.count > this._keys.length) {
  4039. this._keys.length *= 2;
  4040. }
  4041. return this.count;
  4042. };
  4043. SmartCollection.prototype.remove = function (key) {
  4044. if (this.items[key] == undefined) {
  4045. return -1;
  4046. }
  4047. return this.removeItemOfIndex(this.indexOf(key));
  4048. };
  4049. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4050. if (index < this.count && index > -1) {
  4051. delete this.items[this._keys[index]];
  4052. while (index < this.count) {
  4053. this._keys[index] = this._keys[index + 1];
  4054. index++;
  4055. }
  4056. }
  4057. else {
  4058. return -1;
  4059. }
  4060. return --this.count;
  4061. };
  4062. SmartCollection.prototype.indexOf = function (key) {
  4063. for (var i = 0; i !== this.count; i++) {
  4064. if (this._keys[i] === key) {
  4065. return i;
  4066. }
  4067. }
  4068. return -1;
  4069. };
  4070. SmartCollection.prototype.item = function (key) {
  4071. return this.items[key];
  4072. };
  4073. SmartCollection.prototype.getAllKeys = function () {
  4074. if (this.count > 0) {
  4075. var keys = new Array(this.count);
  4076. for (var i = 0; i < this.count; i++) {
  4077. keys[i] = this._keys[i];
  4078. }
  4079. return keys;
  4080. }
  4081. else {
  4082. return undefined;
  4083. }
  4084. };
  4085. SmartCollection.prototype.getKeyByIndex = function (index) {
  4086. if (index < this.count && index > -1) {
  4087. return this._keys[index];
  4088. }
  4089. else {
  4090. return undefined;
  4091. }
  4092. };
  4093. SmartCollection.prototype.getItemByIndex = function (index) {
  4094. if (index < this.count && index > -1) {
  4095. return this.items[this._keys[index]];
  4096. }
  4097. else {
  4098. return undefined;
  4099. }
  4100. };
  4101. SmartCollection.prototype.empty = function () {
  4102. if (this.count > 0) {
  4103. this.count = 0;
  4104. this.items = {};
  4105. this._keys = new Array(this._initialCapacity);
  4106. }
  4107. };
  4108. SmartCollection.prototype.forEach = function (block) {
  4109. var key;
  4110. for (key in this.items) {
  4111. if (this.items.hasOwnProperty(key)) {
  4112. block(this.items[key]);
  4113. }
  4114. }
  4115. };
  4116. return SmartCollection;
  4117. })();
  4118. BABYLON.SmartCollection = SmartCollection;
  4119. })(BABYLON || (BABYLON = {}));
  4120. //# sourceMappingURL=babylon.smartCollection.js.map
  4121. var BABYLON;
  4122. (function (BABYLON) {
  4123. // Screenshots
  4124. var screenshotCanvas;
  4125. var cloneValue = function (source, destinationObject) {
  4126. if (!source)
  4127. return null;
  4128. if (source instanceof BABYLON.Mesh) {
  4129. return null;
  4130. }
  4131. if (source instanceof BABYLON.SubMesh) {
  4132. return source.clone(destinationObject);
  4133. }
  4134. else if (source.clone) {
  4135. return source.clone();
  4136. }
  4137. return null;
  4138. };
  4139. var Tools = (function () {
  4140. function Tools() {
  4141. }
  4142. Tools.SetImmediate = function (action) {
  4143. if (window.setImmediate) {
  4144. window.setImmediate(action);
  4145. }
  4146. else {
  4147. setTimeout(action, 1);
  4148. }
  4149. };
  4150. Tools.IsExponantOfTwo = function (value) {
  4151. var count = 1;
  4152. do {
  4153. count *= 2;
  4154. } while (count < value);
  4155. return count === value;
  4156. };
  4157. Tools.GetExponantOfTwo = function (value, max) {
  4158. var count = 1;
  4159. do {
  4160. count *= 2;
  4161. } while (count < value);
  4162. if (count > max)
  4163. count = max;
  4164. return count;
  4165. };
  4166. Tools.GetFilename = function (path) {
  4167. var index = path.lastIndexOf("/");
  4168. if (index < 0)
  4169. return path;
  4170. return path.substring(index + 1);
  4171. };
  4172. Tools.GetDOMTextContent = function (element) {
  4173. var result = "";
  4174. var child = element.firstChild;
  4175. while (child) {
  4176. if (child.nodeType === 3) {
  4177. result += child.textContent;
  4178. }
  4179. child = child.nextSibling;
  4180. }
  4181. return result;
  4182. };
  4183. Tools.ToDegrees = function (angle) {
  4184. return angle * 180 / Math.PI;
  4185. };
  4186. Tools.ToRadians = function (angle) {
  4187. return angle * Math.PI / 180;
  4188. };
  4189. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4190. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4191. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4192. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4193. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4194. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4195. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4196. }
  4197. return {
  4198. minimum: minimum,
  4199. maximum: maximum
  4200. };
  4201. };
  4202. Tools.ExtractMinAndMax = function (positions, start, count) {
  4203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4205. for (var index = start; index < start + count; index++) {
  4206. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4209. }
  4210. return {
  4211. minimum: minimum,
  4212. maximum: maximum
  4213. };
  4214. };
  4215. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4216. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4217. return undefined;
  4218. return Array.isArray(obj) ? obj : [obj];
  4219. };
  4220. // Misc.
  4221. Tools.GetPointerPrefix = function () {
  4222. var eventPrefix = "pointer";
  4223. // Check if hand.js is referenced or if the browser natively supports pointer events
  4224. if (!navigator.pointerEnabled) {
  4225. eventPrefix = "mouse";
  4226. }
  4227. return eventPrefix;
  4228. };
  4229. Tools.QueueNewFrame = function (func) {
  4230. if (window.requestAnimationFrame)
  4231. window.requestAnimationFrame(func);
  4232. else if (window.msRequestAnimationFrame)
  4233. window.msRequestAnimationFrame(func);
  4234. else if (window.webkitRequestAnimationFrame)
  4235. window.webkitRequestAnimationFrame(func);
  4236. else if (window.mozRequestAnimationFrame)
  4237. window.mozRequestAnimationFrame(func);
  4238. else if (window.oRequestAnimationFrame)
  4239. window.oRequestAnimationFrame(func);
  4240. else {
  4241. window.setTimeout(func, 16);
  4242. }
  4243. };
  4244. Tools.RequestFullscreen = function (element) {
  4245. if (element.requestFullscreen)
  4246. element.requestFullscreen();
  4247. else if (element.msRequestFullscreen)
  4248. element.msRequestFullscreen();
  4249. else if (element.webkitRequestFullscreen)
  4250. element.webkitRequestFullscreen();
  4251. else if (element.mozRequestFullScreen)
  4252. element.mozRequestFullScreen();
  4253. };
  4254. Tools.ExitFullscreen = function () {
  4255. if (document.exitFullscreen) {
  4256. document.exitFullscreen();
  4257. }
  4258. else if (document.mozCancelFullScreen) {
  4259. document.mozCancelFullScreen();
  4260. }
  4261. else if (document.webkitCancelFullScreen) {
  4262. document.webkitCancelFullScreen();
  4263. }
  4264. else if (document.msCancelFullScreen) {
  4265. document.msCancelFullScreen();
  4266. }
  4267. };
  4268. // External files
  4269. Tools.CleanUrl = function (url) {
  4270. url = url.replace(/#/mg, "%23");
  4271. return url;
  4272. };
  4273. Tools.LoadImage = function (url, onload, onerror, database) {
  4274. url = Tools.CleanUrl(url);
  4275. var img = new Image();
  4276. if (url.substr(0, 5) !== "data:")
  4277. img.crossOrigin = 'anonymous';
  4278. img.onload = function () {
  4279. onload(img);
  4280. };
  4281. img.onerror = function (err) {
  4282. onerror(img, err);
  4283. };
  4284. var noIndexedDB = function () {
  4285. img.src = url;
  4286. };
  4287. var loadFromIndexedDB = function () {
  4288. database.loadImageFromDB(url, img);
  4289. };
  4290. //ANY database to do!
  4291. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4292. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4293. }
  4294. else {
  4295. if (url.indexOf("file:") === -1) {
  4296. noIndexedDB();
  4297. }
  4298. else {
  4299. try {
  4300. var textureName = url.substring(5);
  4301. var blobURL;
  4302. try {
  4303. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4304. }
  4305. catch (ex) {
  4306. // Chrome doesn't support oneTimeOnly parameter
  4307. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4308. }
  4309. img.src = blobURL;
  4310. }
  4311. catch (e) {
  4312. Tools.Log("Error while trying to load texture: " + textureName);
  4313. img.src = null;
  4314. }
  4315. }
  4316. }
  4317. return img;
  4318. };
  4319. //ANY
  4320. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4321. url = Tools.CleanUrl(url);
  4322. var noIndexedDB = function () {
  4323. var request = new XMLHttpRequest();
  4324. var loadUrl = Tools.BaseUrl + url;
  4325. request.open('GET', loadUrl, true);
  4326. if (useArrayBuffer) {
  4327. request.responseType = "arraybuffer";
  4328. }
  4329. request.onprogress = progressCallBack;
  4330. request.onreadystatechange = function () {
  4331. if (request.readyState === 4) {
  4332. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4333. callback(!useArrayBuffer ? request.responseText : request.response);
  4334. }
  4335. else {
  4336. if (onError) {
  4337. onError();
  4338. }
  4339. else {
  4340. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4341. }
  4342. }
  4343. }
  4344. };
  4345. request.send(null);
  4346. };
  4347. var loadFromIndexedDB = function () {
  4348. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4349. };
  4350. if (url.indexOf("file:") !== -1) {
  4351. var fileName = url.substring(5);
  4352. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4353. }
  4354. else {
  4355. // Caching all files
  4356. if (database && database.enableSceneOffline) {
  4357. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4358. }
  4359. else {
  4360. noIndexedDB();
  4361. }
  4362. }
  4363. };
  4364. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4365. var reader = new FileReader();
  4366. reader.onload = function (e) {
  4367. //target doesn't have result from ts 1.3
  4368. callback(e.target['result']);
  4369. };
  4370. reader.onprogress = progressCallback;
  4371. reader.readAsDataURL(fileToLoad);
  4372. };
  4373. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4374. var reader = new FileReader();
  4375. reader.onerror = function (e) {
  4376. Tools.Log("Error while reading file: " + fileToLoad.name);
  4377. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4378. };
  4379. reader.onload = function (e) {
  4380. //target doesn't have result from ts 1.3
  4381. callback(e.target['result']);
  4382. };
  4383. reader.onprogress = progressCallBack;
  4384. if (!useArrayBuffer) {
  4385. // Asynchronous read
  4386. reader.readAsText(fileToLoad);
  4387. }
  4388. else {
  4389. reader.readAsArrayBuffer(fileToLoad);
  4390. }
  4391. };
  4392. // Misc.
  4393. Tools.Clamp = function (value, min, max) {
  4394. if (min === void 0) { min = 0; }
  4395. if (max === void 0) { max = 1; }
  4396. return Math.min(max, Math.max(min, value));
  4397. };
  4398. // Returns -1 when value is a negative number and
  4399. // +1 when value is a positive number.
  4400. Tools.Sign = function (value) {
  4401. value = +value; // convert to a number
  4402. if (value === 0 || isNaN(value))
  4403. return value;
  4404. return value > 0 ? 1 : -1;
  4405. };
  4406. Tools.Format = function (value, decimals) {
  4407. if (decimals === void 0) { decimals = 2; }
  4408. return value.toFixed(decimals);
  4409. };
  4410. Tools.CheckExtends = function (v, min, max) {
  4411. if (v.x < min.x)
  4412. min.x = v.x;
  4413. if (v.y < min.y)
  4414. min.y = v.y;
  4415. if (v.z < min.z)
  4416. min.z = v.z;
  4417. if (v.x > max.x)
  4418. max.x = v.x;
  4419. if (v.y > max.y)
  4420. max.y = v.y;
  4421. if (v.z > max.z)
  4422. max.z = v.z;
  4423. };
  4424. Tools.WithinEpsilon = function (a, b, epsilon) {
  4425. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4426. var num = a - b;
  4427. return -epsilon <= num && num <= epsilon;
  4428. };
  4429. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4430. for (var prop in source) {
  4431. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4432. continue;
  4433. }
  4434. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4435. continue;
  4436. }
  4437. var sourceValue = source[prop];
  4438. var typeOfSourceValue = typeof sourceValue;
  4439. if (typeOfSourceValue === "function") {
  4440. continue;
  4441. }
  4442. if (typeOfSourceValue === "object") {
  4443. if (sourceValue instanceof Array) {
  4444. destination[prop] = [];
  4445. if (sourceValue.length > 0) {
  4446. if (typeof sourceValue[0] == "object") {
  4447. for (var index = 0; index < sourceValue.length; index++) {
  4448. var clonedValue = cloneValue(sourceValue[index], destination);
  4449. if (destination[prop].indexOf(clonedValue) === -1) {
  4450. destination[prop].push(clonedValue);
  4451. }
  4452. }
  4453. }
  4454. else {
  4455. destination[prop] = sourceValue.slice(0);
  4456. }
  4457. }
  4458. }
  4459. else {
  4460. destination[prop] = cloneValue(sourceValue, destination);
  4461. }
  4462. }
  4463. else {
  4464. destination[prop] = sourceValue;
  4465. }
  4466. }
  4467. };
  4468. Tools.IsEmpty = function (obj) {
  4469. for (var i in obj) {
  4470. return false;
  4471. }
  4472. return true;
  4473. };
  4474. Tools.RegisterTopRootEvents = function (events) {
  4475. for (var index = 0; index < events.length; index++) {
  4476. var event = events[index];
  4477. window.addEventListener(event.name, event.handler, false);
  4478. try {
  4479. if (window.parent) {
  4480. window.parent.addEventListener(event.name, event.handler, false);
  4481. }
  4482. }
  4483. catch (e) {
  4484. }
  4485. }
  4486. };
  4487. Tools.UnregisterTopRootEvents = function (events) {
  4488. for (var index = 0; index < events.length; index++) {
  4489. var event = events[index];
  4490. window.removeEventListener(event.name, event.handler);
  4491. try {
  4492. if (window.parent) {
  4493. window.parent.removeEventListener(event.name, event.handler);
  4494. }
  4495. }
  4496. catch (e) {
  4497. }
  4498. }
  4499. };
  4500. Tools.DumpFramebuffer = function (width, height, engine) {
  4501. // Read the contents of the framebuffer
  4502. var numberOfChannelsByLine = width * 4;
  4503. var halfHeight = height / 2;
  4504. //Reading datas from WebGL
  4505. var data = engine.readPixels(0, 0, width, height);
  4506. for (var i = 0; i < halfHeight; i++) {
  4507. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4508. var currentCell = j + i * numberOfChannelsByLine;
  4509. var targetLine = height - i - 1;
  4510. var targetCell = j + targetLine * numberOfChannelsByLine;
  4511. var temp = data[currentCell];
  4512. data[currentCell] = data[targetCell];
  4513. data[targetCell] = temp;
  4514. }
  4515. }
  4516. // Create a 2D canvas to store the result
  4517. if (!screenshotCanvas) {
  4518. screenshotCanvas = document.createElement('canvas');
  4519. }
  4520. screenshotCanvas.width = width;
  4521. screenshotCanvas.height = height;
  4522. var context = screenshotCanvas.getContext('2d');
  4523. // Copy the pixels to a 2D canvas
  4524. var imageData = context.createImageData(width, height);
  4525. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4526. var castData = imageData.data;
  4527. castData.set(data);
  4528. context.putImageData(imageData, 0, 0);
  4529. var base64Image = screenshotCanvas.toDataURL();
  4530. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4531. if (("download" in document.createElement("a"))) {
  4532. var a = window.document.createElement("a");
  4533. a.href = base64Image;
  4534. var date = new Date();
  4535. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4536. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4537. window.document.body.appendChild(a);
  4538. a.addEventListener("click", function () {
  4539. a.parentElement.removeChild(a);
  4540. });
  4541. a.click();
  4542. }
  4543. else {
  4544. var newWindow = window.open("");
  4545. var img = newWindow.document.createElement("img");
  4546. img.src = base64Image;
  4547. newWindow.document.body.appendChild(img);
  4548. }
  4549. };
  4550. Tools.CreateScreenshot = function (engine, camera, size) {
  4551. var width;
  4552. var height;
  4553. var scene = camera.getScene();
  4554. var previousCamera = null;
  4555. if (scene.activeCamera !== camera) {
  4556. previousCamera = scene.activeCamera;
  4557. scene.activeCamera = camera;
  4558. }
  4559. //If a precision value is specified
  4560. if (size.precision) {
  4561. width = Math.round(engine.getRenderWidth() * size.precision);
  4562. height = Math.round(width / engine.getAspectRatio(camera));
  4563. size = { width: width, height: height };
  4564. }
  4565. else if (size.width && size.height) {
  4566. width = size.width;
  4567. height = size.height;
  4568. }
  4569. else if (size.width && !size.height) {
  4570. width = size.width;
  4571. height = Math.round(width / engine.getAspectRatio(camera));
  4572. size = { width: width, height: height };
  4573. }
  4574. else if (size.height && !size.width) {
  4575. height = size.height;
  4576. width = Math.round(height * engine.getAspectRatio(camera));
  4577. size = { width: width, height: height };
  4578. }
  4579. else if (!isNaN(size)) {
  4580. height = size;
  4581. width = size;
  4582. }
  4583. else {
  4584. Tools.Error("Invalid 'size' parameter !");
  4585. return;
  4586. }
  4587. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4588. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4589. texture.renderList = scene.meshes;
  4590. texture.onAfterRender = function () {
  4591. Tools.DumpFramebuffer(width, height, engine);
  4592. };
  4593. scene.incrementRenderId();
  4594. texture.render(true);
  4595. texture.dispose();
  4596. if (previousCamera) {
  4597. scene.activeCamera = previousCamera;
  4598. }
  4599. };
  4600. // XHR response validator for local file scenario
  4601. Tools.ValidateXHRData = function (xhr, dataType) {
  4602. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4603. if (dataType === void 0) { dataType = 7; }
  4604. try {
  4605. if (dataType & 1) {
  4606. if (xhr.responseText && xhr.responseText.length > 0) {
  4607. return true;
  4608. }
  4609. else if (dataType === 1) {
  4610. return false;
  4611. }
  4612. }
  4613. if (dataType & 2) {
  4614. // Check header width and height since there is no "TGA" magic number
  4615. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4616. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4617. return true;
  4618. }
  4619. else if (dataType === 2) {
  4620. return false;
  4621. }
  4622. }
  4623. if (dataType & 4) {
  4624. // Check for the "DDS" magic number
  4625. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4626. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4627. return true;
  4628. }
  4629. else {
  4630. return false;
  4631. }
  4632. }
  4633. }
  4634. catch (e) {
  4635. }
  4636. return false;
  4637. };
  4638. Object.defineProperty(Tools, "NoneLogLevel", {
  4639. get: function () {
  4640. return Tools._NoneLogLevel;
  4641. },
  4642. enumerable: true,
  4643. configurable: true
  4644. });
  4645. Object.defineProperty(Tools, "MessageLogLevel", {
  4646. get: function () {
  4647. return Tools._MessageLogLevel;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Object.defineProperty(Tools, "WarningLogLevel", {
  4653. get: function () {
  4654. return Tools._WarningLogLevel;
  4655. },
  4656. enumerable: true,
  4657. configurable: true
  4658. });
  4659. Object.defineProperty(Tools, "ErrorLogLevel", {
  4660. get: function () {
  4661. return Tools._ErrorLogLevel;
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(Tools, "AllLogLevel", {
  4667. get: function () {
  4668. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4669. },
  4670. enumerable: true,
  4671. configurable: true
  4672. });
  4673. Tools._AddLogEntry = function (entry) {
  4674. Tools._LogCache = entry + Tools._LogCache;
  4675. if (Tools.OnNewCacheEntry) {
  4676. Tools.OnNewCacheEntry(entry);
  4677. }
  4678. };
  4679. Tools._FormatMessage = function (message) {
  4680. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4681. var date = new Date();
  4682. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4683. };
  4684. Tools._LogDisabled = function (message) {
  4685. // nothing to do
  4686. };
  4687. Tools._LogEnabled = function (message) {
  4688. var formattedMessage = Tools._FormatMessage(message);
  4689. console.log("BJS - " + formattedMessage);
  4690. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4691. Tools._AddLogEntry(entry);
  4692. };
  4693. Tools._WarnDisabled = function (message) {
  4694. // nothing to do
  4695. };
  4696. Tools._WarnEnabled = function (message) {
  4697. var formattedMessage = Tools._FormatMessage(message);
  4698. console.warn("BJS - " + formattedMessage);
  4699. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4700. Tools._AddLogEntry(entry);
  4701. };
  4702. Tools._ErrorDisabled = function (message) {
  4703. // nothing to do
  4704. };
  4705. Tools._ErrorEnabled = function (message) {
  4706. var formattedMessage = Tools._FormatMessage(message);
  4707. console.error("BJS - " + formattedMessage);
  4708. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4709. Tools._AddLogEntry(entry);
  4710. };
  4711. Object.defineProperty(Tools, "LogCache", {
  4712. get: function () {
  4713. return Tools._LogCache;
  4714. },
  4715. enumerable: true,
  4716. configurable: true
  4717. });
  4718. Object.defineProperty(Tools, "LogLevels", {
  4719. set: function (level) {
  4720. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4721. Tools.Log = Tools._LogEnabled;
  4722. }
  4723. else {
  4724. Tools.Log = Tools._LogDisabled;
  4725. }
  4726. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4727. Tools.Warn = Tools._WarnEnabled;
  4728. }
  4729. else {
  4730. Tools.Warn = Tools._WarnDisabled;
  4731. }
  4732. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4733. Tools.Error = Tools._ErrorEnabled;
  4734. }
  4735. else {
  4736. Tools.Error = Tools._ErrorDisabled;
  4737. }
  4738. },
  4739. enumerable: true,
  4740. configurable: true
  4741. });
  4742. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4743. get: function () {
  4744. return Tools._PerformanceNoneLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4750. get: function () {
  4751. return Tools._PerformanceUserMarkLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4757. get: function () {
  4758. return Tools._PerformanceConsoleLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4764. set: function (level) {
  4765. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4766. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4767. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4768. return;
  4769. }
  4770. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4771. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4772. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4773. return;
  4774. }
  4775. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4776. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4777. },
  4778. enumerable: true,
  4779. configurable: true
  4780. });
  4781. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4782. };
  4783. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4784. };
  4785. Tools._StartUserMark = function (counterName, condition) {
  4786. if (condition === void 0) { condition = true; }
  4787. if (!condition || !Tools._performance.mark) {
  4788. return;
  4789. }
  4790. Tools._performance.mark(counterName + "-Begin");
  4791. };
  4792. Tools._EndUserMark = function (counterName, condition) {
  4793. if (condition === void 0) { condition = true; }
  4794. if (!condition || !Tools._performance.mark) {
  4795. return;
  4796. }
  4797. Tools._performance.mark(counterName + "-End");
  4798. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4799. };
  4800. Tools._StartPerformanceConsole = function (counterName, condition) {
  4801. if (condition === void 0) { condition = true; }
  4802. if (!condition) {
  4803. return;
  4804. }
  4805. Tools._StartUserMark(counterName, condition);
  4806. if (console.time) {
  4807. console.time(counterName);
  4808. }
  4809. };
  4810. Tools._EndPerformanceConsole = function (counterName, condition) {
  4811. if (condition === void 0) { condition = true; }
  4812. if (!condition) {
  4813. return;
  4814. }
  4815. Tools._EndUserMark(counterName, condition);
  4816. if (console.time) {
  4817. console.timeEnd(counterName);
  4818. }
  4819. };
  4820. Object.defineProperty(Tools, "Now", {
  4821. get: function () {
  4822. if (window.performance && window.performance.now) {
  4823. return window.performance.now();
  4824. }
  4825. return new Date().getTime();
  4826. },
  4827. enumerable: true,
  4828. configurable: true
  4829. });
  4830. // Deprecated
  4831. Tools.GetFps = function () {
  4832. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4833. return 0;
  4834. };
  4835. Tools.BaseUrl = "";
  4836. // Logs
  4837. Tools._NoneLogLevel = 0;
  4838. Tools._MessageLogLevel = 1;
  4839. Tools._WarningLogLevel = 2;
  4840. Tools._ErrorLogLevel = 4;
  4841. Tools._LogCache = "";
  4842. Tools.Log = Tools._LogEnabled;
  4843. Tools.Warn = Tools._WarnEnabled;
  4844. Tools.Error = Tools._ErrorEnabled;
  4845. // Performances
  4846. Tools._PerformanceNoneLogLevel = 0;
  4847. Tools._PerformanceUserMarkLogLevel = 1;
  4848. Tools._PerformanceConsoleLogLevel = 2;
  4849. Tools._performance = window.performance;
  4850. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4851. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4852. return Tools;
  4853. })();
  4854. BABYLON.Tools = Tools;
  4855. /**
  4856. * An implementation of a loop for asynchronous functions.
  4857. */
  4858. var AsyncLoop = (function () {
  4859. /**
  4860. * Constroctor.
  4861. * @param iterations the number of iterations.
  4862. * @param _fn the function to run each iteration
  4863. * @param _successCallback the callback that will be called upon succesful execution
  4864. * @param offset starting offset.
  4865. */
  4866. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4867. if (offset === void 0) { offset = 0; }
  4868. this.iterations = iterations;
  4869. this._fn = _fn;
  4870. this._successCallback = _successCallback;
  4871. this.index = offset - 1;
  4872. this._done = false;
  4873. }
  4874. /**
  4875. * Execute the next iteration. Must be called after the last iteration was finished.
  4876. */
  4877. AsyncLoop.prototype.executeNext = function () {
  4878. if (!this._done) {
  4879. if (this.index + 1 < this.iterations) {
  4880. ++this.index;
  4881. this._fn(this);
  4882. }
  4883. else {
  4884. this.breakLoop();
  4885. }
  4886. }
  4887. };
  4888. /**
  4889. * Break the loop and run the success callback.
  4890. */
  4891. AsyncLoop.prototype.breakLoop = function () {
  4892. this._done = true;
  4893. this._successCallback();
  4894. };
  4895. /**
  4896. * Helper function
  4897. */
  4898. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4899. if (offset === void 0) { offset = 0; }
  4900. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4901. loop.executeNext();
  4902. return loop;
  4903. };
  4904. /**
  4905. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4906. * @param iterations total number of iterations
  4907. * @param syncedIterations number of synchronous iterations in each async iteration.
  4908. * @param fn the function to call each iteration.
  4909. * @param callback a success call back that will be called when iterating stops.
  4910. * @param breakFunction a break condition (optional)
  4911. * @param timeout timeout settings for the setTimeout function. default - 0.
  4912. * @constructor
  4913. */
  4914. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4915. if (timeout === void 0) { timeout = 0; }
  4916. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4917. if (breakFunction && breakFunction())
  4918. loop.breakLoop();
  4919. else {
  4920. setTimeout(function () {
  4921. for (var i = 0; i < syncedIterations; ++i) {
  4922. var iteration = (loop.index * syncedIterations) + i;
  4923. if (iteration >= iterations)
  4924. break;
  4925. fn(iteration);
  4926. if (breakFunction && breakFunction()) {
  4927. loop.breakLoop();
  4928. break;
  4929. }
  4930. }
  4931. loop.executeNext();
  4932. }, timeout);
  4933. }
  4934. }, callback);
  4935. };
  4936. return AsyncLoop;
  4937. })();
  4938. BABYLON.AsyncLoop = AsyncLoop;
  4939. })(BABYLON || (BABYLON = {}));
  4940. //# sourceMappingURL=babylon.tools.js.map
  4941. var BABYLON;
  4942. (function (BABYLON) {
  4943. var _DepthCullingState = (function () {
  4944. function _DepthCullingState() {
  4945. this._isDepthTestDirty = false;
  4946. this._isDepthMaskDirty = false;
  4947. this._isDepthFuncDirty = false;
  4948. this._isCullFaceDirty = false;
  4949. this._isCullDirty = false;
  4950. this._isZOffsetDirty = false;
  4951. }
  4952. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4953. get: function () {
  4954. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4955. },
  4956. enumerable: true,
  4957. configurable: true
  4958. });
  4959. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4960. get: function () {
  4961. return this._zOffset;
  4962. },
  4963. set: function (value) {
  4964. if (this._zOffset === value) {
  4965. return;
  4966. }
  4967. this._zOffset = value;
  4968. this._isZOffsetDirty = true;
  4969. },
  4970. enumerable: true,
  4971. configurable: true
  4972. });
  4973. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4974. get: function () {
  4975. return this._cullFace;
  4976. },
  4977. set: function (value) {
  4978. if (this._cullFace === value) {
  4979. return;
  4980. }
  4981. this._cullFace = value;
  4982. this._isCullFaceDirty = true;
  4983. },
  4984. enumerable: true,
  4985. configurable: true
  4986. });
  4987. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4988. get: function () {
  4989. return this._cull;
  4990. },
  4991. set: function (value) {
  4992. if (this._cull === value) {
  4993. return;
  4994. }
  4995. this._cull = value;
  4996. this._isCullDirty = true;
  4997. },
  4998. enumerable: true,
  4999. configurable: true
  5000. });
  5001. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5002. get: function () {
  5003. return this._depthFunc;
  5004. },
  5005. set: function (value) {
  5006. if (this._depthFunc === value) {
  5007. return;
  5008. }
  5009. this._depthFunc = value;
  5010. this._isDepthFuncDirty = true;
  5011. },
  5012. enumerable: true,
  5013. configurable: true
  5014. });
  5015. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5016. get: function () {
  5017. return this._depthMask;
  5018. },
  5019. set: function (value) {
  5020. if (this._depthMask === value) {
  5021. return;
  5022. }
  5023. this._depthMask = value;
  5024. this._isDepthMaskDirty = true;
  5025. },
  5026. enumerable: true,
  5027. configurable: true
  5028. });
  5029. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5030. get: function () {
  5031. return this._depthTest;
  5032. },
  5033. set: function (value) {
  5034. if (this._depthTest === value) {
  5035. return;
  5036. }
  5037. this._depthTest = value;
  5038. this._isDepthTestDirty = true;
  5039. },
  5040. enumerable: true,
  5041. configurable: true
  5042. });
  5043. _DepthCullingState.prototype.reset = function () {
  5044. this._depthMask = true;
  5045. this._depthTest = true;
  5046. this._depthFunc = null;
  5047. this._cull = null;
  5048. this._cullFace = null;
  5049. this._zOffset = 0;
  5050. this._isDepthTestDirty = true;
  5051. this._isDepthMaskDirty = true;
  5052. this._isDepthFuncDirty = false;
  5053. this._isCullFaceDirty = false;
  5054. this._isCullDirty = false;
  5055. this._isZOffsetDirty = false;
  5056. };
  5057. _DepthCullingState.prototype.apply = function (gl) {
  5058. if (!this.isDirty) {
  5059. return;
  5060. }
  5061. // Cull
  5062. if (this._isCullDirty) {
  5063. if (this.cull) {
  5064. gl.enable(gl.CULL_FACE);
  5065. }
  5066. else {
  5067. gl.disable(gl.CULL_FACE);
  5068. }
  5069. this._isCullDirty = false;
  5070. }
  5071. // Cull face
  5072. if (this._isCullFaceDirty) {
  5073. gl.cullFace(this.cullFace);
  5074. this._isCullFaceDirty = false;
  5075. }
  5076. // Depth mask
  5077. if (this._isDepthMaskDirty) {
  5078. gl.depthMask(this.depthMask);
  5079. this._isDepthMaskDirty = false;
  5080. }
  5081. // Depth test
  5082. if (this._isDepthTestDirty) {
  5083. if (this.depthTest) {
  5084. gl.enable(gl.DEPTH_TEST);
  5085. }
  5086. else {
  5087. gl.disable(gl.DEPTH_TEST);
  5088. }
  5089. this._isDepthTestDirty = false;
  5090. }
  5091. // Depth func
  5092. if (this._isDepthFuncDirty) {
  5093. gl.depthFunc(this.depthFunc);
  5094. this._isDepthFuncDirty = false;
  5095. }
  5096. // zOffset
  5097. if (this._isZOffsetDirty) {
  5098. if (this.zOffset) {
  5099. gl.enable(gl.POLYGON_OFFSET_FILL);
  5100. gl.polygonOffset(this.zOffset, 0);
  5101. }
  5102. else {
  5103. gl.disable(gl.POLYGON_OFFSET_FILL);
  5104. }
  5105. this._isZOffsetDirty = false;
  5106. }
  5107. };
  5108. return _DepthCullingState;
  5109. })();
  5110. BABYLON._DepthCullingState = _DepthCullingState;
  5111. var _AlphaState = (function () {
  5112. function _AlphaState() {
  5113. this._isAlphaBlendDirty = false;
  5114. this._isBlendFunctionParametersDirty = false;
  5115. this._alphaBlend = false;
  5116. this._blendFunctionParameters = new Array(4);
  5117. }
  5118. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5119. get: function () {
  5120. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5121. },
  5122. enumerable: true,
  5123. configurable: true
  5124. });
  5125. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5126. get: function () {
  5127. return this._alphaBlend;
  5128. },
  5129. set: function (value) {
  5130. if (this._alphaBlend === value) {
  5131. return;
  5132. }
  5133. this._alphaBlend = value;
  5134. this._isAlphaBlendDirty = true;
  5135. },
  5136. enumerable: true,
  5137. configurable: true
  5138. });
  5139. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5140. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  5141. return;
  5142. }
  5143. this._blendFunctionParameters[0] = value0;
  5144. this._blendFunctionParameters[1] = value1;
  5145. this._blendFunctionParameters[2] = value2;
  5146. this._blendFunctionParameters[3] = value3;
  5147. this._isBlendFunctionParametersDirty = true;
  5148. };
  5149. _AlphaState.prototype.reset = function () {
  5150. this._alphaBlend = false;
  5151. this._blendFunctionParameters[0] = null;
  5152. this._blendFunctionParameters[1] = null;
  5153. this._blendFunctionParameters[2] = null;
  5154. this._blendFunctionParameters[3] = null;
  5155. this._isAlphaBlendDirty = true;
  5156. this._isBlendFunctionParametersDirty = false;
  5157. };
  5158. _AlphaState.prototype.apply = function (gl) {
  5159. if (!this.isDirty) {
  5160. return;
  5161. }
  5162. // Alpha blend
  5163. if (this._isAlphaBlendDirty) {
  5164. if (this._alphaBlend) {
  5165. gl.enable(gl.BLEND);
  5166. }
  5167. else {
  5168. gl.disable(gl.BLEND);
  5169. }
  5170. this._isAlphaBlendDirty = false;
  5171. }
  5172. // Alpha function
  5173. if (this._isBlendFunctionParametersDirty) {
  5174. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5175. this._isBlendFunctionParametersDirty = false;
  5176. }
  5177. };
  5178. return _AlphaState;
  5179. })();
  5180. BABYLON._AlphaState = _AlphaState;
  5181. var compileShader = function (gl, source, type, defines) {
  5182. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5183. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5184. gl.compileShader(shader);
  5185. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5186. throw new Error(gl.getShaderInfoLog(shader));
  5187. }
  5188. return shader;
  5189. };
  5190. var getWebGLTextureType = function (gl, type) {
  5191. var textureType = gl.UNSIGNED_BYTE;
  5192. if (type === Engine.TEXTURETYPE_FLOAT)
  5193. textureType = gl.FLOAT;
  5194. return textureType;
  5195. };
  5196. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5197. var magFilter = gl.NEAREST;
  5198. var minFilter = gl.NEAREST;
  5199. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5200. magFilter = gl.LINEAR;
  5201. if (generateMipMaps) {
  5202. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5203. }
  5204. else {
  5205. minFilter = gl.LINEAR;
  5206. }
  5207. }
  5208. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5209. magFilter = gl.LINEAR;
  5210. if (generateMipMaps) {
  5211. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5212. }
  5213. else {
  5214. minFilter = gl.LINEAR;
  5215. }
  5216. }
  5217. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5218. magFilter = gl.NEAREST;
  5219. if (generateMipMaps) {
  5220. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5221. }
  5222. else {
  5223. minFilter = gl.NEAREST;
  5224. }
  5225. }
  5226. return {
  5227. min: minFilter,
  5228. mag: magFilter
  5229. };
  5230. };
  5231. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5233. var engine = scene.getEngine();
  5234. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5235. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5236. gl.bindTexture(gl.TEXTURE_2D, texture);
  5237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5238. texture._baseWidth = width;
  5239. texture._baseHeight = height;
  5240. texture._width = potWidth;
  5241. texture._height = potHeight;
  5242. texture.isReady = true;
  5243. processFunction(potWidth, potHeight);
  5244. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5247. if (!noMipmap && !isCompressed) {
  5248. gl.generateMipmap(gl.TEXTURE_2D);
  5249. }
  5250. gl.bindTexture(gl.TEXTURE_2D, null);
  5251. engine._activeTexturesCache = [];
  5252. scene._removePendingData(texture);
  5253. };
  5254. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5255. var onload = function () {
  5256. loadedImages[index] = img;
  5257. loadedImages._internalCount++;
  5258. scene._removePendingData(img);
  5259. if (loadedImages._internalCount === 6) {
  5260. onfinish(loadedImages);
  5261. }
  5262. };
  5263. var onerror = function () {
  5264. scene._removePendingData(img);
  5265. };
  5266. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5267. scene._addPendingData(img);
  5268. };
  5269. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5270. var loadedImages = [];
  5271. loadedImages._internalCount = 0;
  5272. for (var index = 0; index < 6; index++) {
  5273. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5274. }
  5275. };
  5276. var EngineCapabilities = (function () {
  5277. function EngineCapabilities() {
  5278. }
  5279. return EngineCapabilities;
  5280. })();
  5281. BABYLON.EngineCapabilities = EngineCapabilities;
  5282. /**
  5283. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5284. */
  5285. var Engine = (function () {
  5286. /**
  5287. * @constructor
  5288. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5289. * @param {boolean} [antialias] - enable antialias
  5290. * @param options - further options to be sent to the getContext function
  5291. */
  5292. function Engine(canvas, antialias, options) {
  5293. var _this = this;
  5294. // Public members
  5295. this.isFullscreen = false;
  5296. this.isPointerLock = false;
  5297. this.cullBackFaces = true;
  5298. this.renderEvenInBackground = true;
  5299. this.scenes = new Array();
  5300. this._windowIsBackground = false;
  5301. this._loadingDivBackgroundColor = "black";
  5302. this._drawCalls = 0;
  5303. this._renderingQueueLaunched = false;
  5304. this._activeRenderLoops = [];
  5305. // FPS
  5306. this.fpsRange = 60;
  5307. this.previousFramesDuration = [];
  5308. this.fps = 60;
  5309. this.deltaTime = 0;
  5310. // States
  5311. this._depthCullingState = new _DepthCullingState();
  5312. this._alphaState = new _AlphaState();
  5313. this._alphaMode = Engine.ALPHA_DISABLE;
  5314. // Cache
  5315. this._loadedTexturesCache = new Array();
  5316. this._activeTexturesCache = new Array();
  5317. this._compiledEffects = {};
  5318. this._uintIndicesCurrentlySet = false;
  5319. this._renderingCanvas = canvas;
  5320. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5321. options = options || {};
  5322. options.antialias = antialias;
  5323. try {
  5324. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5325. }
  5326. catch (e) {
  5327. throw new Error("WebGL not supported");
  5328. }
  5329. if (!this._gl) {
  5330. throw new Error("WebGL not supported");
  5331. }
  5332. this._onBlur = function () {
  5333. _this._windowIsBackground = true;
  5334. };
  5335. this._onFocus = function () {
  5336. _this._windowIsBackground = false;
  5337. };
  5338. window.addEventListener("blur", this._onBlur);
  5339. window.addEventListener("focus", this._onFocus);
  5340. // Viewport
  5341. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5342. this.resize();
  5343. // Caps
  5344. this._caps = new EngineCapabilities();
  5345. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5346. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5347. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5348. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5349. // Infos
  5350. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5351. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5352. if (rendererInfo != null) {
  5353. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5354. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5355. }
  5356. if (!this._glVendor) {
  5357. this._glVendor = "Unknown vendor";
  5358. }
  5359. if (!this._glRenderer) {
  5360. this._glRenderer = "Unknown renderer";
  5361. }
  5362. // Extensions
  5363. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5364. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5365. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5366. 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');
  5367. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5368. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5369. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5370. this._caps.highPrecisionShaderSupported = true;
  5371. if (this._gl.getShaderPrecisionFormat) {
  5372. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5373. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5374. }
  5375. // Depth buffer
  5376. this.setDepthBuffer(true);
  5377. this.setDepthFunctionToLessOrEqual();
  5378. this.setDepthWrite(true);
  5379. // Fullscreen
  5380. this._onFullscreenChange = function () {
  5381. if (document.fullscreen !== undefined) {
  5382. _this.isFullscreen = document.fullscreen;
  5383. }
  5384. else if (document.mozFullScreen !== undefined) {
  5385. _this.isFullscreen = document.mozFullScreen;
  5386. }
  5387. else if (document.webkitIsFullScreen !== undefined) {
  5388. _this.isFullscreen = document.webkitIsFullScreen;
  5389. }
  5390. else if (document.msIsFullScreen !== undefined) {
  5391. _this.isFullscreen = document.msIsFullScreen;
  5392. }
  5393. // Pointer lock
  5394. if (_this.isFullscreen && _this._pointerLockRequested) {
  5395. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  5396. if (canvas.requestPointerLock) {
  5397. canvas.requestPointerLock();
  5398. }
  5399. }
  5400. };
  5401. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5402. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5403. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5404. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5405. // Pointer lock
  5406. this._onPointerLockChange = function () {
  5407. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  5408. };
  5409. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5410. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5411. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5412. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5413. if (!Engine.audioEngine) {
  5414. Engine.audioEngine = new BABYLON.AudioEngine();
  5415. }
  5416. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5417. }
  5418. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5419. get: function () {
  5420. return Engine._ALPHA_DISABLE;
  5421. },
  5422. enumerable: true,
  5423. configurable: true
  5424. });
  5425. Object.defineProperty(Engine, "ALPHA_ADD", {
  5426. get: function () {
  5427. return Engine._ALPHA_ADD;
  5428. },
  5429. enumerable: true,
  5430. configurable: true
  5431. });
  5432. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5433. get: function () {
  5434. return Engine._ALPHA_COMBINE;
  5435. },
  5436. enumerable: true,
  5437. configurable: true
  5438. });
  5439. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5440. get: function () {
  5441. return Engine._DELAYLOADSTATE_NONE;
  5442. },
  5443. enumerable: true,
  5444. configurable: true
  5445. });
  5446. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5447. get: function () {
  5448. return Engine._DELAYLOADSTATE_LOADED;
  5449. },
  5450. enumerable: true,
  5451. configurable: true
  5452. });
  5453. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5454. get: function () {
  5455. return Engine._DELAYLOADSTATE_LOADING;
  5456. },
  5457. enumerable: true,
  5458. configurable: true
  5459. });
  5460. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5461. get: function () {
  5462. return Engine._DELAYLOADSTATE_NOTLOADED;
  5463. },
  5464. enumerable: true,
  5465. configurable: true
  5466. });
  5467. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5468. get: function () {
  5469. return Engine._TEXTUREFORMAT_ALPHA;
  5470. },
  5471. enumerable: true,
  5472. configurable: true
  5473. });
  5474. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5475. get: function () {
  5476. return Engine._TEXTUREFORMAT_LUMINANCE;
  5477. },
  5478. enumerable: true,
  5479. configurable: true
  5480. });
  5481. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5482. get: function () {
  5483. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5484. },
  5485. enumerable: true,
  5486. configurable: true
  5487. });
  5488. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5489. get: function () {
  5490. return Engine._TEXTUREFORMAT_RGB;
  5491. },
  5492. enumerable: true,
  5493. configurable: true
  5494. });
  5495. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5496. get: function () {
  5497. return Engine._TEXTUREFORMAT_RGBA;
  5498. },
  5499. enumerable: true,
  5500. configurable: true
  5501. });
  5502. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5503. get: function () {
  5504. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5505. },
  5506. enumerable: true,
  5507. configurable: true
  5508. });
  5509. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5510. get: function () {
  5511. return Engine._TEXTURETYPE_FLOAT;
  5512. },
  5513. enumerable: true,
  5514. configurable: true
  5515. });
  5516. Object.defineProperty(Engine, "Version", {
  5517. get: function () {
  5518. return "2.1.0 beta";
  5519. },
  5520. enumerable: true,
  5521. configurable: true
  5522. });
  5523. Engine.prototype._prepareWorkingCanvas = function () {
  5524. if (this._workingCanvas) {
  5525. return;
  5526. }
  5527. this._workingCanvas = document.createElement("canvas");
  5528. this._workingContext = this._workingCanvas.getContext("2d");
  5529. };
  5530. Engine.prototype.getGlInfo = function () {
  5531. return {
  5532. vendor: this._glVendor,
  5533. renderer: this._glRenderer,
  5534. version: this._glVersion
  5535. };
  5536. };
  5537. Engine.prototype.getAspectRatio = function (camera) {
  5538. var viewport = camera.viewport;
  5539. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5540. };
  5541. Engine.prototype.getRenderWidth = function () {
  5542. if (this._currentRenderTarget) {
  5543. return this._currentRenderTarget._width;
  5544. }
  5545. return this._renderingCanvas.width;
  5546. };
  5547. Engine.prototype.getRenderHeight = function () {
  5548. if (this._currentRenderTarget) {
  5549. return this._currentRenderTarget._height;
  5550. }
  5551. return this._renderingCanvas.height;
  5552. };
  5553. Engine.prototype.getRenderingCanvas = function () {
  5554. return this._renderingCanvas;
  5555. };
  5556. Engine.prototype.getRenderingCanvasClientRect = function () {
  5557. return this._renderingCanvas.getBoundingClientRect();
  5558. };
  5559. Engine.prototype.setHardwareScalingLevel = function (level) {
  5560. this._hardwareScalingLevel = level;
  5561. this.resize();
  5562. };
  5563. Engine.prototype.getHardwareScalingLevel = function () {
  5564. return this._hardwareScalingLevel;
  5565. };
  5566. Engine.prototype.getLoadedTexturesCache = function () {
  5567. return this._loadedTexturesCache;
  5568. };
  5569. Engine.prototype.getCaps = function () {
  5570. return this._caps;
  5571. };
  5572. Object.defineProperty(Engine.prototype, "drawCalls", {
  5573. get: function () {
  5574. return this._drawCalls;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. // Methods
  5580. Engine.prototype.resetDrawCalls = function () {
  5581. this._drawCalls = 0;
  5582. };
  5583. Engine.prototype.setDepthFunctionToGreater = function () {
  5584. this._depthCullingState.depthFunc = this._gl.GREATER;
  5585. };
  5586. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5587. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5588. };
  5589. Engine.prototype.setDepthFunctionToLess = function () {
  5590. this._depthCullingState.depthFunc = this._gl.LESS;
  5591. };
  5592. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5593. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5594. };
  5595. /**
  5596. * stop executing a render loop function and remove it from the execution array
  5597. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5598. */
  5599. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5600. if (!renderFunction) {
  5601. this._activeRenderLoops = [];
  5602. return;
  5603. }
  5604. var index = this._activeRenderLoops.indexOf(renderFunction);
  5605. if (index >= 0) {
  5606. this._activeRenderLoops.splice(index, 1);
  5607. }
  5608. };
  5609. Engine.prototype._renderLoop = function () {
  5610. var _this = this;
  5611. var shouldRender = true;
  5612. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5613. shouldRender = false;
  5614. }
  5615. if (shouldRender) {
  5616. // Start new frame
  5617. this.beginFrame();
  5618. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5619. var renderFunction = this._activeRenderLoops[index];
  5620. renderFunction();
  5621. }
  5622. // Present
  5623. this.endFrame();
  5624. }
  5625. if (this._activeRenderLoops.length > 0) {
  5626. // Register new frame
  5627. BABYLON.Tools.QueueNewFrame(function () {
  5628. _this._renderLoop();
  5629. });
  5630. }
  5631. else {
  5632. this._renderingQueueLaunched = false;
  5633. }
  5634. };
  5635. /**
  5636. * Register and execute a render loop. The engine can have more than one render function.
  5637. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5638. * @example
  5639. * engine.runRenderLoop(function () {
  5640. * scene.render()
  5641. * })
  5642. */
  5643. Engine.prototype.runRenderLoop = function (renderFunction) {
  5644. var _this = this;
  5645. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5646. return;
  5647. }
  5648. this._activeRenderLoops.push(renderFunction);
  5649. if (!this._renderingQueueLaunched) {
  5650. this._renderingQueueLaunched = true;
  5651. BABYLON.Tools.QueueNewFrame(function () {
  5652. _this._renderLoop();
  5653. });
  5654. }
  5655. };
  5656. /**
  5657. * Toggle full screen mode.
  5658. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5659. */
  5660. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5661. if (this.isFullscreen) {
  5662. BABYLON.Tools.ExitFullscreen();
  5663. }
  5664. else {
  5665. this._pointerLockRequested = requestPointerLock;
  5666. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5667. }
  5668. };
  5669. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5670. this.applyStates();
  5671. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5672. if (this._depthCullingState.depthMask) {
  5673. this._gl.clearDepth(1.0);
  5674. }
  5675. var mode = 0;
  5676. if (backBuffer)
  5677. mode |= this._gl.COLOR_BUFFER_BIT;
  5678. if (depthStencil && this._depthCullingState.depthMask)
  5679. mode |= this._gl.DEPTH_BUFFER_BIT;
  5680. this._gl.clear(mode);
  5681. };
  5682. /**
  5683. * Set the WebGL's viewport
  5684. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5685. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5686. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5687. */
  5688. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5689. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5690. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5691. var x = viewport.x || 0;
  5692. var y = viewport.y || 0;
  5693. this._cachedViewport = viewport;
  5694. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5695. };
  5696. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5697. this._cachedViewport = null;
  5698. this._gl.viewport(x, y, width, height);
  5699. };
  5700. Engine.prototype.beginFrame = function () {
  5701. this._measureFps();
  5702. };
  5703. Engine.prototype.endFrame = function () {
  5704. //this.flushFramebuffer();
  5705. };
  5706. /**
  5707. * resize the view according to the canvas' size.
  5708. * @example
  5709. * window.addEventListener("resize", function () {
  5710. * engine.resize();
  5711. * });
  5712. */
  5713. Engine.prototype.resize = function () {
  5714. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5715. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5716. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5717. };
  5718. /**
  5719. * force a specific size of the canvas
  5720. * @param {number} width - the new canvas' width
  5721. * @param {number} height - the new canvas' height
  5722. */
  5723. Engine.prototype.setSize = function (width, height) {
  5724. this._renderingCanvas.width = width;
  5725. this._renderingCanvas.height = height;
  5726. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5727. for (var index = 0; index < this.scenes.length; index++) {
  5728. var scene = this.scenes[index];
  5729. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5730. var cam = scene.cameras[camIndex];
  5731. cam._currentRenderId = 0;
  5732. }
  5733. }
  5734. };
  5735. Engine.prototype.bindFramebuffer = function (texture) {
  5736. this._currentRenderTarget = texture;
  5737. var gl = this._gl;
  5738. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5739. this._gl.viewport(0, 0, texture._width, texture._height);
  5740. this.wipeCaches();
  5741. };
  5742. Engine.prototype.unBindFramebuffer = function (texture) {
  5743. this._currentRenderTarget = null;
  5744. if (texture.generateMipMaps) {
  5745. var gl = this._gl;
  5746. gl.bindTexture(gl.TEXTURE_2D, texture);
  5747. gl.generateMipmap(gl.TEXTURE_2D);
  5748. gl.bindTexture(gl.TEXTURE_2D, null);
  5749. }
  5750. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5751. };
  5752. Engine.prototype.flushFramebuffer = function () {
  5753. this._gl.flush();
  5754. };
  5755. Engine.prototype.restoreDefaultFramebuffer = function () {
  5756. this._currentRenderTarget = null;
  5757. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5758. this.setViewport(this._cachedViewport);
  5759. this.wipeCaches();
  5760. };
  5761. // VBOs
  5762. Engine.prototype._resetVertexBufferBinding = function () {
  5763. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5764. this._cachedVertexBuffers = null;
  5765. };
  5766. Engine.prototype.createVertexBuffer = function (vertices) {
  5767. var vbo = this._gl.createBuffer();
  5768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5769. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5770. this._resetVertexBufferBinding();
  5771. vbo.references = 1;
  5772. return vbo;
  5773. };
  5774. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5775. var vbo = this._gl.createBuffer();
  5776. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5777. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5778. this._resetVertexBufferBinding();
  5779. vbo.references = 1;
  5780. return vbo;
  5781. };
  5782. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5783. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5784. if (offset === undefined) {
  5785. offset = 0;
  5786. }
  5787. if (vertices instanceof Float32Array) {
  5788. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5789. }
  5790. else {
  5791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5792. }
  5793. this._resetVertexBufferBinding();
  5794. };
  5795. Engine.prototype._resetIndexBufferBinding = function () {
  5796. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5797. this._cachedIndexBuffer = null;
  5798. };
  5799. Engine.prototype.createIndexBuffer = function (indices) {
  5800. var vbo = this._gl.createBuffer();
  5801. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5802. // Check for 32 bits indices
  5803. var arrayBuffer;
  5804. var need32Bits = false;
  5805. if (this._caps.uintIndices) {
  5806. for (var index = 0; index < indices.length; index++) {
  5807. if (indices[index] > 65535) {
  5808. need32Bits = true;
  5809. break;
  5810. }
  5811. }
  5812. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5813. }
  5814. else {
  5815. arrayBuffer = new Uint16Array(indices);
  5816. }
  5817. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5818. this._resetIndexBufferBinding();
  5819. vbo.references = 1;
  5820. vbo.is32Bits = need32Bits;
  5821. return vbo;
  5822. };
  5823. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5824. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5825. this._cachedVertexBuffers = vertexBuffer;
  5826. this._cachedEffectForVertexBuffers = effect;
  5827. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5828. var offset = 0;
  5829. for (var index = 0; index < vertexDeclaration.length; index++) {
  5830. var order = effect.getAttributeLocation(index);
  5831. if (order >= 0) {
  5832. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5833. }
  5834. offset += vertexDeclaration[index] * 4;
  5835. }
  5836. }
  5837. if (this._cachedIndexBuffer !== indexBuffer) {
  5838. this._cachedIndexBuffer = indexBuffer;
  5839. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5840. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5841. }
  5842. };
  5843. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5844. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5845. this._cachedVertexBuffers = vertexBuffers;
  5846. this._cachedEffectForVertexBuffers = effect;
  5847. var attributes = effect.getAttributesNames();
  5848. for (var index = 0; index < attributes.length; index++) {
  5849. var order = effect.getAttributeLocation(index);
  5850. if (order >= 0) {
  5851. var vertexBuffer = vertexBuffers[attributes[index]];
  5852. if (!vertexBuffer) {
  5853. continue;
  5854. }
  5855. var stride = vertexBuffer.getStrideSize();
  5856. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5857. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5858. }
  5859. }
  5860. }
  5861. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5862. this._cachedIndexBuffer = indexBuffer;
  5863. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5864. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5865. }
  5866. };
  5867. Engine.prototype._releaseBuffer = function (buffer) {
  5868. buffer.references--;
  5869. if (buffer.references === 0) {
  5870. this._gl.deleteBuffer(buffer);
  5871. return true;
  5872. }
  5873. return false;
  5874. };
  5875. Engine.prototype.createInstancesBuffer = function (capacity) {
  5876. var buffer = this._gl.createBuffer();
  5877. buffer.capacity = capacity;
  5878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5879. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5880. return buffer;
  5881. };
  5882. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5883. this._gl.deleteBuffer(buffer);
  5884. };
  5885. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5886. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5887. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5888. for (var index = 0; index < 4; index++) {
  5889. var offsetLocation = offsetLocations[index];
  5890. this._gl.enableVertexAttribArray(offsetLocation);
  5891. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5892. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5893. }
  5894. };
  5895. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5897. for (var index = 0; index < 4; index++) {
  5898. var offsetLocation = offsetLocations[index];
  5899. this._gl.disableVertexAttribArray(offsetLocation);
  5900. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5901. }
  5902. };
  5903. Engine.prototype.applyStates = function () {
  5904. this._depthCullingState.apply(this._gl);
  5905. this._alphaState.apply(this._gl);
  5906. };
  5907. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5908. // Apply states
  5909. this.applyStates();
  5910. this._drawCalls++;
  5911. // Render
  5912. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5913. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5914. if (instancesCount) {
  5915. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5916. return;
  5917. }
  5918. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5919. };
  5920. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5921. // Apply states
  5922. this.applyStates();
  5923. this._drawCalls++;
  5924. if (instancesCount) {
  5925. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5926. return;
  5927. }
  5928. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5929. };
  5930. // Shaders
  5931. Engine.prototype._releaseEffect = function (effect) {
  5932. if (this._compiledEffects[effect._key]) {
  5933. delete this._compiledEffects[effect._key];
  5934. if (effect.getProgram()) {
  5935. this._gl.deleteProgram(effect.getProgram());
  5936. }
  5937. }
  5938. };
  5939. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5940. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5941. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5942. var name = vertex + "+" + fragment + "@" + defines;
  5943. if (this._compiledEffects[name]) {
  5944. return this._compiledEffects[name];
  5945. }
  5946. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5947. effect._key = name;
  5948. this._compiledEffects[name] = effect;
  5949. return effect;
  5950. };
  5951. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5952. if (uniformsNames === void 0) { uniformsNames = []; }
  5953. if (samplers === void 0) { samplers = []; }
  5954. if (defines === void 0) { defines = ""; }
  5955. return this.createEffect({
  5956. vertex: "particles",
  5957. fragmentElement: fragmentName
  5958. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5959. };
  5960. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5961. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5962. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5963. var shaderProgram = this._gl.createProgram();
  5964. this._gl.attachShader(shaderProgram, vertexShader);
  5965. this._gl.attachShader(shaderProgram, fragmentShader);
  5966. this._gl.linkProgram(shaderProgram);
  5967. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5968. if (!linked) {
  5969. var error = this._gl.getProgramInfoLog(shaderProgram);
  5970. if (error) {
  5971. throw new Error(error);
  5972. }
  5973. }
  5974. this._gl.deleteShader(vertexShader);
  5975. this._gl.deleteShader(fragmentShader);
  5976. return shaderProgram;
  5977. };
  5978. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5979. var results = [];
  5980. for (var index = 0; index < uniformsNames.length; index++) {
  5981. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5982. }
  5983. return results;
  5984. };
  5985. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5986. var results = [];
  5987. for (var index = 0; index < attributesNames.length; index++) {
  5988. try {
  5989. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5990. }
  5991. catch (e) {
  5992. results.push(-1);
  5993. }
  5994. }
  5995. return results;
  5996. };
  5997. Engine.prototype.enableEffect = function (effect) {
  5998. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5999. if (effect && effect.onBind) {
  6000. effect.onBind(effect);
  6001. }
  6002. return;
  6003. }
  6004. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6005. // Use program
  6006. this._gl.useProgram(effect.getProgram());
  6007. for (var i in this._vertexAttribArrays) {
  6008. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6009. continue;
  6010. }
  6011. this._vertexAttribArrays[i] = false;
  6012. this._gl.disableVertexAttribArray(i);
  6013. }
  6014. var attributesCount = effect.getAttributesCount();
  6015. for (var index = 0; index < attributesCount; index++) {
  6016. // Attributes
  6017. var order = effect.getAttributeLocation(index);
  6018. if (order >= 0) {
  6019. this._vertexAttribArrays[order] = true;
  6020. this._gl.enableVertexAttribArray(order);
  6021. }
  6022. }
  6023. this._currentEffect = effect;
  6024. if (effect.onBind) {
  6025. effect.onBind(effect);
  6026. }
  6027. };
  6028. Engine.prototype.setArray = function (uniform, array) {
  6029. if (!uniform)
  6030. return;
  6031. this._gl.uniform1fv(uniform, array);
  6032. };
  6033. Engine.prototype.setArray2 = function (uniform, array) {
  6034. if (!uniform || array.length % 2 !== 0)
  6035. return;
  6036. this._gl.uniform2fv(uniform, array);
  6037. };
  6038. Engine.prototype.setArray3 = function (uniform, array) {
  6039. if (!uniform || array.length % 3 !== 0)
  6040. return;
  6041. this._gl.uniform3fv(uniform, array);
  6042. };
  6043. Engine.prototype.setArray4 = function (uniform, array) {
  6044. if (!uniform || array.length % 4 !== 0)
  6045. return;
  6046. this._gl.uniform4fv(uniform, array);
  6047. };
  6048. Engine.prototype.setMatrices = function (uniform, matrices) {
  6049. if (!uniform)
  6050. return;
  6051. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6052. };
  6053. Engine.prototype.setMatrix = function (uniform, matrix) {
  6054. if (!uniform)
  6055. return;
  6056. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6057. };
  6058. Engine.prototype.setFloat = function (uniform, value) {
  6059. if (!uniform)
  6060. return;
  6061. this._gl.uniform1f(uniform, value);
  6062. };
  6063. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6064. if (!uniform)
  6065. return;
  6066. this._gl.uniform2f(uniform, x, y);
  6067. };
  6068. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6069. if (!uniform)
  6070. return;
  6071. this._gl.uniform3f(uniform, x, y, z);
  6072. };
  6073. Engine.prototype.setBool = function (uniform, bool) {
  6074. if (!uniform)
  6075. return;
  6076. this._gl.uniform1i(uniform, bool);
  6077. };
  6078. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6079. if (!uniform)
  6080. return;
  6081. this._gl.uniform4f(uniform, x, y, z, w);
  6082. };
  6083. Engine.prototype.setColor3 = function (uniform, color3) {
  6084. if (!uniform)
  6085. return;
  6086. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6087. };
  6088. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6089. if (!uniform)
  6090. return;
  6091. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6092. };
  6093. // States
  6094. Engine.prototype.setState = function (culling, zOffset, force) {
  6095. if (zOffset === void 0) { zOffset = 0; }
  6096. // Culling
  6097. if (this._depthCullingState.cull !== culling || force) {
  6098. if (culling) {
  6099. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6100. this._depthCullingState.cull = true;
  6101. }
  6102. else {
  6103. this._depthCullingState.cull = false;
  6104. }
  6105. }
  6106. // Z offset
  6107. this._depthCullingState.zOffset = zOffset;
  6108. };
  6109. Engine.prototype.setDepthBuffer = function (enable) {
  6110. this._depthCullingState.depthTest = enable;
  6111. };
  6112. Engine.prototype.getDepthWrite = function () {
  6113. return this._depthCullingState.depthMask;
  6114. };
  6115. Engine.prototype.setDepthWrite = function (enable) {
  6116. this._depthCullingState.depthMask = enable;
  6117. };
  6118. Engine.prototype.setColorWrite = function (enable) {
  6119. this._gl.colorMask(enable, enable, enable, enable);
  6120. };
  6121. Engine.prototype.setAlphaMode = function (mode) {
  6122. switch (mode) {
  6123. case Engine.ALPHA_DISABLE:
  6124. this.setDepthWrite(true);
  6125. this._alphaState.alphaBlend = false;
  6126. break;
  6127. case Engine.ALPHA_COMBINE:
  6128. this.setDepthWrite(false);
  6129. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6130. this._alphaState.alphaBlend = true;
  6131. break;
  6132. case Engine.ALPHA_ADD:
  6133. this.setDepthWrite(false);
  6134. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6135. this._alphaState.alphaBlend = true;
  6136. break;
  6137. }
  6138. this._alphaMode = mode;
  6139. };
  6140. Engine.prototype.getAlphaMode = function () {
  6141. return this._alphaMode;
  6142. };
  6143. Engine.prototype.setAlphaTesting = function (enable) {
  6144. this._alphaTest = enable;
  6145. };
  6146. Engine.prototype.getAlphaTesting = function () {
  6147. return this._alphaTest;
  6148. };
  6149. // Textures
  6150. Engine.prototype.wipeCaches = function () {
  6151. this._activeTexturesCache = [];
  6152. this._currentEffect = null;
  6153. this._depthCullingState.reset();
  6154. this._alphaState.reset();
  6155. this._cachedVertexBuffers = null;
  6156. this._cachedIndexBuffer = null;
  6157. this._cachedEffectForVertexBuffers = null;
  6158. };
  6159. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6160. var gl = this._gl;
  6161. gl.bindTexture(gl.TEXTURE_2D, texture);
  6162. var magFilter = gl.NEAREST;
  6163. var minFilter = gl.NEAREST;
  6164. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6165. magFilter = gl.LINEAR;
  6166. minFilter = gl.LINEAR;
  6167. }
  6168. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6169. magFilter = gl.LINEAR;
  6170. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6171. }
  6172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6174. gl.bindTexture(gl.TEXTURE_2D, null);
  6175. texture.samplingMode = samplingMode;
  6176. };
  6177. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6178. var _this = this;
  6179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6180. if (onLoad === void 0) { onLoad = null; }
  6181. if (onError === void 0) { onError = null; }
  6182. if (buffer === void 0) { buffer = null; }
  6183. var texture = this._gl.createTexture();
  6184. var extension;
  6185. var fromData = false;
  6186. if (url.substr(0, 5) === "data:") {
  6187. fromData = true;
  6188. }
  6189. if (!fromData)
  6190. extension = url.substr(url.length - 4, 4).toLowerCase();
  6191. else {
  6192. var oldUrl = url;
  6193. fromData = oldUrl.split(':');
  6194. url = oldUrl;
  6195. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6196. }
  6197. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6198. var isTGA = (extension === ".tga");
  6199. scene._addPendingData(texture);
  6200. texture.url = url;
  6201. texture.noMipmap = noMipmap;
  6202. texture.references = 1;
  6203. texture.samplingMode = samplingMode;
  6204. this._loadedTexturesCache.push(texture);
  6205. var onerror = function () {
  6206. scene._removePendingData(texture);
  6207. if (onError) {
  6208. onError();
  6209. }
  6210. };
  6211. if (isTGA) {
  6212. var callback = function (arrayBuffer) {
  6213. var data = new Uint8Array(arrayBuffer);
  6214. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6215. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6216. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6217. if (onLoad) {
  6218. onLoad();
  6219. }
  6220. }, samplingMode);
  6221. };
  6222. if (!(fromData instanceof Array))
  6223. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6224. callback(arrayBuffer);
  6225. }, onerror, scene.database, true);
  6226. else
  6227. callback(buffer);
  6228. }
  6229. else if (isDDS) {
  6230. callback = function (data) {
  6231. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6232. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6233. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6234. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6235. if (onLoad) {
  6236. onLoad();
  6237. }
  6238. }, samplingMode);
  6239. };
  6240. if (!(fromData instanceof Array))
  6241. BABYLON.Tools.LoadFile(url, function (data) {
  6242. callback(data);
  6243. }, onerror, scene.database, true);
  6244. else
  6245. callback(buffer);
  6246. }
  6247. else {
  6248. var onload = function (img) {
  6249. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6250. var isPot = (img.width === potWidth && img.height === potHeight);
  6251. if (!isPot) {
  6252. _this._prepareWorkingCanvas();
  6253. _this._workingCanvas.width = potWidth;
  6254. _this._workingCanvas.height = potHeight;
  6255. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6256. _this._workingContext.imageSmoothingEnabled = false;
  6257. _this._workingContext.mozImageSmoothingEnabled = false;
  6258. _this._workingContext.oImageSmoothingEnabled = false;
  6259. _this._workingContext.webkitImageSmoothingEnabled = false;
  6260. _this._workingContext.msImageSmoothingEnabled = false;
  6261. }
  6262. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6263. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6264. _this._workingContext.imageSmoothingEnabled = true;
  6265. _this._workingContext.mozImageSmoothingEnabled = true;
  6266. _this._workingContext.oImageSmoothingEnabled = true;
  6267. _this._workingContext.webkitImageSmoothingEnabled = true;
  6268. _this._workingContext.msImageSmoothingEnabled = true;
  6269. }
  6270. }
  6271. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6272. if (onLoad) {
  6273. onLoad();
  6274. }
  6275. }, samplingMode);
  6276. };
  6277. if (!(fromData instanceof Array))
  6278. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6279. else
  6280. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6281. }
  6282. return texture;
  6283. };
  6284. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6285. var texture = this._gl.createTexture();
  6286. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6287. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6288. // Format
  6289. var internalFormat = this._gl.RGBA;
  6290. switch (format) {
  6291. case Engine.TEXTUREFORMAT_ALPHA:
  6292. internalFormat = this._gl.ALPHA;
  6293. break;
  6294. case Engine.TEXTUREFORMAT_LUMINANCE:
  6295. internalFormat = this._gl.LUMINANCE;
  6296. break;
  6297. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6298. internalFormat = this._gl.LUMINANCE_ALPHA;
  6299. break;
  6300. case Engine.TEXTUREFORMAT_RGB:
  6301. internalFormat = this._gl.RGB;
  6302. break;
  6303. case Engine.TEXTUREFORMAT_RGBA:
  6304. internalFormat = this._gl.RGBA;
  6305. break;
  6306. }
  6307. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6308. if (generateMipMaps) {
  6309. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6310. }
  6311. // Filters
  6312. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6313. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6315. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6316. this._activeTexturesCache = [];
  6317. texture._baseWidth = width;
  6318. texture._baseHeight = height;
  6319. texture._width = width;
  6320. texture._height = height;
  6321. texture.isReady = true;
  6322. texture.references = 1;
  6323. texture.samplingMode = samplingMode;
  6324. this._loadedTexturesCache.push(texture);
  6325. return texture;
  6326. };
  6327. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6328. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6329. var texture = this._gl.createTexture();
  6330. texture._baseWidth = width;
  6331. texture._baseHeight = height;
  6332. if (forceExponantOfTwo) {
  6333. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6334. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6335. }
  6336. this._activeTexturesCache = [];
  6337. texture._width = width;
  6338. texture._height = height;
  6339. texture.isReady = false;
  6340. texture.generateMipMaps = generateMipMaps;
  6341. texture.references = 1;
  6342. texture.samplingMode = samplingMode;
  6343. this.updateTextureSamplingMode(samplingMode, texture);
  6344. this._loadedTexturesCache.push(texture);
  6345. return texture;
  6346. };
  6347. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6348. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6349. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6350. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6351. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6352. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6353. };
  6354. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6355. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6356. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6357. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6358. if (texture.generateMipMaps) {
  6359. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6360. }
  6361. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6362. this._activeTexturesCache = [];
  6363. texture.isReady = true;
  6364. };
  6365. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6366. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6367. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6368. // Testing video texture support
  6369. if (this._videoTextureSupported === undefined) {
  6370. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6371. if (this._gl.getError() !== 0) {
  6372. this._videoTextureSupported = false;
  6373. }
  6374. else {
  6375. this._videoTextureSupported = true;
  6376. }
  6377. }
  6378. // Copy video through the current working canvas if video texture is not supported
  6379. if (!this._videoTextureSupported) {
  6380. if (!texture._workingCanvas) {
  6381. texture._workingCanvas = document.createElement("canvas");
  6382. texture._workingContext = texture._workingCanvas.getContext("2d");
  6383. texture._workingCanvas.width = texture._width;
  6384. texture._workingCanvas.height = texture._height;
  6385. }
  6386. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6388. }
  6389. else {
  6390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6391. }
  6392. if (texture.generateMipMaps) {
  6393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6394. }
  6395. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6396. this._activeTexturesCache = [];
  6397. texture.isReady = true;
  6398. };
  6399. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6400. // old version had a "generateMipMaps" arg instead of options.
  6401. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6402. // in the same way, generateDepthBuffer is defaulted to true
  6403. var generateMipMaps = false;
  6404. var generateDepthBuffer = true;
  6405. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6406. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6407. if (options !== undefined) {
  6408. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6409. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6410. type = options.type === undefined ? type : options.type;
  6411. if (options.samplingMode !== undefined) {
  6412. samplingMode = options.samplingMode;
  6413. }
  6414. if (type === Engine.TEXTURETYPE_FLOAT) {
  6415. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6416. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6417. }
  6418. }
  6419. var gl = this._gl;
  6420. var texture = gl.createTexture();
  6421. gl.bindTexture(gl.TEXTURE_2D, texture);
  6422. var width = size.width || size;
  6423. var height = size.height || size;
  6424. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6425. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6426. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6427. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6428. }
  6429. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6430. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6433. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6434. var depthBuffer;
  6435. // Create the depth buffer
  6436. if (generateDepthBuffer) {
  6437. depthBuffer = gl.createRenderbuffer();
  6438. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6439. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6440. }
  6441. // Create the framebuffer
  6442. var framebuffer = gl.createFramebuffer();
  6443. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6444. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6445. if (generateDepthBuffer) {
  6446. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6447. }
  6448. // Unbind
  6449. gl.bindTexture(gl.TEXTURE_2D, null);
  6450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6451. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6452. texture._framebuffer = framebuffer;
  6453. if (generateDepthBuffer) {
  6454. texture._depthBuffer = depthBuffer;
  6455. }
  6456. texture._width = width;
  6457. texture._height = height;
  6458. texture.isReady = true;
  6459. texture.generateMipMaps = generateMipMaps;
  6460. texture.references = 1;
  6461. texture.samplingMode = samplingMode;
  6462. this._activeTexturesCache = [];
  6463. this._loadedTexturesCache.push(texture);
  6464. return texture;
  6465. };
  6466. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6467. var _this = this;
  6468. var gl = this._gl;
  6469. var texture = gl.createTexture();
  6470. texture.isCube = true;
  6471. texture.url = rootUrl;
  6472. texture.references = 1;
  6473. this._loadedTexturesCache.push(texture);
  6474. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6475. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6476. if (isDDS) {
  6477. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6478. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6479. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6480. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6481. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6482. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6483. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6484. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6485. }
  6486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6490. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6491. _this._activeTexturesCache = [];
  6492. texture._width = info.width;
  6493. texture._height = info.height;
  6494. texture.isReady = true;
  6495. }, null, null, true);
  6496. }
  6497. else {
  6498. cascadeLoad(rootUrl, scene, function (imgs) {
  6499. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6500. var height = width;
  6501. _this._prepareWorkingCanvas();
  6502. _this._workingCanvas.width = width;
  6503. _this._workingCanvas.height = height;
  6504. var faces = [
  6505. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6506. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6507. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6508. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6509. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6510. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6511. ];
  6512. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6514. for (var index = 0; index < faces.length; index++) {
  6515. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6516. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6517. }
  6518. if (!noMipmap) {
  6519. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6520. }
  6521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6524. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6525. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6526. _this._activeTexturesCache = [];
  6527. texture._width = width;
  6528. texture._height = height;
  6529. texture.isReady = true;
  6530. }, extensions);
  6531. }
  6532. return texture;
  6533. };
  6534. Engine.prototype._releaseTexture = function (texture) {
  6535. var gl = this._gl;
  6536. if (texture._framebuffer) {
  6537. gl.deleteFramebuffer(texture._framebuffer);
  6538. }
  6539. if (texture._depthBuffer) {
  6540. gl.deleteRenderbuffer(texture._depthBuffer);
  6541. }
  6542. gl.deleteTexture(texture);
  6543. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6544. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6545. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6546. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6547. this._activeTexturesCache[channel] = null;
  6548. }
  6549. var index = this._loadedTexturesCache.indexOf(texture);
  6550. if (index !== -1) {
  6551. this._loadedTexturesCache.splice(index, 1);
  6552. }
  6553. };
  6554. Engine.prototype.bindSamplers = function (effect) {
  6555. this._gl.useProgram(effect.getProgram());
  6556. var samplers = effect.getSamplers();
  6557. for (var index = 0; index < samplers.length; index++) {
  6558. var uniform = effect.getUniform(samplers[index]);
  6559. this._gl.uniform1i(uniform, index);
  6560. }
  6561. this._currentEffect = null;
  6562. };
  6563. Engine.prototype._bindTexture = function (channel, texture) {
  6564. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6566. this._activeTexturesCache[channel] = null;
  6567. };
  6568. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6569. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6570. };
  6571. Engine.prototype.setTexture = function (channel, texture) {
  6572. if (channel < 0) {
  6573. return;
  6574. }
  6575. // Not ready?
  6576. if (!texture || !texture.isReady()) {
  6577. if (this._activeTexturesCache[channel] != null) {
  6578. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6579. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6580. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6581. this._activeTexturesCache[channel] = null;
  6582. }
  6583. return;
  6584. }
  6585. // Video
  6586. if (texture instanceof BABYLON.VideoTexture) {
  6587. if (texture.update()) {
  6588. this._activeTexturesCache[channel] = null;
  6589. }
  6590. }
  6591. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6592. texture.delayLoad();
  6593. return;
  6594. }
  6595. if (this._activeTexturesCache[channel] === texture) {
  6596. return;
  6597. }
  6598. this._activeTexturesCache[channel] = texture;
  6599. var internalTexture = texture.getInternalTexture();
  6600. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6601. if (internalTexture.isCube) {
  6602. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6603. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6604. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6605. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6606. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6607. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6608. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6609. }
  6610. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6611. }
  6612. else {
  6613. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6614. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6615. internalTexture._cachedWrapU = texture.wrapU;
  6616. switch (texture.wrapU) {
  6617. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6618. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6619. break;
  6620. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6622. break;
  6623. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6625. break;
  6626. }
  6627. }
  6628. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6629. internalTexture._cachedWrapV = texture.wrapV;
  6630. switch (texture.wrapV) {
  6631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6633. break;
  6634. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6636. break;
  6637. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6639. break;
  6640. }
  6641. }
  6642. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6643. }
  6644. };
  6645. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6646. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6647. var value = texture.anisotropicFilteringLevel;
  6648. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6649. value = 1;
  6650. }
  6651. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6652. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6653. texture._cachedAnisotropicFilteringLevel = value;
  6654. }
  6655. };
  6656. Engine.prototype.readPixels = function (x, y, width, height) {
  6657. var data = new Uint8Array(height * width * 4);
  6658. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6659. return data;
  6660. };
  6661. // Dispose
  6662. Engine.prototype.dispose = function () {
  6663. this.hideLoadingUI();
  6664. this.stopRenderLoop();
  6665. while (this.scenes.length) {
  6666. this.scenes[0].dispose();
  6667. }
  6668. // Release audio engine
  6669. Engine.audioEngine.dispose();
  6670. for (var name in this._compiledEffects) {
  6671. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6672. }
  6673. for (var i in this._vertexAttribArrays) {
  6674. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6675. continue;
  6676. }
  6677. this._gl.disableVertexAttribArray(i);
  6678. }
  6679. // Events
  6680. window.removeEventListener("blur", this._onBlur);
  6681. window.removeEventListener("focus", this._onFocus);
  6682. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6683. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6684. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6685. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6686. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6687. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6688. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6689. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6690. };
  6691. // Loading screen
  6692. Engine.prototype.displayLoadingUI = function () {
  6693. var _this = this;
  6694. this._loadingDiv = document.createElement("div");
  6695. this._loadingDiv.style.opacity = "0";
  6696. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6697. // Loading text
  6698. this._loadingTextDiv = document.createElement("div");
  6699. this._loadingTextDiv.style.position = "absolute";
  6700. this._loadingTextDiv.style.left = "0";
  6701. this._loadingTextDiv.style.top = "50%";
  6702. this._loadingTextDiv.style.marginTop = "80px";
  6703. this._loadingTextDiv.style.width = "100%";
  6704. this._loadingTextDiv.style.height = "20px";
  6705. this._loadingTextDiv.style.fontFamily = "Arial";
  6706. this._loadingTextDiv.style.fontSize = "14px";
  6707. this._loadingTextDiv.style.color = "white";
  6708. this._loadingTextDiv.style.textAlign = "center";
  6709. this._loadingTextDiv.innerHTML = "Loading";
  6710. this._loadingDiv.appendChild(this._loadingTextDiv);
  6711. // Loading img
  6712. var imgBack = new Image();
  6713. 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==";
  6714. imgBack.style.position = "absolute";
  6715. imgBack.style.left = "50%";
  6716. imgBack.style.top = "50%";
  6717. imgBack.style.marginLeft = "-50px";
  6718. imgBack.style.marginTop = "-50px";
  6719. imgBack.style.transition = "transform 1.0s ease";
  6720. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6721. var deg = 360;
  6722. var onTransitionEnd = function () {
  6723. deg += 360;
  6724. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6725. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6726. };
  6727. imgBack.addEventListener("transitionend", onTransitionEnd);
  6728. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6729. this._loadingDiv.appendChild(imgBack);
  6730. // front image
  6731. var imgFront = new Image();
  6732. 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=";
  6733. imgFront.style.position = "absolute";
  6734. imgFront.style.left = "50%";
  6735. imgFront.style.top = "50%";
  6736. imgFront.style.marginLeft = "-50px";
  6737. imgFront.style.marginTop = "-50px";
  6738. this._loadingDiv.appendChild(imgFront);
  6739. // Resize
  6740. this._resizeLoadingUI = function () {
  6741. var canvasRect = _this.getRenderingCanvasClientRect();
  6742. _this._loadingDiv.style.position = "absolute";
  6743. _this._loadingDiv.style.left = canvasRect.left + "px";
  6744. _this._loadingDiv.style.top = canvasRect.top + "px";
  6745. _this._loadingDiv.style.width = canvasRect.width + "px";
  6746. _this._loadingDiv.style.height = canvasRect.height + "px";
  6747. };
  6748. this._resizeLoadingUI();
  6749. window.addEventListener("resize", this._resizeLoadingUI);
  6750. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6751. document.body.appendChild(this._loadingDiv);
  6752. setTimeout(function () {
  6753. _this._loadingDiv.style.opacity = "1";
  6754. imgBack.style.transform = "rotateZ(360deg)";
  6755. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6756. }, 0);
  6757. };
  6758. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6759. set: function (text) {
  6760. if (!this._loadingDiv) {
  6761. return;
  6762. }
  6763. this._loadingTextDiv.innerHTML = text;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6769. get: function () {
  6770. return this._loadingDivBackgroundColor;
  6771. },
  6772. set: function (color) {
  6773. this._loadingDivBackgroundColor = color;
  6774. if (!this._loadingDiv) {
  6775. return;
  6776. }
  6777. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Engine.prototype.hideLoadingUI = function () {
  6783. var _this = this;
  6784. if (!this._loadingDiv) {
  6785. return;
  6786. }
  6787. var onTransitionEnd = function () {
  6788. if (!_this._loadingDiv) {
  6789. return;
  6790. }
  6791. document.body.removeChild(_this._loadingDiv);
  6792. window.removeEventListener("resize", _this._resizeLoadingUI);
  6793. _this._loadingDiv = null;
  6794. };
  6795. this._loadingDiv.style.opacity = "0";
  6796. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6797. };
  6798. // FPS
  6799. Engine.prototype.getFps = function () {
  6800. return this.fps;
  6801. };
  6802. Engine.prototype.getDeltaTime = function () {
  6803. return this.deltaTime;
  6804. };
  6805. Engine.prototype._measureFps = function () {
  6806. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6807. var length = this.previousFramesDuration.length;
  6808. if (length >= 2) {
  6809. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6810. }
  6811. if (length >= this.fpsRange) {
  6812. if (length > this.fpsRange) {
  6813. this.previousFramesDuration.splice(0, 1);
  6814. length = this.previousFramesDuration.length;
  6815. }
  6816. var sum = 0;
  6817. for (var id = 0; id < length - 1; id++) {
  6818. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6819. }
  6820. this.fps = 1000.0 / (sum / (length - 1));
  6821. }
  6822. };
  6823. // Statics
  6824. Engine.isSupported = function () {
  6825. try {
  6826. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6827. if (navigator.isCocoonJS) {
  6828. return true;
  6829. }
  6830. var tempcanvas = document.createElement("canvas");
  6831. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6832. return gl != null && !!window.WebGLRenderingContext;
  6833. }
  6834. catch (e) {
  6835. return false;
  6836. }
  6837. };
  6838. // Const statics
  6839. Engine._ALPHA_DISABLE = 0;
  6840. Engine._ALPHA_ADD = 1;
  6841. Engine._ALPHA_COMBINE = 2;
  6842. Engine._DELAYLOADSTATE_NONE = 0;
  6843. Engine._DELAYLOADSTATE_LOADED = 1;
  6844. Engine._DELAYLOADSTATE_LOADING = 2;
  6845. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6846. Engine._TEXTUREFORMAT_ALPHA = 0;
  6847. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6848. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6849. Engine._TEXTUREFORMAT_RGB = 4;
  6850. Engine._TEXTUREFORMAT_RGBA = 4;
  6851. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6852. Engine._TEXTURETYPE_FLOAT = 1;
  6853. // Updatable statics so stick with vars here
  6854. Engine.Epsilon = 0.001;
  6855. Engine.CollisionsEpsilon = 0.001;
  6856. Engine.CodeRepository = "Babylon/";
  6857. Engine.ShadersRepository = "Babylon/Shaders/";
  6858. return Engine;
  6859. })();
  6860. BABYLON.Engine = Engine;
  6861. })(BABYLON || (BABYLON = {}));
  6862. //# sourceMappingURL=babylon.engine.js.map
  6863. var BABYLON;
  6864. (function (BABYLON) {
  6865. /**
  6866. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6867. */
  6868. var Node = (function () {
  6869. /**
  6870. * @constructor
  6871. * @param {string} name - the name and id to be given to this node
  6872. * @param {BABYLON.Scene} the scene this node will be added to
  6873. */
  6874. function Node(name, scene) {
  6875. this.state = "";
  6876. this.animations = new Array();
  6877. this._childrenFlag = -1;
  6878. this._isEnabled = true;
  6879. this._isReady = true;
  6880. this._currentRenderId = -1;
  6881. this._parentRenderId = -1;
  6882. this.name = name;
  6883. this.id = name;
  6884. this._scene = scene;
  6885. this._initCache();
  6886. }
  6887. Node.prototype.getScene = function () {
  6888. return this._scene;
  6889. };
  6890. Node.prototype.getEngine = function () {
  6891. return this._scene.getEngine();
  6892. };
  6893. // override it in derived class
  6894. Node.prototype.getWorldMatrix = function () {
  6895. return BABYLON.Matrix.Identity();
  6896. };
  6897. // override it in derived class if you add new variables to the cache
  6898. // and call the parent class method
  6899. Node.prototype._initCache = function () {
  6900. this._cache = {};
  6901. this._cache.parent = undefined;
  6902. };
  6903. Node.prototype.updateCache = function (force) {
  6904. if (!force && this.isSynchronized())
  6905. return;
  6906. this._cache.parent = this.parent;
  6907. this._updateCache();
  6908. };
  6909. // override it in derived class if you add new variables to the cache
  6910. // and call the parent class method if !ignoreParentClass
  6911. Node.prototype._updateCache = function (ignoreParentClass) {
  6912. };
  6913. // override it in derived class if you add new variables to the cache
  6914. Node.prototype._isSynchronized = function () {
  6915. return true;
  6916. };
  6917. Node.prototype._markSyncedWithParent = function () {
  6918. this._parentRenderId = this.parent._currentRenderId;
  6919. };
  6920. Node.prototype.isSynchronizedWithParent = function () {
  6921. if (!this.parent) {
  6922. return true;
  6923. }
  6924. if (this._parentRenderId !== this.parent._currentRenderId) {
  6925. return false;
  6926. }
  6927. return this.parent.isSynchronized();
  6928. };
  6929. Node.prototype.isSynchronized = function (updateCache) {
  6930. var check = this.hasNewParent();
  6931. check = check || !this.isSynchronizedWithParent();
  6932. check = check || !this._isSynchronized();
  6933. if (updateCache)
  6934. this.updateCache(true);
  6935. return !check;
  6936. };
  6937. Node.prototype.hasNewParent = function (update) {
  6938. if (this._cache.parent === this.parent)
  6939. return false;
  6940. if (update)
  6941. this._cache.parent = this.parent;
  6942. return true;
  6943. };
  6944. /**
  6945. * Is this node ready to be used/rendered
  6946. * @return {boolean} is it ready
  6947. */
  6948. Node.prototype.isReady = function () {
  6949. return this._isReady;
  6950. };
  6951. /**
  6952. * Is this node enabled.
  6953. * If the node has a parent and is enabled, the parent will be inspected as well.
  6954. * @return {boolean} whether this node (and its parent) is enabled.
  6955. * @see setEnabled
  6956. */
  6957. Node.prototype.isEnabled = function () {
  6958. if (!this._isEnabled) {
  6959. return false;
  6960. }
  6961. if (this.parent) {
  6962. return this.parent.isEnabled();
  6963. }
  6964. return true;
  6965. };
  6966. /**
  6967. * Set the enabled state of this node.
  6968. * @param {boolean} value - the new enabled state
  6969. * @see isEnabled
  6970. */
  6971. Node.prototype.setEnabled = function (value) {
  6972. this._isEnabled = value;
  6973. };
  6974. /**
  6975. * Is this node a descendant of the given node.
  6976. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6977. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6978. * @see parent
  6979. */
  6980. Node.prototype.isDescendantOf = function (ancestor) {
  6981. if (this.parent) {
  6982. if (this.parent === ancestor) {
  6983. return true;
  6984. }
  6985. return this.parent.isDescendantOf(ancestor);
  6986. }
  6987. return false;
  6988. };
  6989. Node.prototype._getDescendants = function (list, results) {
  6990. for (var index = 0; index < list.length; index++) {
  6991. var item = list[index];
  6992. if (item.isDescendantOf(this)) {
  6993. results.push(item);
  6994. }
  6995. }
  6996. };
  6997. /**
  6998. * Will return all nodes that have this node as parent.
  6999. * @return {BABYLON.Node[]} all children nodes of all types.
  7000. */
  7001. Node.prototype.getDescendants = function () {
  7002. var results = [];
  7003. this._getDescendants(this._scene.meshes, results);
  7004. this._getDescendants(this._scene.lights, results);
  7005. this._getDescendants(this._scene.cameras, results);
  7006. return results;
  7007. };
  7008. Node.prototype._setReady = function (state) {
  7009. if (state == this._isReady) {
  7010. return;
  7011. }
  7012. if (!state) {
  7013. this._isReady = false;
  7014. return;
  7015. }
  7016. this._isReady = true;
  7017. if (this.onReady) {
  7018. this.onReady(this);
  7019. }
  7020. };
  7021. return Node;
  7022. })();
  7023. BABYLON.Node = Node;
  7024. })(BABYLON || (BABYLON = {}));
  7025. //# sourceMappingURL=babylon.node.js.map
  7026. var BABYLON;
  7027. (function (BABYLON) {
  7028. var FilesInput = (function () {
  7029. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7030. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7031. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7032. this._engine = p_engine;
  7033. this._canvas = p_canvas;
  7034. this._currentScene = p_scene;
  7035. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7036. this._progressCallback = p_progressCallback;
  7037. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7038. this._textureLoadingCallback = p_textureLoadingCallback;
  7039. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7040. }
  7041. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7042. var _this = this;
  7043. if (p_elementToMonitor) {
  7044. this._elementToMonitor = p_elementToMonitor;
  7045. this._elementToMonitor.addEventListener("dragenter", function (e) {
  7046. _this.drag(e);
  7047. }, false);
  7048. this._elementToMonitor.addEventListener("dragover", function (e) {
  7049. _this.drag(e);
  7050. }, false);
  7051. this._elementToMonitor.addEventListener("drop", function (e) {
  7052. _this.drop(e);
  7053. }, false);
  7054. }
  7055. };
  7056. FilesInput.prototype.renderFunction = function () {
  7057. if (this._additionnalRenderLoopLogicCallback) {
  7058. this._additionnalRenderLoopLogicCallback();
  7059. }
  7060. if (this._currentScene) {
  7061. if (this._textureLoadingCallback) {
  7062. var remaining = this._currentScene.getWaitingItemsCount();
  7063. if (remaining > 0) {
  7064. this._textureLoadingCallback(remaining);
  7065. }
  7066. }
  7067. this._currentScene.render();
  7068. }
  7069. };
  7070. FilesInput.prototype.drag = function (e) {
  7071. e.stopPropagation();
  7072. e.preventDefault();
  7073. };
  7074. FilesInput.prototype.drop = function (eventDrop) {
  7075. eventDrop.stopPropagation();
  7076. eventDrop.preventDefault();
  7077. this.loadFiles(eventDrop);
  7078. };
  7079. FilesInput.prototype.loadFiles = function (event) {
  7080. if (this._startingProcessingFilesCallback)
  7081. this._startingProcessingFilesCallback();
  7082. // Handling data transfer via drag'n'drop
  7083. if (event && event.dataTransfer && event.dataTransfer.files) {
  7084. this._filesToLoad = event.dataTransfer.files;
  7085. }
  7086. // Handling files from input files
  7087. if (event && event.target && event.target.files) {
  7088. this._filesToLoad = event.target.files;
  7089. }
  7090. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7091. for (var i = 0; i < this._filesToLoad.length; i++) {
  7092. switch (this._filesToLoad[i].type) {
  7093. case "image/jpeg":
  7094. case "image/png":
  7095. case "image/bmp":
  7096. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7097. break;
  7098. case "image/targa":
  7099. case "image/vnd.ms-dds":
  7100. case "audio/wav":
  7101. case "audio/x-wav":
  7102. case "audio/mp3":
  7103. case "audio/mpeg":
  7104. case "audio/mpeg3":
  7105. case "audio/x-mpeg-3":
  7106. case "audio/ogg":
  7107. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7108. break;
  7109. default:
  7110. 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) {
  7111. this._sceneFileToLoad = this._filesToLoad[i];
  7112. }
  7113. break;
  7114. }
  7115. }
  7116. this.reload();
  7117. }
  7118. };
  7119. FilesInput.prototype.reload = function () {
  7120. var _this = this;
  7121. var that = this;
  7122. // If a ".babylon" file has been provided
  7123. if (this._sceneFileToLoad) {
  7124. if (this._currentScene) {
  7125. this._engine.stopRenderLoop();
  7126. this._currentScene.dispose();
  7127. }
  7128. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7129. that._currentScene = newScene;
  7130. // Wait for textures and shaders to be ready
  7131. that._currentScene.executeWhenReady(function () {
  7132. // Attach camera to canvas inputs
  7133. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7134. that._currentScene.createDefaultCameraOrLight();
  7135. }
  7136. that._currentScene.activeCamera.attachControl(that._canvas);
  7137. if (that._sceneLoadedCallback) {
  7138. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7139. }
  7140. that._engine.runRenderLoop(function () {
  7141. that.renderFunction();
  7142. });
  7143. });
  7144. }, function (progress) {
  7145. if (_this._progressCallback) {
  7146. _this._progressCallback(progress);
  7147. }
  7148. });
  7149. }
  7150. else {
  7151. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7152. }
  7153. };
  7154. FilesInput.FilesTextures = new Array();
  7155. FilesInput.FilesToLoad = new Array();
  7156. return FilesInput;
  7157. })();
  7158. BABYLON.FilesInput = FilesInput;
  7159. })(BABYLON || (BABYLON = {}));
  7160. //# sourceMappingURL=babylon.filesInput.js.map
  7161. var BABYLON;
  7162. (function (BABYLON) {
  7163. var IntersectionInfo = (function () {
  7164. function IntersectionInfo(bu, bv, distance) {
  7165. this.bu = bu;
  7166. this.bv = bv;
  7167. this.distance = distance;
  7168. this.faceId = 0;
  7169. this.subMeshId = 0;
  7170. }
  7171. return IntersectionInfo;
  7172. })();
  7173. BABYLON.IntersectionInfo = IntersectionInfo;
  7174. var PickingInfo = (function () {
  7175. function PickingInfo() {
  7176. this.hit = false;
  7177. this.distance = 0;
  7178. this.pickedPoint = null;
  7179. this.pickedMesh = null;
  7180. this.bu = 0;
  7181. this.bv = 0;
  7182. this.faceId = -1;
  7183. this.subMeshId = 0;
  7184. }
  7185. // Methods
  7186. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7187. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7188. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7189. return null;
  7190. }
  7191. var indices = this.pickedMesh.getIndices();
  7192. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7193. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7194. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7195. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7196. normal0 = normal0.scale(this.bu);
  7197. normal1 = normal1.scale(this.bv);
  7198. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7199. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7200. if (useWorldCoordinates) {
  7201. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7202. }
  7203. return result;
  7204. };
  7205. PickingInfo.prototype.getTextureCoordinates = function () {
  7206. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7207. return null;
  7208. }
  7209. var indices = this.pickedMesh.getIndices();
  7210. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7211. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7212. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7213. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7214. uv0 = uv0.scale(this.bu);
  7215. uv1 = uv1.scale(this.bv);
  7216. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7217. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7218. };
  7219. return PickingInfo;
  7220. })();
  7221. BABYLON.PickingInfo = PickingInfo;
  7222. })(BABYLON || (BABYLON = {}));
  7223. //# sourceMappingURL=babylon.pickingInfo.js.map
  7224. var BABYLON;
  7225. (function (BABYLON) {
  7226. var BoundingSphere = (function () {
  7227. function BoundingSphere(minimum, maximum) {
  7228. this.minimum = minimum;
  7229. this.maximum = maximum;
  7230. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7231. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7232. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7233. this.radius = distance * 0.5;
  7234. this.centerWorld = BABYLON.Vector3.Zero();
  7235. this._update(BABYLON.Matrix.Identity());
  7236. }
  7237. // Methods
  7238. BoundingSphere.prototype._update = function (world) {
  7239. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7240. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7241. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7242. };
  7243. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7244. for (var i = 0; i < 6; i++) {
  7245. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7246. return false;
  7247. }
  7248. return true;
  7249. };
  7250. BoundingSphere.prototype.intersectsPoint = function (point) {
  7251. var x = this.centerWorld.x - point.x;
  7252. var y = this.centerWorld.y - point.y;
  7253. var z = this.centerWorld.z - point.z;
  7254. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7255. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7256. return false;
  7257. return true;
  7258. };
  7259. // Statics
  7260. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7261. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7262. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7263. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7264. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7265. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7266. return false;
  7267. return true;
  7268. };
  7269. return BoundingSphere;
  7270. })();
  7271. BABYLON.BoundingSphere = BoundingSphere;
  7272. })(BABYLON || (BABYLON = {}));
  7273. //# sourceMappingURL=babylon.boundingSphere.js.map
  7274. var BABYLON;
  7275. (function (BABYLON) {
  7276. var BoundingBox = (function () {
  7277. function BoundingBox(minimum, maximum) {
  7278. this.minimum = minimum;
  7279. this.maximum = maximum;
  7280. this.vectors = new Array();
  7281. this.vectorsWorld = new Array();
  7282. // Bounding vectors
  7283. this.vectors.push(this.minimum.clone());
  7284. this.vectors.push(this.maximum.clone());
  7285. this.vectors.push(this.minimum.clone());
  7286. this.vectors[2].x = this.maximum.x;
  7287. this.vectors.push(this.minimum.clone());
  7288. this.vectors[3].y = this.maximum.y;
  7289. this.vectors.push(this.minimum.clone());
  7290. this.vectors[4].z = this.maximum.z;
  7291. this.vectors.push(this.maximum.clone());
  7292. this.vectors[5].z = this.minimum.z;
  7293. this.vectors.push(this.maximum.clone());
  7294. this.vectors[6].x = this.minimum.x;
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors[7].y = this.minimum.y;
  7297. // OBB
  7298. this.center = this.maximum.add(this.minimum).scale(0.5);
  7299. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7300. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7301. for (var index = 0; index < this.vectors.length; index++) {
  7302. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7303. }
  7304. this.minimumWorld = BABYLON.Vector3.Zero();
  7305. this.maximumWorld = BABYLON.Vector3.Zero();
  7306. this._update(BABYLON.Matrix.Identity());
  7307. }
  7308. // Methods
  7309. BoundingBox.prototype.getWorldMatrix = function () {
  7310. return this._worldMatrix;
  7311. };
  7312. BoundingBox.prototype._update = function (world) {
  7313. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7314. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7315. for (var index = 0; index < this.vectors.length; index++) {
  7316. var v = this.vectorsWorld[index];
  7317. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7318. if (v.x < this.minimumWorld.x)
  7319. this.minimumWorld.x = v.x;
  7320. if (v.y < this.minimumWorld.y)
  7321. this.minimumWorld.y = v.y;
  7322. if (v.z < this.minimumWorld.z)
  7323. this.minimumWorld.z = v.z;
  7324. if (v.x > this.maximumWorld.x)
  7325. this.maximumWorld.x = v.x;
  7326. if (v.y > this.maximumWorld.y)
  7327. this.maximumWorld.y = v.y;
  7328. if (v.z > this.maximumWorld.z)
  7329. this.maximumWorld.z = v.z;
  7330. }
  7331. // OBB
  7332. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7333. this.center.scaleInPlace(0.5);
  7334. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7335. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7336. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7337. this._worldMatrix = world;
  7338. };
  7339. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7340. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7341. };
  7342. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7343. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7344. };
  7345. BoundingBox.prototype.intersectsPoint = function (point) {
  7346. var delta = -BABYLON.Engine.Epsilon;
  7347. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7348. return false;
  7349. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7350. return false;
  7351. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7352. return false;
  7353. return true;
  7354. };
  7355. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7356. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7357. };
  7358. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7359. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7360. return false;
  7361. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7362. return false;
  7363. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7364. return false;
  7365. return true;
  7366. };
  7367. // Statics
  7368. BoundingBox.Intersects = function (box0, box1) {
  7369. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7370. return false;
  7371. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7372. return false;
  7373. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7374. return false;
  7375. return true;
  7376. };
  7377. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7378. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7379. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7380. return (num <= (sphereRadius * sphereRadius));
  7381. };
  7382. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7383. for (var p = 0; p < 6; p++) {
  7384. for (var i = 0; i < 8; i++) {
  7385. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7386. return false;
  7387. }
  7388. }
  7389. }
  7390. return true;
  7391. };
  7392. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7393. for (var p = 0; p < 6; p++) {
  7394. var inCount = 8;
  7395. for (var i = 0; i < 8; i++) {
  7396. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7397. --inCount;
  7398. }
  7399. else {
  7400. break;
  7401. }
  7402. }
  7403. if (inCount === 0)
  7404. return false;
  7405. }
  7406. return true;
  7407. };
  7408. return BoundingBox;
  7409. })();
  7410. BABYLON.BoundingBox = BoundingBox;
  7411. })(BABYLON || (BABYLON = {}));
  7412. //# sourceMappingURL=babylon.boundingBox.js.map
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var computeBoxExtents = function (axis, box) {
  7416. var p = BABYLON.Vector3.Dot(box.center, axis);
  7417. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7418. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7419. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7420. var r = r0 + r1 + r2;
  7421. return {
  7422. min: p - r,
  7423. max: p + r
  7424. };
  7425. };
  7426. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7427. var axisOverlap = function (axis, box0, box1) {
  7428. var result0 = computeBoxExtents(axis, box0);
  7429. var result1 = computeBoxExtents(axis, box1);
  7430. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7431. };
  7432. var BoundingInfo = (function () {
  7433. function BoundingInfo(minimum, maximum) {
  7434. this.minimum = minimum;
  7435. this.maximum = maximum;
  7436. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7437. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7438. }
  7439. // Methods
  7440. BoundingInfo.prototype._update = function (world) {
  7441. this.boundingBox._update(world);
  7442. this.boundingSphere._update(world);
  7443. };
  7444. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7445. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7446. return false;
  7447. return this.boundingBox.isInFrustum(frustumPlanes);
  7448. };
  7449. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7450. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7451. };
  7452. BoundingInfo.prototype._checkCollision = function (collider) {
  7453. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7454. };
  7455. BoundingInfo.prototype.intersectsPoint = function (point) {
  7456. if (!this.boundingSphere.centerWorld) {
  7457. return false;
  7458. }
  7459. if (!this.boundingSphere.intersectsPoint(point)) {
  7460. return false;
  7461. }
  7462. if (!this.boundingBox.intersectsPoint(point)) {
  7463. return false;
  7464. }
  7465. return true;
  7466. };
  7467. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7468. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7472. return false;
  7473. }
  7474. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7475. return false;
  7476. }
  7477. if (!precise) {
  7478. return true;
  7479. }
  7480. var box0 = this.boundingBox;
  7481. var box1 = boundingInfo.boundingBox;
  7482. if (!axisOverlap(box0.directions[0], box0, box1))
  7483. return false;
  7484. if (!axisOverlap(box0.directions[1], box0, box1))
  7485. return false;
  7486. if (!axisOverlap(box0.directions[2], box0, box1))
  7487. return false;
  7488. if (!axisOverlap(box1.directions[0], box0, box1))
  7489. return false;
  7490. if (!axisOverlap(box1.directions[1], box0, box1))
  7491. return false;
  7492. if (!axisOverlap(box1.directions[2], box0, box1))
  7493. return false;
  7494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7495. return false;
  7496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7497. return false;
  7498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7499. return false;
  7500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7501. return false;
  7502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7503. return false;
  7504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7511. return false;
  7512. return true;
  7513. };
  7514. return BoundingInfo;
  7515. })();
  7516. BABYLON.BoundingInfo = BoundingInfo;
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.boundingInfo.js.map
  7519. var __extends = this.__extends || function (d, b) {
  7520. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7521. function __() { this.constructor = d; }
  7522. __.prototype = b.prototype;
  7523. d.prototype = new __();
  7524. };
  7525. var BABYLON;
  7526. (function (BABYLON) {
  7527. var AbstractMesh = (function (_super) {
  7528. __extends(AbstractMesh, _super);
  7529. function AbstractMesh(name, scene) {
  7530. var _this = this;
  7531. _super.call(this, name, scene);
  7532. // Properties
  7533. this.definedFacingForward = true; // orientation for POV movement & rotation
  7534. this.position = new BABYLON.Vector3(0, 0, 0);
  7535. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7536. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7537. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7538. this.visibility = 1.0;
  7539. this.alphaIndex = Number.MAX_VALUE;
  7540. this.infiniteDistance = false;
  7541. this.isVisible = true;
  7542. this.isPickable = true;
  7543. this.showBoundingBox = false;
  7544. this.showSubMeshesBoundingBox = false;
  7545. this.onDispose = null;
  7546. this.checkCollisions = false;
  7547. this.isBlocker = false;
  7548. this.renderingGroupId = 0;
  7549. this.receiveShadows = false;
  7550. this.renderOutline = false;
  7551. this.outlineColor = BABYLON.Color3.Red();
  7552. this.outlineWidth = 0.02;
  7553. this.renderOverlay = false;
  7554. this.overlayColor = BABYLON.Color3.Red();
  7555. this.overlayAlpha = 0.5;
  7556. this.hasVertexAlpha = false;
  7557. this.useVertexColors = true;
  7558. this.applyFog = true;
  7559. this.useOctreeForRenderingSelection = true;
  7560. this.useOctreeForPicking = true;
  7561. this.useOctreeForCollisions = true;
  7562. this.layerMask = 0x0FFFFFFF;
  7563. this.alwaysSelectAsActiveMesh = false;
  7564. // Physics
  7565. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7566. // Collisions
  7567. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7568. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7569. this._collider = new BABYLON.Collider();
  7570. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7571. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7572. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7573. // Cache
  7574. this._localScaling = BABYLON.Matrix.Zero();
  7575. this._localRotation = BABYLON.Matrix.Zero();
  7576. this._localTranslation = BABYLON.Matrix.Zero();
  7577. this._localBillboard = BABYLON.Matrix.Zero();
  7578. this._localPivotScaling = BABYLON.Matrix.Zero();
  7579. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7580. this._localWorld = BABYLON.Matrix.Zero();
  7581. this._worldMatrix = BABYLON.Matrix.Zero();
  7582. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7583. this._absolutePosition = BABYLON.Vector3.Zero();
  7584. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7585. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7586. this._isDirty = false;
  7587. this._pivotMatrix = BABYLON.Matrix.Identity();
  7588. this._isDisposed = false;
  7589. this._renderId = 0;
  7590. this._intersectionsInProgress = new Array();
  7591. this._onAfterWorldMatrixUpdate = new Array();
  7592. this._isWorldMatrixFrozen = false;
  7593. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7594. if (collidedMesh === void 0) { collidedMesh = null; }
  7595. //TODO move this to the collision coordinator!
  7596. if (_this.getScene().workerCollisions)
  7597. newPosition.multiplyInPlace(_this._collider.radius);
  7598. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7599. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7600. _this.position.addInPlace(_this._diffPositionForCollisions);
  7601. }
  7602. };
  7603. scene.addMesh(this);
  7604. }
  7605. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7606. get: function () {
  7607. return AbstractMesh._BILLBOARDMODE_NONE;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7613. get: function () {
  7614. return AbstractMesh._BILLBOARDMODE_X;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7620. get: function () {
  7621. return AbstractMesh._BILLBOARDMODE_Y;
  7622. },
  7623. enumerable: true,
  7624. configurable: true
  7625. });
  7626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7627. get: function () {
  7628. return AbstractMesh._BILLBOARDMODE_Z;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7634. get: function () {
  7635. return AbstractMesh._BILLBOARDMODE_ALL;
  7636. },
  7637. enumerable: true,
  7638. configurable: true
  7639. });
  7640. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7641. // Methods
  7642. get: function () {
  7643. return false;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. AbstractMesh.prototype.getLOD = function (camera) {
  7649. return this;
  7650. };
  7651. AbstractMesh.prototype.getTotalVertices = function () {
  7652. return 0;
  7653. };
  7654. AbstractMesh.prototype.getIndices = function () {
  7655. return null;
  7656. };
  7657. AbstractMesh.prototype.getVerticesData = function (kind) {
  7658. return null;
  7659. };
  7660. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7661. return false;
  7662. };
  7663. AbstractMesh.prototype.getBoundingInfo = function () {
  7664. if (this._masterMesh) {
  7665. return this._masterMesh.getBoundingInfo();
  7666. }
  7667. if (!this._boundingInfo) {
  7668. this._updateBoundingInfo();
  7669. }
  7670. return this._boundingInfo;
  7671. };
  7672. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7673. get: function () {
  7674. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. AbstractMesh.prototype._preActivate = function () {
  7680. };
  7681. AbstractMesh.prototype._activate = function (renderId) {
  7682. this._renderId = renderId;
  7683. };
  7684. AbstractMesh.prototype.getWorldMatrix = function () {
  7685. if (this._masterMesh) {
  7686. return this._masterMesh.getWorldMatrix();
  7687. }
  7688. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7689. this.computeWorldMatrix();
  7690. }
  7691. return this._worldMatrix;
  7692. };
  7693. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7694. get: function () {
  7695. return this._worldMatrix;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7701. get: function () {
  7702. return this._absolutePosition;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7708. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7709. this.computeWorldMatrix(true);
  7710. this._isWorldMatrixFrozen = true;
  7711. };
  7712. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7713. this._isWorldMatrixFrozen = false;
  7714. this.computeWorldMatrix(true);
  7715. };
  7716. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7717. get: function () {
  7718. return this._isWorldMatrixFrozen;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7724. if (!this.rotationQuaternion) {
  7725. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7726. this.rotation = BABYLON.Vector3.Zero();
  7727. }
  7728. if (!space || space === 0 /* LOCAL */) {
  7729. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7730. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7731. }
  7732. else {
  7733. if (this.parent) {
  7734. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7735. invertParentWorldMatrix.invert();
  7736. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7737. }
  7738. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7739. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7740. }
  7741. };
  7742. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7743. var displacementVector = axis.scale(distance);
  7744. if (!space || space === 0 /* LOCAL */) {
  7745. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7746. this.setPositionWithLocalVector(tempV3);
  7747. }
  7748. else {
  7749. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7750. }
  7751. };
  7752. AbstractMesh.prototype.getAbsolutePosition = function () {
  7753. this.computeWorldMatrix();
  7754. return this._absolutePosition;
  7755. };
  7756. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7757. if (!absolutePosition) {
  7758. return;
  7759. }
  7760. var absolutePositionX;
  7761. var absolutePositionY;
  7762. var absolutePositionZ;
  7763. if (absolutePosition.x === undefined) {
  7764. if (arguments.length < 3) {
  7765. return;
  7766. }
  7767. absolutePositionX = arguments[0];
  7768. absolutePositionY = arguments[1];
  7769. absolutePositionZ = arguments[2];
  7770. }
  7771. else {
  7772. absolutePositionX = absolutePosition.x;
  7773. absolutePositionY = absolutePosition.y;
  7774. absolutePositionZ = absolutePosition.z;
  7775. }
  7776. if (this.parent) {
  7777. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7778. invertParentWorldMatrix.invert();
  7779. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7780. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7781. }
  7782. else {
  7783. this.position.x = absolutePositionX;
  7784. this.position.y = absolutePositionY;
  7785. this.position.z = absolutePositionZ;
  7786. }
  7787. };
  7788. // ================================== Point of View Movement =================================
  7789. /**
  7790. * Perform relative position change from the point of view of behind the front of the mesh.
  7791. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7792. * Supports definition of mesh facing forward or backward.
  7793. * @param {number} amountRight
  7794. * @param {number} amountUp
  7795. * @param {number} amountForward
  7796. */
  7797. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7798. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7799. };
  7800. /**
  7801. * Calculate relative position change from the point of view of behind the front of the mesh.
  7802. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7803. * Supports definition of mesh facing forward or backward.
  7804. * @param {number} amountRight
  7805. * @param {number} amountUp
  7806. * @param {number} amountForward
  7807. */
  7808. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7809. var rotMatrix = new BABYLON.Matrix();
  7810. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7811. rotQuaternion.toRotationMatrix(rotMatrix);
  7812. var translationDelta = BABYLON.Vector3.Zero();
  7813. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7814. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7815. return translationDelta;
  7816. };
  7817. // ================================== Point of View Rotation =================================
  7818. /**
  7819. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7820. * Supports definition of mesh facing forward or backward.
  7821. * @param {number} flipBack
  7822. * @param {number} twirlClockwise
  7823. * @param {number} tiltRight
  7824. */
  7825. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7826. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7827. };
  7828. /**
  7829. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7830. * Supports definition of mesh facing forward or backward.
  7831. * @param {number} flipBack
  7832. * @param {number} twirlClockwise
  7833. * @param {number} tiltRight
  7834. */
  7835. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7836. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7837. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7838. };
  7839. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7840. this._pivotMatrix = matrix;
  7841. this._cache.pivotMatrixUpdated = true;
  7842. };
  7843. AbstractMesh.prototype.getPivotMatrix = function () {
  7844. return this._pivotMatrix;
  7845. };
  7846. AbstractMesh.prototype._isSynchronized = function () {
  7847. if (this._isDirty) {
  7848. return false;
  7849. }
  7850. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7851. return false;
  7852. if (this._cache.pivotMatrixUpdated) {
  7853. return false;
  7854. }
  7855. if (this.infiniteDistance) {
  7856. return false;
  7857. }
  7858. if (!this._cache.position.equals(this.position))
  7859. return false;
  7860. if (this.rotationQuaternion) {
  7861. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7862. return false;
  7863. }
  7864. else {
  7865. if (!this._cache.rotation.equals(this.rotation))
  7866. return false;
  7867. }
  7868. if (!this._cache.scaling.equals(this.scaling))
  7869. return false;
  7870. return true;
  7871. };
  7872. AbstractMesh.prototype._initCache = function () {
  7873. _super.prototype._initCache.call(this);
  7874. this._cache.localMatrixUpdated = false;
  7875. this._cache.position = BABYLON.Vector3.Zero();
  7876. this._cache.scaling = BABYLON.Vector3.Zero();
  7877. this._cache.rotation = BABYLON.Vector3.Zero();
  7878. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7879. };
  7880. AbstractMesh.prototype.markAsDirty = function (property) {
  7881. if (property === "rotation") {
  7882. this.rotationQuaternion = null;
  7883. }
  7884. this._currentRenderId = Number.MAX_VALUE;
  7885. this._isDirty = true;
  7886. };
  7887. AbstractMesh.prototype._updateBoundingInfo = function () {
  7888. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7889. this._boundingInfo._update(this.worldMatrixFromCache);
  7890. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7891. };
  7892. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7893. if (!this.subMeshes) {
  7894. return;
  7895. }
  7896. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7897. var subMesh = this.subMeshes[subIndex];
  7898. subMesh.updateBoundingInfo(matrix);
  7899. }
  7900. };
  7901. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7902. if (this._isWorldMatrixFrozen) {
  7903. return this._worldMatrix;
  7904. }
  7905. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7906. return this._worldMatrix;
  7907. }
  7908. this._cache.position.copyFrom(this.position);
  7909. this._cache.scaling.copyFrom(this.scaling);
  7910. this._cache.pivotMatrixUpdated = false;
  7911. this._currentRenderId = this.getScene().getRenderId();
  7912. this._isDirty = false;
  7913. // Scaling
  7914. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7915. // Rotation
  7916. if (this.rotationQuaternion) {
  7917. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7918. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7919. }
  7920. else {
  7921. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7922. this._cache.rotation.copyFrom(this.rotation);
  7923. }
  7924. // Translation
  7925. if (this.infiniteDistance && !this.parent) {
  7926. var camera = this.getScene().activeCamera;
  7927. var cameraWorldMatrix = camera.getWorldMatrix();
  7928. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7929. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7930. }
  7931. else {
  7932. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7933. }
  7934. // Composing transformations
  7935. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7936. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7937. // Billboarding
  7938. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7939. var localPosition = this.position.clone();
  7940. var zero = this.getScene().activeCamera.globalPosition.clone();
  7941. if (this.parent && this.parent.position) {
  7942. localPosition.addInPlace(this.parent.position);
  7943. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7944. }
  7945. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7946. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7947. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7948. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7949. zero.y = localPosition.y + 0.001;
  7950. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7951. zero.z = localPosition.z + 0.001;
  7952. }
  7953. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7954. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7955. this._localBillboard.invert();
  7956. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7957. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7958. }
  7959. // Local world
  7960. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7961. // Parent
  7962. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7963. this._markSyncedWithParent();
  7964. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7965. }
  7966. else {
  7967. this._worldMatrix.copyFrom(this._localWorld);
  7968. }
  7969. // Bounding info
  7970. this._updateBoundingInfo();
  7971. // Absolute position
  7972. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7973. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7974. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7975. }
  7976. return this._worldMatrix;
  7977. };
  7978. /**
  7979. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7980. * @param func: callback function to add
  7981. */
  7982. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7983. this._onAfterWorldMatrixUpdate.push(func);
  7984. };
  7985. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7986. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7987. if (index > -1) {
  7988. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7989. }
  7990. };
  7991. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7992. this.computeWorldMatrix();
  7993. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7994. };
  7995. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7996. this.computeWorldMatrix();
  7997. var invLocalWorldMatrix = this._localWorld.clone();
  7998. invLocalWorldMatrix.invert();
  7999. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8000. };
  8001. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8002. this.computeWorldMatrix(true);
  8003. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8004. };
  8005. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8006. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8007. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8008. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8009. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8010. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8011. /// <returns>Mesh oriented towards targetMesh</returns>
  8012. yawCor = yawCor || 0; // default to zero if undefined
  8013. pitchCor = pitchCor || 0;
  8014. rollCor = rollCor || 0;
  8015. var dv = targetPoint.subtract(this.position);
  8016. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8017. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8018. var pitch = Math.atan2(dv.y, len);
  8019. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8020. };
  8021. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8022. return this._boundingInfo.isInFrustum(frustumPlanes);
  8023. };
  8024. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8025. if (!camera) {
  8026. camera = this.getScene().activeCamera;
  8027. }
  8028. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8029. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8030. return false;
  8031. }
  8032. return true;
  8033. };
  8034. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8035. if (!this._boundingInfo || !mesh._boundingInfo) {
  8036. return false;
  8037. }
  8038. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8039. };
  8040. AbstractMesh.prototype.intersectsPoint = function (point) {
  8041. if (!this._boundingInfo) {
  8042. return false;
  8043. }
  8044. return this._boundingInfo.intersectsPoint(point);
  8045. };
  8046. // Physics
  8047. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8048. var physicsEngine = this.getScene().getPhysicsEngine();
  8049. if (!physicsEngine) {
  8050. return;
  8051. }
  8052. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8053. if (impostor.impostor) {
  8054. // Old API
  8055. options = impostor;
  8056. impostor = impostor.impostor;
  8057. }
  8058. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8059. physicsEngine._unregisterMesh(this);
  8060. return;
  8061. }
  8062. if (!options) {
  8063. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8064. }
  8065. else {
  8066. if (!options.mass && options.mass !== 0)
  8067. options.mass = 0;
  8068. if (!options.friction && options.friction !== 0)
  8069. options.friction = 0.2;
  8070. if (!options.restitution && options.restitution !== 0)
  8071. options.restitution = 0.2;
  8072. }
  8073. this._physicImpostor = impostor;
  8074. this._physicsMass = options.mass;
  8075. this._physicsFriction = options.friction;
  8076. this._physicRestitution = options.restitution;
  8077. return physicsEngine._registerMesh(this, impostor, options);
  8078. };
  8079. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8080. if (!this._physicImpostor) {
  8081. return BABYLON.PhysicsEngine.NoImpostor;
  8082. }
  8083. return this._physicImpostor;
  8084. };
  8085. AbstractMesh.prototype.getPhysicsMass = function () {
  8086. if (!this._physicsMass) {
  8087. return 0;
  8088. }
  8089. return this._physicsMass;
  8090. };
  8091. AbstractMesh.prototype.getPhysicsFriction = function () {
  8092. if (!this._physicsFriction) {
  8093. return 0;
  8094. }
  8095. return this._physicsFriction;
  8096. };
  8097. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8098. if (!this._physicRestitution) {
  8099. return 0;
  8100. }
  8101. return this._physicRestitution;
  8102. };
  8103. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8104. if (!camera) {
  8105. camera = this.getScene().activeCamera;
  8106. }
  8107. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8108. };
  8109. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8110. if (!camera) {
  8111. camera = this.getScene().activeCamera;
  8112. }
  8113. return this.absolutePosition.subtract(camera.position).length();
  8114. };
  8115. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8116. if (!this._physicImpostor) {
  8117. return;
  8118. }
  8119. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8120. };
  8121. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8122. if (!this._physicImpostor) {
  8123. return;
  8124. }
  8125. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8126. };
  8127. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8128. if (!this._physicImpostor) {
  8129. return;
  8130. }
  8131. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8132. };
  8133. // Collisions
  8134. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8135. var globalPosition = this.getAbsolutePosition();
  8136. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8137. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8138. this._collider.radius = this.ellipsoid;
  8139. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8140. };
  8141. // Submeshes octree
  8142. /**
  8143. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8144. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8145. */
  8146. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8147. if (maxCapacity === void 0) { maxCapacity = 64; }
  8148. if (maxDepth === void 0) { maxDepth = 2; }
  8149. if (!this._submeshesOctree) {
  8150. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8151. }
  8152. this.computeWorldMatrix(true);
  8153. // Update octree
  8154. var bbox = this.getBoundingInfo().boundingBox;
  8155. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8156. return this._submeshesOctree;
  8157. };
  8158. // Collisions
  8159. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8160. this._generatePointsArray();
  8161. // Transformation
  8162. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8163. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8164. subMesh._lastColliderWorldVertices = [];
  8165. subMesh._trianglePlanes = [];
  8166. var start = subMesh.verticesStart;
  8167. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8168. for (var i = start; i < end; i++) {
  8169. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8170. }
  8171. }
  8172. // Collide
  8173. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8174. if (collider.collisionFound) {
  8175. collider.collidedMesh = this;
  8176. }
  8177. };
  8178. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8179. var subMeshes;
  8180. var len;
  8181. // Octrees
  8182. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8183. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8184. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8185. len = intersections.length;
  8186. subMeshes = intersections.data;
  8187. }
  8188. else {
  8189. subMeshes = this.subMeshes;
  8190. len = subMeshes.length;
  8191. }
  8192. for (var index = 0; index < len; index++) {
  8193. var subMesh = subMeshes[index];
  8194. // Bounding test
  8195. if (len > 1 && !subMesh._checkCollision(collider))
  8196. continue;
  8197. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8198. }
  8199. };
  8200. AbstractMesh.prototype._checkCollision = function (collider) {
  8201. // Bounding box test
  8202. if (!this._boundingInfo._checkCollision(collider))
  8203. return;
  8204. // Transformation matrix
  8205. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8206. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8207. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8208. };
  8209. // Picking
  8210. AbstractMesh.prototype._generatePointsArray = function () {
  8211. return false;
  8212. };
  8213. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8214. var pickingInfo = new BABYLON.PickingInfo();
  8215. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8216. return pickingInfo;
  8217. }
  8218. if (!this._generatePointsArray()) {
  8219. return pickingInfo;
  8220. }
  8221. var intersectInfo = null;
  8222. // Octrees
  8223. var subMeshes;
  8224. var len;
  8225. if (this._submeshesOctree && this.useOctreeForPicking) {
  8226. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8227. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8228. len = intersections.length;
  8229. subMeshes = intersections.data;
  8230. }
  8231. else {
  8232. subMeshes = this.subMeshes;
  8233. len = subMeshes.length;
  8234. }
  8235. for (var index = 0; index < len; index++) {
  8236. var subMesh = subMeshes[index];
  8237. // Bounding test
  8238. if (len > 1 && !subMesh.canIntersects(ray))
  8239. continue;
  8240. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8241. if (currentIntersectInfo) {
  8242. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8243. intersectInfo = currentIntersectInfo;
  8244. intersectInfo.subMeshId = index;
  8245. if (fastCheck) {
  8246. break;
  8247. }
  8248. }
  8249. }
  8250. }
  8251. if (intersectInfo) {
  8252. // Get picked point
  8253. var world = this.getWorldMatrix();
  8254. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8255. var direction = ray.direction.clone();
  8256. direction = direction.scale(intersectInfo.distance);
  8257. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8258. var pickedPoint = worldOrigin.add(worldDirection);
  8259. // Return result
  8260. pickingInfo.hit = true;
  8261. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8262. pickingInfo.pickedPoint = pickedPoint;
  8263. pickingInfo.pickedMesh = this;
  8264. pickingInfo.bu = intersectInfo.bu;
  8265. pickingInfo.bv = intersectInfo.bv;
  8266. pickingInfo.faceId = intersectInfo.faceId;
  8267. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8268. return pickingInfo;
  8269. }
  8270. return pickingInfo;
  8271. };
  8272. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8273. return null;
  8274. };
  8275. AbstractMesh.prototype.releaseSubMeshes = function () {
  8276. if (this.subMeshes) {
  8277. while (this.subMeshes.length) {
  8278. this.subMeshes[0].dispose();
  8279. }
  8280. }
  8281. else {
  8282. this.subMeshes = new Array();
  8283. }
  8284. };
  8285. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8286. var index;
  8287. // Physics
  8288. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8289. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8290. }
  8291. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8292. var other = this._intersectionsInProgress[index];
  8293. var pos = other._intersectionsInProgress.indexOf(this);
  8294. other._intersectionsInProgress.splice(pos, 1);
  8295. }
  8296. this._intersectionsInProgress = [];
  8297. // SubMeshes
  8298. this.releaseSubMeshes();
  8299. // Remove from scene
  8300. this.getScene().removeMesh(this);
  8301. if (!doNotRecurse) {
  8302. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8303. if (this.getScene().particleSystems[index].emitter === this) {
  8304. this.getScene().particleSystems[index].dispose();
  8305. index--;
  8306. }
  8307. }
  8308. // Children
  8309. var objects = this.getScene().meshes.slice(0);
  8310. for (index = 0; index < objects.length; index++) {
  8311. if (objects[index].parent === this) {
  8312. objects[index].dispose();
  8313. }
  8314. }
  8315. }
  8316. else {
  8317. for (index = 0; index < this.getScene().meshes.length; index++) {
  8318. var obj = this.getScene().meshes[index];
  8319. if (obj.parent === this) {
  8320. obj.parent = null;
  8321. obj.computeWorldMatrix(true);
  8322. }
  8323. }
  8324. }
  8325. this._onAfterWorldMatrixUpdate = [];
  8326. this._isDisposed = true;
  8327. // Callback
  8328. if (this.onDispose) {
  8329. this.onDispose();
  8330. }
  8331. };
  8332. // Statics
  8333. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8334. AbstractMesh._BILLBOARDMODE_X = 1;
  8335. AbstractMesh._BILLBOARDMODE_Y = 2;
  8336. AbstractMesh._BILLBOARDMODE_Z = 4;
  8337. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8338. return AbstractMesh;
  8339. })(BABYLON.Node);
  8340. BABYLON.AbstractMesh = AbstractMesh;
  8341. })(BABYLON || (BABYLON = {}));
  8342. //# sourceMappingURL=babylon.abstractMesh.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 Light = (function (_super) {
  8352. __extends(Light, _super);
  8353. function Light(name, scene) {
  8354. _super.call(this, name, scene);
  8355. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8356. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8357. this.intensity = 1.0;
  8358. this.range = Number.MAX_VALUE;
  8359. this.includeOnlyWithLayerMask = 0;
  8360. this.includedOnlyMeshes = new Array();
  8361. this.excludedMeshes = new Array();
  8362. this.excludeWithLayerMask = 0;
  8363. this._excludedMeshesIds = new Array();
  8364. this._includedOnlyMeshesIds = new Array();
  8365. scene.addLight(this);
  8366. }
  8367. Light.prototype.getShadowGenerator = function () {
  8368. return this._shadowGenerator;
  8369. };
  8370. Light.prototype.getAbsolutePosition = function () {
  8371. return BABYLON.Vector3.Zero();
  8372. };
  8373. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8374. };
  8375. Light.prototype._getWorldMatrix = function () {
  8376. return BABYLON.Matrix.Identity();
  8377. };
  8378. Light.prototype.canAffectMesh = function (mesh) {
  8379. if (!mesh) {
  8380. return true;
  8381. }
  8382. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8383. return false;
  8384. }
  8385. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8386. return false;
  8387. }
  8388. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8389. return false;
  8390. }
  8391. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8392. return false;
  8393. }
  8394. return true;
  8395. };
  8396. Light.prototype.getWorldMatrix = function () {
  8397. this._currentRenderId = this.getScene().getRenderId();
  8398. var worldMatrix = this._getWorldMatrix();
  8399. if (this.parent && this.parent.getWorldMatrix) {
  8400. if (!this._parentedWorldMatrix) {
  8401. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8402. }
  8403. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8404. this._markSyncedWithParent();
  8405. return this._parentedWorldMatrix;
  8406. }
  8407. return worldMatrix;
  8408. };
  8409. Light.prototype.dispose = function () {
  8410. if (this._shadowGenerator) {
  8411. this._shadowGenerator.dispose();
  8412. this._shadowGenerator = null;
  8413. }
  8414. // Remove from scene
  8415. this.getScene().removeLight(this);
  8416. };
  8417. return Light;
  8418. })(BABYLON.Node);
  8419. BABYLON.Light = Light;
  8420. })(BABYLON || (BABYLON = {}));
  8421. //# sourceMappingURL=babylon.light.js.map
  8422. var __extends = this.__extends || function (d, b) {
  8423. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8424. function __() { this.constructor = d; }
  8425. __.prototype = b.prototype;
  8426. d.prototype = new __();
  8427. };
  8428. var BABYLON;
  8429. (function (BABYLON) {
  8430. var PointLight = (function (_super) {
  8431. __extends(PointLight, _super);
  8432. function PointLight(name, position, scene) {
  8433. _super.call(this, name, scene);
  8434. this.position = position;
  8435. }
  8436. PointLight.prototype.getAbsolutePosition = function () {
  8437. return this._transformedPosition ? this._transformedPosition : this.position;
  8438. };
  8439. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8440. if (this.parent && this.parent.getWorldMatrix) {
  8441. if (!this._transformedPosition) {
  8442. this._transformedPosition = BABYLON.Vector3.Zero();
  8443. }
  8444. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8445. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8446. return;
  8447. }
  8448. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8449. };
  8450. PointLight.prototype.getShadowGenerator = function () {
  8451. return null;
  8452. };
  8453. PointLight.prototype._getWorldMatrix = function () {
  8454. if (!this._worldMatrix) {
  8455. this._worldMatrix = BABYLON.Matrix.Identity();
  8456. }
  8457. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8458. return this._worldMatrix;
  8459. };
  8460. return PointLight;
  8461. })(BABYLON.Light);
  8462. BABYLON.PointLight = PointLight;
  8463. })(BABYLON || (BABYLON = {}));
  8464. //# sourceMappingURL=babylon.pointLight.js.map
  8465. var __extends = this.__extends || function (d, b) {
  8466. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8467. function __() { this.constructor = d; }
  8468. __.prototype = b.prototype;
  8469. d.prototype = new __();
  8470. };
  8471. var BABYLON;
  8472. (function (BABYLON) {
  8473. var SpotLight = (function (_super) {
  8474. __extends(SpotLight, _super);
  8475. function SpotLight(name, position, direction, angle, exponent, scene) {
  8476. _super.call(this, name, scene);
  8477. this.position = position;
  8478. this.direction = direction;
  8479. this.angle = angle;
  8480. this.exponent = exponent;
  8481. }
  8482. SpotLight.prototype.getAbsolutePosition = function () {
  8483. return this.transformedPosition ? this.transformedPosition : this.position;
  8484. };
  8485. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8486. var activeCamera = this.getScene().activeCamera;
  8487. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8488. };
  8489. SpotLight.prototype.supportsVSM = function () {
  8490. return true;
  8491. };
  8492. SpotLight.prototype.needRefreshPerFrame = function () {
  8493. return false;
  8494. };
  8495. SpotLight.prototype.setDirectionToTarget = function (target) {
  8496. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8497. return this.direction;
  8498. };
  8499. SpotLight.prototype.computeTransformedPosition = function () {
  8500. if (this.parent && this.parent.getWorldMatrix) {
  8501. if (!this.transformedPosition) {
  8502. this.transformedPosition = BABYLON.Vector3.Zero();
  8503. }
  8504. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8505. return true;
  8506. }
  8507. return false;
  8508. };
  8509. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8510. var normalizeDirection;
  8511. if (this.parent && this.parent.getWorldMatrix) {
  8512. if (!this._transformedDirection) {
  8513. this._transformedDirection = BABYLON.Vector3.Zero();
  8514. }
  8515. this.computeTransformedPosition();
  8516. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8517. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8518. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8519. }
  8520. else {
  8521. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8522. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8523. }
  8524. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8525. };
  8526. SpotLight.prototype._getWorldMatrix = function () {
  8527. if (!this._worldMatrix) {
  8528. this._worldMatrix = BABYLON.Matrix.Identity();
  8529. }
  8530. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8531. return this._worldMatrix;
  8532. };
  8533. return SpotLight;
  8534. })(BABYLON.Light);
  8535. BABYLON.SpotLight = SpotLight;
  8536. })(BABYLON || (BABYLON = {}));
  8537. //# sourceMappingURL=babylon.spotLight.js.map
  8538. var __extends = this.__extends || function (d, b) {
  8539. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8540. function __() { this.constructor = d; }
  8541. __.prototype = b.prototype;
  8542. d.prototype = new __();
  8543. };
  8544. var BABYLON;
  8545. (function (BABYLON) {
  8546. var HemisphericLight = (function (_super) {
  8547. __extends(HemisphericLight, _super);
  8548. function HemisphericLight(name, direction, scene) {
  8549. _super.call(this, name, scene);
  8550. this.direction = direction;
  8551. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8552. }
  8553. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8554. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8555. return this.direction;
  8556. };
  8557. HemisphericLight.prototype.getShadowGenerator = function () {
  8558. return null;
  8559. };
  8560. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8561. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8562. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8563. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8564. };
  8565. HemisphericLight.prototype._getWorldMatrix = function () {
  8566. if (!this._worldMatrix) {
  8567. this._worldMatrix = BABYLON.Matrix.Identity();
  8568. }
  8569. return this._worldMatrix;
  8570. };
  8571. return HemisphericLight;
  8572. })(BABYLON.Light);
  8573. BABYLON.HemisphericLight = HemisphericLight;
  8574. })(BABYLON || (BABYLON = {}));
  8575. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8576. var __extends = this.__extends || function (d, b) {
  8577. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8578. function __() { this.constructor = d; }
  8579. __.prototype = b.prototype;
  8580. d.prototype = new __();
  8581. };
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. var DirectionalLight = (function (_super) {
  8585. __extends(DirectionalLight, _super);
  8586. function DirectionalLight(name, direction, scene) {
  8587. _super.call(this, name, scene);
  8588. this.direction = direction;
  8589. this.shadowOrthoScale = 0.5;
  8590. this.position = direction.scale(-1);
  8591. }
  8592. DirectionalLight.prototype.getAbsolutePosition = function () {
  8593. return this.transformedPosition ? this.transformedPosition : this.position;
  8594. };
  8595. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8596. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8597. return this.direction;
  8598. };
  8599. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8600. var orthoLeft = Number.MAX_VALUE;
  8601. var orthoRight = Number.MIN_VALUE;
  8602. var orthoTop = Number.MIN_VALUE;
  8603. var orthoBottom = Number.MAX_VALUE;
  8604. var tempVector3 = BABYLON.Vector3.Zero();
  8605. var activeCamera = this.getScene().activeCamera;
  8606. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8607. var mesh = renderList[meshIndex];
  8608. if (!mesh) {
  8609. continue;
  8610. }
  8611. var boundingInfo = mesh.getBoundingInfo();
  8612. if (!boundingInfo) {
  8613. continue;
  8614. }
  8615. var boundingBox = boundingInfo.boundingBox;
  8616. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8617. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8618. if (tempVector3.x < orthoLeft)
  8619. orthoLeft = tempVector3.x;
  8620. if (tempVector3.y < orthoBottom)
  8621. orthoBottom = tempVector3.y;
  8622. if (tempVector3.x > orthoRight)
  8623. orthoRight = tempVector3.x;
  8624. if (tempVector3.y > orthoTop)
  8625. orthoTop = tempVector3.y;
  8626. }
  8627. }
  8628. var xOffset = orthoRight - orthoLeft;
  8629. var yOffset = orthoTop - orthoBottom;
  8630. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8631. };
  8632. DirectionalLight.prototype.supportsVSM = function () {
  8633. return true;
  8634. };
  8635. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8636. return true;
  8637. };
  8638. DirectionalLight.prototype.computeTransformedPosition = function () {
  8639. if (this.parent && this.parent.getWorldMatrix) {
  8640. if (!this.transformedPosition) {
  8641. this.transformedPosition = BABYLON.Vector3.Zero();
  8642. }
  8643. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8644. return true;
  8645. }
  8646. return false;
  8647. };
  8648. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8649. if (this.parent && this.parent.getWorldMatrix) {
  8650. if (!this._transformedDirection) {
  8651. this._transformedDirection = BABYLON.Vector3.Zero();
  8652. }
  8653. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8654. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8655. return;
  8656. }
  8657. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8658. };
  8659. DirectionalLight.prototype._getWorldMatrix = function () {
  8660. if (!this._worldMatrix) {
  8661. this._worldMatrix = BABYLON.Matrix.Identity();
  8662. }
  8663. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8664. return this._worldMatrix;
  8665. };
  8666. return DirectionalLight;
  8667. })(BABYLON.Light);
  8668. BABYLON.DirectionalLight = DirectionalLight;
  8669. })(BABYLON || (BABYLON = {}));
  8670. //# sourceMappingURL=babylon.directionalLight.js.map
  8671. var BABYLON;
  8672. (function (BABYLON) {
  8673. var ShadowGenerator = (function () {
  8674. function ShadowGenerator(mapSize, light) {
  8675. var _this = this;
  8676. // Members
  8677. this._filter = ShadowGenerator.FILTER_NONE;
  8678. this.blurScale = 2;
  8679. this._blurBoxOffset = 0;
  8680. this._bias = 0.00005;
  8681. this._darkness = 0;
  8682. this._transparencyShadow = false;
  8683. this._viewMatrix = BABYLON.Matrix.Zero();
  8684. this._projectionMatrix = BABYLON.Matrix.Zero();
  8685. this._transformMatrix = BABYLON.Matrix.Zero();
  8686. this._worldViewProjection = BABYLON.Matrix.Zero();
  8687. this._light = light;
  8688. this._scene = light.getScene();
  8689. this._mapSize = mapSize;
  8690. light._shadowGenerator = this;
  8691. // Render target
  8692. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8693. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8694. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8695. this._shadowMap.anisotropicFilteringLevel = 1;
  8696. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8697. this._shadowMap.renderParticles = false;
  8698. this._shadowMap.onAfterUnbind = function () {
  8699. if (!_this.useBlurVarianceShadowMap) {
  8700. return;
  8701. }
  8702. if (!_this._shadowMap2) {
  8703. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8704. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8705. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8706. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8707. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8708. _this._downSamplePostprocess.onApply = function (effect) {
  8709. effect.setTexture("textureSampler", _this._shadowMap);
  8710. };
  8711. _this.blurBoxOffset = 1;
  8712. }
  8713. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8714. };
  8715. // Custom render function
  8716. var renderSubMesh = function (subMesh) {
  8717. var mesh = subMesh.getRenderingMesh();
  8718. var scene = _this._scene;
  8719. var engine = scene.getEngine();
  8720. // Culling
  8721. engine.setState(subMesh.getMaterial().backFaceCulling);
  8722. // Managing instances
  8723. var batch = mesh._getInstancesRenderList(subMesh._id);
  8724. if (batch.mustReturn) {
  8725. return;
  8726. }
  8727. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8728. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8729. engine.enableEffect(_this._effect);
  8730. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8731. var material = subMesh.getMaterial();
  8732. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8733. // Alpha test
  8734. if (material && material.needAlphaTesting()) {
  8735. var alphaTexture = material.getAlphaTestTexture();
  8736. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8737. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8738. }
  8739. // Bones
  8740. if (mesh.useBones) {
  8741. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8742. }
  8743. // Draw
  8744. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8745. }
  8746. else {
  8747. // Need to reset refresh rate of the shadowMap
  8748. _this._shadowMap.resetRefreshCounter();
  8749. }
  8750. };
  8751. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8752. var index;
  8753. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8754. renderSubMesh(opaqueSubMeshes.data[index]);
  8755. }
  8756. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8757. renderSubMesh(alphaTestSubMeshes.data[index]);
  8758. }
  8759. if (_this._transparencyShadow) {
  8760. for (index = 0; index < transparentSubMeshes.length; index++) {
  8761. renderSubMesh(transparentSubMeshes.data[index]);
  8762. }
  8763. }
  8764. };
  8765. this._shadowMap.onClear = function (engine) {
  8766. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8767. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8768. }
  8769. else {
  8770. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8771. }
  8772. };
  8773. }
  8774. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8775. // Static
  8776. get: function () {
  8777. return ShadowGenerator._FILTER_NONE;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8783. get: function () {
  8784. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8790. get: function () {
  8791. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8797. get: function () {
  8798. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8799. },
  8800. enumerable: true,
  8801. configurable: true
  8802. });
  8803. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8804. get: function () {
  8805. return this._bias;
  8806. },
  8807. set: function (bias) {
  8808. this._bias = bias;
  8809. },
  8810. enumerable: true,
  8811. configurable: true
  8812. });
  8813. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8814. get: function () {
  8815. return this._blurBoxOffset;
  8816. },
  8817. set: function (value) {
  8818. var _this = this;
  8819. if (this._blurBoxOffset === value) {
  8820. return;
  8821. }
  8822. this._blurBoxOffset = value;
  8823. if (this._boxBlurPostprocess) {
  8824. this._boxBlurPostprocess.dispose();
  8825. }
  8826. 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);
  8827. this._boxBlurPostprocess.onApply = function (effect) {
  8828. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8829. };
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8835. get: function () {
  8836. return this._filter;
  8837. },
  8838. set: function (value) {
  8839. if (this._filter === value) {
  8840. return;
  8841. }
  8842. this._filter = value;
  8843. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8844. this._shadowMap.anisotropicFilteringLevel = 16;
  8845. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8846. }
  8847. else {
  8848. this._shadowMap.anisotropicFilteringLevel = 1;
  8849. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8850. }
  8851. },
  8852. enumerable: true,
  8853. configurable: true
  8854. });
  8855. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8856. get: function () {
  8857. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8858. },
  8859. set: function (value) {
  8860. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8866. get: function () {
  8867. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8868. },
  8869. set: function (value) {
  8870. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8871. },
  8872. enumerable: true,
  8873. configurable: true
  8874. });
  8875. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8876. get: function () {
  8877. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8878. },
  8879. set: function (value) {
  8880. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8886. var defines = [];
  8887. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8888. defines.push("#define VSM");
  8889. }
  8890. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8891. var mesh = subMesh.getMesh();
  8892. var material = subMesh.getMaterial();
  8893. // Alpha test
  8894. if (material && material.needAlphaTesting()) {
  8895. defines.push("#define ALPHATEST");
  8896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8897. attribs.push(BABYLON.VertexBuffer.UVKind);
  8898. defines.push("#define UV1");
  8899. }
  8900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8901. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8902. defines.push("#define UV2");
  8903. }
  8904. }
  8905. // Bones
  8906. if (mesh.useBones) {
  8907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8909. defines.push("#define BONES");
  8910. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8911. }
  8912. // Instances
  8913. if (useInstances) {
  8914. defines.push("#define INSTANCES");
  8915. attribs.push("world0");
  8916. attribs.push("world1");
  8917. attribs.push("world2");
  8918. attribs.push("world3");
  8919. }
  8920. // Get correct effect
  8921. var join = defines.join("\n");
  8922. if (this._cachedDefines !== join) {
  8923. this._cachedDefines = join;
  8924. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8925. }
  8926. return this._effect.isReady();
  8927. };
  8928. ShadowGenerator.prototype.getShadowMap = function () {
  8929. return this._shadowMap;
  8930. };
  8931. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8932. if (this._shadowMap2) {
  8933. return this._shadowMap2;
  8934. }
  8935. return this._shadowMap;
  8936. };
  8937. ShadowGenerator.prototype.getLight = function () {
  8938. return this._light;
  8939. };
  8940. // Methods
  8941. ShadowGenerator.prototype.getTransformMatrix = function () {
  8942. var scene = this._scene;
  8943. if (this._currentRenderID === scene.getRenderId()) {
  8944. return this._transformMatrix;
  8945. }
  8946. this._currentRenderID = scene.getRenderId();
  8947. var lightPosition = this._light.position;
  8948. var lightDirection = this._light.direction;
  8949. if (this._light.computeTransformedPosition()) {
  8950. lightPosition = this._light.transformedPosition;
  8951. }
  8952. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8953. this._cachedPosition = lightPosition.clone();
  8954. this._cachedDirection = lightDirection.clone();
  8955. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8956. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8957. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8958. }
  8959. return this._transformMatrix;
  8960. };
  8961. ShadowGenerator.prototype.getDarkness = function () {
  8962. return this._darkness;
  8963. };
  8964. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8965. if (darkness >= 1.0)
  8966. this._darkness = 1.0;
  8967. else if (darkness <= 0.0)
  8968. this._darkness = 0.0;
  8969. else
  8970. this._darkness = darkness;
  8971. };
  8972. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8973. this._transparencyShadow = hasShadow;
  8974. };
  8975. ShadowGenerator.prototype._packHalf = function (depth) {
  8976. var scale = depth * 255.0;
  8977. var fract = scale - Math.floor(scale);
  8978. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8979. };
  8980. ShadowGenerator.prototype.dispose = function () {
  8981. this._shadowMap.dispose();
  8982. if (this._shadowMap2) {
  8983. this._shadowMap2.dispose();
  8984. }
  8985. if (this._downSamplePostprocess) {
  8986. this._downSamplePostprocess.dispose();
  8987. }
  8988. if (this._boxBlurPostprocess) {
  8989. this._boxBlurPostprocess.dispose();
  8990. }
  8991. };
  8992. ShadowGenerator._FILTER_NONE = 0;
  8993. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8994. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8995. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8996. return ShadowGenerator;
  8997. })();
  8998. BABYLON.ShadowGenerator = ShadowGenerator;
  8999. })(BABYLON || (BABYLON = {}));
  9000. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9001. var BABYLON;
  9002. (function (BABYLON) {
  9003. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9004. if (boxMin.x > sphereCenter.x + sphereRadius)
  9005. return false;
  9006. if (sphereCenter.x - sphereRadius > boxMax.x)
  9007. return false;
  9008. if (boxMin.y > sphereCenter.y + sphereRadius)
  9009. return false;
  9010. if (sphereCenter.y - sphereRadius > boxMax.y)
  9011. return false;
  9012. if (boxMin.z > sphereCenter.z + sphereRadius)
  9013. return false;
  9014. if (sphereCenter.z - sphereRadius > boxMax.z)
  9015. return false;
  9016. return true;
  9017. };
  9018. var getLowestRoot = function (a, b, c, maxR) {
  9019. var determinant = b * b - 4.0 * a * c;
  9020. var result = { root: 0, found: false };
  9021. if (determinant < 0)
  9022. return result;
  9023. var sqrtD = Math.sqrt(determinant);
  9024. var r1 = (-b - sqrtD) / (2.0 * a);
  9025. var r2 = (-b + sqrtD) / (2.0 * a);
  9026. if (r1 > r2) {
  9027. var temp = r2;
  9028. r2 = r1;
  9029. r1 = temp;
  9030. }
  9031. if (r1 > 0 && r1 < maxR) {
  9032. result.root = r1;
  9033. result.found = true;
  9034. return result;
  9035. }
  9036. if (r2 > 0 && r2 < maxR) {
  9037. result.root = r2;
  9038. result.found = true;
  9039. return result;
  9040. }
  9041. return result;
  9042. };
  9043. var Collider = (function () {
  9044. function Collider() {
  9045. this.radius = new BABYLON.Vector3(1, 1, 1);
  9046. this.retry = 0;
  9047. this.basePointWorld = BABYLON.Vector3.Zero();
  9048. this.velocityWorld = BABYLON.Vector3.Zero();
  9049. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9050. this._collisionPoint = BABYLON.Vector3.Zero();
  9051. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9052. this._tempVector = BABYLON.Vector3.Zero();
  9053. this._tempVector2 = BABYLON.Vector3.Zero();
  9054. this._tempVector3 = BABYLON.Vector3.Zero();
  9055. this._tempVector4 = BABYLON.Vector3.Zero();
  9056. this._edge = BABYLON.Vector3.Zero();
  9057. this._baseToVertex = BABYLON.Vector3.Zero();
  9058. this._destinationPoint = BABYLON.Vector3.Zero();
  9059. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9060. this._displacementVector = BABYLON.Vector3.Zero();
  9061. }
  9062. // Methods
  9063. Collider.prototype._initialize = function (source, dir, e) {
  9064. this.velocity = dir;
  9065. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9066. this.basePoint = source;
  9067. source.multiplyToRef(this.radius, this.basePointWorld);
  9068. dir.multiplyToRef(this.radius, this.velocityWorld);
  9069. this.velocityWorldLength = this.velocityWorld.length();
  9070. this.epsilon = e;
  9071. this.collisionFound = false;
  9072. };
  9073. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9074. pa.subtractToRef(point, this._tempVector);
  9075. pb.subtractToRef(point, this._tempVector2);
  9076. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9077. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9078. if (d < 0)
  9079. return false;
  9080. pc.subtractToRef(point, this._tempVector3);
  9081. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9082. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9083. if (d < 0)
  9084. return false;
  9085. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9086. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9087. return d >= 0;
  9088. };
  9089. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9090. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9091. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9092. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9093. return false;
  9094. }
  9095. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9096. return false;
  9097. return true;
  9098. };
  9099. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9100. var t0;
  9101. var embeddedInPlane = false;
  9102. //defensive programming, actually not needed.
  9103. if (!trianglePlaneArray) {
  9104. trianglePlaneArray = [];
  9105. }
  9106. if (!trianglePlaneArray[faceIndex]) {
  9107. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9108. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9109. }
  9110. var trianglePlane = trianglePlaneArray[faceIndex];
  9111. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9112. return;
  9113. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9114. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9115. if (normalDotVelocity == 0) {
  9116. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9117. return;
  9118. embeddedInPlane = true;
  9119. t0 = 0;
  9120. }
  9121. else {
  9122. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9123. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9124. if (t0 > t1) {
  9125. var temp = t1;
  9126. t1 = t0;
  9127. t0 = temp;
  9128. }
  9129. if (t0 > 1.0 || t1 < 0.0)
  9130. return;
  9131. if (t0 < 0)
  9132. t0 = 0;
  9133. if (t0 > 1.0)
  9134. t0 = 1.0;
  9135. }
  9136. this._collisionPoint.copyFromFloats(0, 0, 0);
  9137. var found = false;
  9138. var t = 1.0;
  9139. if (!embeddedInPlane) {
  9140. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9141. this.velocity.scaleToRef(t0, this._tempVector);
  9142. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9143. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9144. found = true;
  9145. t = t0;
  9146. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9147. }
  9148. }
  9149. if (!found) {
  9150. var velocitySquaredLength = this.velocity.lengthSquared();
  9151. var a = velocitySquaredLength;
  9152. this.basePoint.subtractToRef(p1, this._tempVector);
  9153. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9154. var c = this._tempVector.lengthSquared() - 1.0;
  9155. var lowestRoot = getLowestRoot(a, b, c, t);
  9156. if (lowestRoot.found) {
  9157. t = lowestRoot.root;
  9158. found = true;
  9159. this._collisionPoint.copyFrom(p1);
  9160. }
  9161. this.basePoint.subtractToRef(p2, this._tempVector);
  9162. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9163. c = this._tempVector.lengthSquared() - 1.0;
  9164. lowestRoot = getLowestRoot(a, b, c, t);
  9165. if (lowestRoot.found) {
  9166. t = lowestRoot.root;
  9167. found = true;
  9168. this._collisionPoint.copyFrom(p2);
  9169. }
  9170. this.basePoint.subtractToRef(p3, this._tempVector);
  9171. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9172. c = this._tempVector.lengthSquared() - 1.0;
  9173. lowestRoot = getLowestRoot(a, b, c, t);
  9174. if (lowestRoot.found) {
  9175. t = lowestRoot.root;
  9176. found = true;
  9177. this._collisionPoint.copyFrom(p3);
  9178. }
  9179. p2.subtractToRef(p1, this._edge);
  9180. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9181. var edgeSquaredLength = this._edge.lengthSquared();
  9182. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9183. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9184. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9185. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9186. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9187. lowestRoot = getLowestRoot(a, b, c, t);
  9188. if (lowestRoot.found) {
  9189. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9190. if (f >= 0.0 && f <= 1.0) {
  9191. t = lowestRoot.root;
  9192. found = true;
  9193. this._edge.scaleInPlace(f);
  9194. p1.addToRef(this._edge, this._collisionPoint);
  9195. }
  9196. }
  9197. p3.subtractToRef(p2, this._edge);
  9198. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9199. edgeSquaredLength = this._edge.lengthSquared();
  9200. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9201. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9202. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9203. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9204. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9205. lowestRoot = getLowestRoot(a, b, c, t);
  9206. if (lowestRoot.found) {
  9207. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9208. if (f >= 0.0 && f <= 1.0) {
  9209. t = lowestRoot.root;
  9210. found = true;
  9211. this._edge.scaleInPlace(f);
  9212. p2.addToRef(this._edge, this._collisionPoint);
  9213. }
  9214. }
  9215. p1.subtractToRef(p3, this._edge);
  9216. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9217. edgeSquaredLength = this._edge.lengthSquared();
  9218. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9219. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9220. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9221. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9222. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9223. lowestRoot = getLowestRoot(a, b, c, t);
  9224. if (lowestRoot.found) {
  9225. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9226. if (f >= 0.0 && f <= 1.0) {
  9227. t = lowestRoot.root;
  9228. found = true;
  9229. this._edge.scaleInPlace(f);
  9230. p3.addToRef(this._edge, this._collisionPoint);
  9231. }
  9232. }
  9233. }
  9234. if (found) {
  9235. var distToCollision = t * this.velocity.length();
  9236. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9237. if (!this.intersectionPoint) {
  9238. this.intersectionPoint = this._collisionPoint.clone();
  9239. }
  9240. else {
  9241. this.intersectionPoint.copyFrom(this._collisionPoint);
  9242. }
  9243. this.nearestDistance = distToCollision;
  9244. this.collisionFound = true;
  9245. }
  9246. }
  9247. };
  9248. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9249. for (var i = indexStart; i < indexEnd; i += 3) {
  9250. var p1 = pts[indices[i] - decal];
  9251. var p2 = pts[indices[i + 1] - decal];
  9252. var p3 = pts[indices[i + 2] - decal];
  9253. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9254. }
  9255. };
  9256. Collider.prototype._getResponse = function (pos, vel) {
  9257. pos.addToRef(vel, this._destinationPoint);
  9258. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9259. this.basePoint.addToRef(vel, pos);
  9260. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9261. this._slidePlaneNormal.normalize();
  9262. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9263. pos.addInPlace(this._displacementVector);
  9264. this.intersectionPoint.addInPlace(this._displacementVector);
  9265. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9266. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9267. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9268. };
  9269. return Collider;
  9270. })();
  9271. BABYLON.Collider = Collider;
  9272. })(BABYLON || (BABYLON = {}));
  9273. //# sourceMappingURL=babylon.collider.js.map
  9274. var BABYLON;
  9275. (function (BABYLON) {
  9276. //WebWorker code will be inserted to this variable.
  9277. BABYLON.CollisionWorker = "";
  9278. (function (WorkerTaskType) {
  9279. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9280. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9281. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9282. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9283. var WorkerTaskType = BABYLON.WorkerTaskType;
  9284. (function (WorkerReplyType) {
  9285. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9286. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9287. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9288. var WorkerReplyType = BABYLON.WorkerReplyType;
  9289. var CollisionCoordinatorWorker = (function () {
  9290. function CollisionCoordinatorWorker() {
  9291. var _this = this;
  9292. this._scaledPosition = BABYLON.Vector3.Zero();
  9293. this._scaledVelocity = BABYLON.Vector3.Zero();
  9294. this.onMeshUpdated = function (mesh) {
  9295. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9296. };
  9297. this.onGeometryUpdated = function (geometry) {
  9298. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9299. };
  9300. this._afterRender = function () {
  9301. if (!_this._init)
  9302. return;
  9303. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9304. return;
  9305. }
  9306. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9307. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9308. if (_this._runningUpdated > 4) {
  9309. return;
  9310. }
  9311. ++_this._runningUpdated;
  9312. var payload = {
  9313. updatedMeshes: _this._addUpdateMeshesList,
  9314. updatedGeometries: _this._addUpdateGeometriesList,
  9315. removedGeometries: _this._toRemoveGeometryArray,
  9316. removedMeshes: _this._toRemoveMeshesArray
  9317. };
  9318. var message = {
  9319. payload: payload,
  9320. taskType: 1 /* UPDATE */
  9321. };
  9322. var serializable = [];
  9323. for (var id in payload.updatedGeometries) {
  9324. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9325. //prepare transferables
  9326. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9327. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9328. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9329. }
  9330. }
  9331. _this._worker.postMessage(message, serializable);
  9332. _this._addUpdateMeshesList = {};
  9333. _this._addUpdateGeometriesList = {};
  9334. _this._toRemoveGeometryArray = [];
  9335. _this._toRemoveMeshesArray = [];
  9336. };
  9337. this._onMessageFromWorker = function (e) {
  9338. var returnData = e.data;
  9339. if (returnData.error != 0 /* SUCCESS */) {
  9340. //TODO what errors can be returned from the worker?
  9341. BABYLON.Tools.Warn("error returned from worker!");
  9342. return;
  9343. }
  9344. switch (returnData.taskType) {
  9345. case 0 /* INIT */:
  9346. _this._init = true;
  9347. //Update the worked with ALL of the scene's current state
  9348. _this._scene.meshes.forEach(function (mesh) {
  9349. _this.onMeshAdded(mesh);
  9350. });
  9351. _this._scene.getGeometries().forEach(function (geometry) {
  9352. _this.onGeometryAdded(geometry);
  9353. });
  9354. break;
  9355. case 1 /* UPDATE */:
  9356. _this._runningUpdated--;
  9357. break;
  9358. case 2 /* COLLIDE */:
  9359. _this._runningCollisionTask = false;
  9360. var returnPayload = returnData.payload;
  9361. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9362. return;
  9363. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9364. //cleanup
  9365. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9366. break;
  9367. }
  9368. };
  9369. this._collisionsCallbackArray = [];
  9370. this._init = false;
  9371. this._runningUpdated = 0;
  9372. this._runningCollisionTask = false;
  9373. this._addUpdateMeshesList = {};
  9374. this._addUpdateGeometriesList = {};
  9375. this._toRemoveGeometryArray = [];
  9376. this._toRemoveMeshesArray = [];
  9377. }
  9378. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9379. if (!this._init)
  9380. return;
  9381. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9382. return;
  9383. position.divideToRef(collider.radius, this._scaledPosition);
  9384. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9385. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9386. var payload = {
  9387. collider: {
  9388. position: this._scaledPosition.asArray(),
  9389. velocity: this._scaledVelocity.asArray(),
  9390. radius: collider.radius.asArray()
  9391. },
  9392. collisionId: collisionIndex,
  9393. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9394. maximumRetry: maximumRetry
  9395. };
  9396. var message = {
  9397. payload: payload,
  9398. taskType: 2 /* COLLIDE */
  9399. };
  9400. this._worker.postMessage(message);
  9401. };
  9402. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9403. this._scene = scene;
  9404. this._scene.registerAfterRender(this._afterRender);
  9405. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9406. this._worker = new Worker(workerUrl);
  9407. this._worker.onmessage = this._onMessageFromWorker;
  9408. var message = {
  9409. payload: {},
  9410. taskType: 0 /* INIT */
  9411. };
  9412. this._worker.postMessage(message);
  9413. };
  9414. CollisionCoordinatorWorker.prototype.destroy = function () {
  9415. this._scene.unregisterAfterRender(this._afterRender);
  9416. this._worker.terminate();
  9417. };
  9418. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9419. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9420. this.onMeshUpdated(mesh);
  9421. };
  9422. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9423. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9424. };
  9425. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9426. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9427. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9428. this.onGeometryUpdated(geometry);
  9429. };
  9430. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9431. this._toRemoveGeometryArray.push(geometry.id);
  9432. };
  9433. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9434. var submeshes = [];
  9435. if (mesh.subMeshes) {
  9436. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9437. return {
  9438. position: idx,
  9439. verticesStart: sm.verticesStart,
  9440. verticesCount: sm.verticesCount,
  9441. indexStart: sm.indexStart,
  9442. indexCount: sm.indexCount,
  9443. hasMaterial: !!sm.getMaterial(),
  9444. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9445. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9446. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9447. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9448. };
  9449. });
  9450. }
  9451. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9452. return {
  9453. uniqueId: mesh.uniqueId,
  9454. id: mesh.id,
  9455. name: mesh.name,
  9456. geometryId: geometryId,
  9457. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9458. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9459. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9460. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9461. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9462. subMeshes: submeshes,
  9463. checkCollisions: mesh.checkCollisions
  9464. };
  9465. };
  9466. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9467. return {
  9468. id: geometry.id,
  9469. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9470. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9471. indices: new Int32Array(geometry.getIndices() || []),
  9472. };
  9473. };
  9474. return CollisionCoordinatorWorker;
  9475. })();
  9476. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9477. var CollisionCoordinatorLegacy = (function () {
  9478. function CollisionCoordinatorLegacy() {
  9479. this._scaledPosition = BABYLON.Vector3.Zero();
  9480. this._scaledVelocity = BABYLON.Vector3.Zero();
  9481. this._finalPosition = BABYLON.Vector3.Zero();
  9482. }
  9483. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9484. position.divideToRef(collider.radius, this._scaledPosition);
  9485. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9486. collider.retry = 0;
  9487. collider.initialVelocity = this._scaledVelocity;
  9488. collider.initialPosition = this._scaledPosition;
  9489. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9490. this._finalPosition.multiplyInPlace(collider.radius);
  9491. //run the callback
  9492. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9493. };
  9494. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9495. this._scene = scene;
  9496. };
  9497. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9498. //Legacy need no destruction method.
  9499. };
  9500. //No update in legacy mode
  9501. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9502. };
  9503. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9504. };
  9505. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9506. };
  9507. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9508. };
  9509. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9510. };
  9511. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9512. };
  9513. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9514. if (excludedMesh === void 0) { excludedMesh = null; }
  9515. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9516. if (collider.retry >= maximumRetry) {
  9517. finalPosition.copyFrom(position);
  9518. return;
  9519. }
  9520. collider._initialize(position, velocity, closeDistance);
  9521. for (var index = 0; index < this._scene.meshes.length; index++) {
  9522. var mesh = this._scene.meshes[index];
  9523. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9524. mesh._checkCollision(collider);
  9525. }
  9526. }
  9527. if (!collider.collisionFound) {
  9528. position.addToRef(velocity, finalPosition);
  9529. return;
  9530. }
  9531. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9532. collider._getResponse(position, velocity);
  9533. }
  9534. if (velocity.length() <= closeDistance) {
  9535. finalPosition.copyFrom(position);
  9536. return;
  9537. }
  9538. collider.retry++;
  9539. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9540. };
  9541. return CollisionCoordinatorLegacy;
  9542. })();
  9543. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9544. })(BABYLON || (BABYLON = {}));
  9545. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9546. var __extends = this.__extends || function (d, b) {
  9547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9548. function __() { this.constructor = d; }
  9549. __.prototype = b.prototype;
  9550. d.prototype = new __();
  9551. };
  9552. var BABYLON;
  9553. (function (BABYLON) {
  9554. var VRCameraMetrics = (function () {
  9555. function VRCameraMetrics() {
  9556. this.compensateDistorsion = true;
  9557. }
  9558. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9559. get: function () {
  9560. return this.hResolution / (2 * this.vResolution);
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9566. get: function () {
  9567. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9568. },
  9569. enumerable: true,
  9570. configurable: true
  9571. });
  9572. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9573. get: function () {
  9574. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9575. var h = (4 * meters) / this.hScreenSize;
  9576. return BABYLON.Matrix.Translation(h, 0, 0);
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9582. get: function () {
  9583. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9584. var h = (4 * meters) / this.hScreenSize;
  9585. return BABYLON.Matrix.Translation(-h, 0, 0);
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9591. get: function () {
  9592. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9598. get: function () {
  9599. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. VRCameraMetrics.GetDefault = function () {
  9605. var result = new VRCameraMetrics();
  9606. result.hResolution = 1280;
  9607. result.vResolution = 800;
  9608. result.hScreenSize = 0.149759993;
  9609. result.vScreenSize = 0.0935999975;
  9610. result.vScreenCenter = 0.0467999987, result.eyeToScreenDistance = 0.0410000011;
  9611. result.lensSeparationDistance = 0.0635000020;
  9612. result.interpupillaryDistance = 0.0640000030;
  9613. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9614. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9615. result.postProcessScaleFactor = 1.714605507808412;
  9616. result.lensCenterOffset = 0.151976421;
  9617. return result;
  9618. };
  9619. return VRCameraMetrics;
  9620. })();
  9621. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9622. var Camera = (function (_super) {
  9623. __extends(Camera, _super);
  9624. function Camera(name, position, scene) {
  9625. _super.call(this, name, scene);
  9626. this.position = position;
  9627. // Members
  9628. this.upVector = BABYLON.Vector3.Up();
  9629. this.orthoLeft = null;
  9630. this.orthoRight = null;
  9631. this.orthoBottom = null;
  9632. this.orthoTop = null;
  9633. this.fov = 0.8;
  9634. this.minZ = 1.0;
  9635. this.maxZ = 10000.0;
  9636. this.inertia = 0.9;
  9637. this.mode = Camera.PERSPECTIVE_CAMERA;
  9638. this.isIntermediate = false;
  9639. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9640. this.layerMask = 0x0FFFFFFF;
  9641. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9642. // Subcamera members
  9643. this.subCameras = new Array();
  9644. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9645. // Cache
  9646. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9647. this._projectionMatrix = new BABYLON.Matrix();
  9648. this._postProcesses = new Array();
  9649. this._postProcessesTakenIndices = [];
  9650. this._activeMeshes = new BABYLON.SmartArray(256);
  9651. this._globalPosition = BABYLON.Vector3.Zero();
  9652. scene.addCamera(this);
  9653. if (!scene.activeCamera) {
  9654. scene.activeCamera = this;
  9655. }
  9656. }
  9657. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9658. get: function () {
  9659. return Camera._PERSPECTIVE_CAMERA;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9665. get: function () {
  9666. return Camera._ORTHOGRAPHIC_CAMERA;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9672. get: function () {
  9673. return Camera._FOVMODE_VERTICAL_FIXED;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9679. get: function () {
  9680. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9686. get: function () {
  9687. return Camera._SUB_CAMERA_MODE_NONE;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9693. get: function () {
  9694. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Camera, "SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM", {
  9700. get: function () {
  9701. return Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VERTICAL_STEREOGRAM", {
  9707. get: function () {
  9708. return Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9714. get: function () {
  9715. return Camera._SUB_CAMERA_MODE_VR;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9721. get: function () {
  9722. return Camera._SUB_CAMERAID_A;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9728. get: function () {
  9729. return Camera._SUB_CAMERAID_B;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(Camera.prototype, "globalPosition", {
  9735. get: function () {
  9736. return this._globalPosition;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. Camera.prototype.getActiveMeshes = function () {
  9742. return this._activeMeshes;
  9743. };
  9744. Camera.prototype.isActiveMesh = function (mesh) {
  9745. return (this._activeMeshes.indexOf(mesh) !== -1);
  9746. };
  9747. //Cache
  9748. Camera.prototype._initCache = function () {
  9749. _super.prototype._initCache.call(this);
  9750. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9751. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9752. this._cache.mode = undefined;
  9753. this._cache.minZ = undefined;
  9754. this._cache.maxZ = undefined;
  9755. this._cache.fov = undefined;
  9756. this._cache.aspectRatio = undefined;
  9757. this._cache.orthoLeft = undefined;
  9758. this._cache.orthoRight = undefined;
  9759. this._cache.orthoBottom = undefined;
  9760. this._cache.orthoTop = undefined;
  9761. this._cache.renderWidth = undefined;
  9762. this._cache.renderHeight = undefined;
  9763. };
  9764. Camera.prototype._updateCache = function (ignoreParentClass) {
  9765. if (!ignoreParentClass) {
  9766. _super.prototype._updateCache.call(this);
  9767. }
  9768. var engine = this.getEngine();
  9769. this._cache.position.copyFrom(this.position);
  9770. this._cache.upVector.copyFrom(this.upVector);
  9771. this._cache.mode = this.mode;
  9772. this._cache.minZ = this.minZ;
  9773. this._cache.maxZ = this.maxZ;
  9774. this._cache.fov = this.fov;
  9775. this._cache.aspectRatio = engine.getAspectRatio(this);
  9776. this._cache.orthoLeft = this.orthoLeft;
  9777. this._cache.orthoRight = this.orthoRight;
  9778. this._cache.orthoBottom = this.orthoBottom;
  9779. this._cache.orthoTop = this.orthoTop;
  9780. this._cache.renderWidth = engine.getRenderWidth();
  9781. this._cache.renderHeight = engine.getRenderHeight();
  9782. };
  9783. Camera.prototype._updateFromScene = function () {
  9784. this.updateCache();
  9785. this._update();
  9786. };
  9787. // Synchronized
  9788. Camera.prototype._isSynchronized = function () {
  9789. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9790. };
  9791. Camera.prototype._isSynchronizedViewMatrix = function () {
  9792. if (!_super.prototype._isSynchronized.call(this))
  9793. return false;
  9794. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9795. };
  9796. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9797. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9798. if (!check) {
  9799. return false;
  9800. }
  9801. var engine = this.getEngine();
  9802. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9803. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9804. }
  9805. else {
  9806. 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();
  9807. }
  9808. return check;
  9809. };
  9810. // Controls
  9811. Camera.prototype.attachControl = function (element) {
  9812. };
  9813. Camera.prototype.detachControl = function (element) {
  9814. };
  9815. Camera.prototype._update = function () {
  9816. this._checkInputs();
  9817. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9818. this._updateSubCameras();
  9819. }
  9820. };
  9821. Camera.prototype._checkInputs = function () {
  9822. };
  9823. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9824. if (insertAt === void 0) { insertAt = null; }
  9825. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9826. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9827. return 0;
  9828. }
  9829. if (insertAt == null || insertAt < 0) {
  9830. this._postProcesses.push(postProcess);
  9831. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9832. return this._postProcesses.length - 1;
  9833. }
  9834. var add = 0;
  9835. if (this._postProcesses[insertAt]) {
  9836. var start = this._postProcesses.length - 1;
  9837. for (var i = start; i >= insertAt + 1; --i) {
  9838. this._postProcesses[i + 1] = this._postProcesses[i];
  9839. }
  9840. add = 1;
  9841. }
  9842. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9843. if (this._postProcessesTakenIndices[i] < insertAt) {
  9844. continue;
  9845. }
  9846. start = this._postProcessesTakenIndices.length - 1;
  9847. for (var j = start; j >= i; --j) {
  9848. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9849. }
  9850. this._postProcessesTakenIndices[i] = insertAt;
  9851. break;
  9852. }
  9853. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9854. this._postProcessesTakenIndices.push(insertAt);
  9855. }
  9856. var result = insertAt + add;
  9857. this._postProcesses[result] = postProcess;
  9858. return result;
  9859. };
  9860. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9861. if (atIndices === void 0) { atIndices = null; }
  9862. var result = [];
  9863. if (!atIndices) {
  9864. var length = this._postProcesses.length;
  9865. for (var i = 0; i < length; i++) {
  9866. if (this._postProcesses[i] !== postProcess) {
  9867. continue;
  9868. }
  9869. delete this._postProcesses[i];
  9870. var index = this._postProcessesTakenIndices.indexOf(i);
  9871. this._postProcessesTakenIndices.splice(index, 1);
  9872. }
  9873. }
  9874. else {
  9875. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9876. for (i = 0; i < atIndices.length; i++) {
  9877. var foundPostProcess = this._postProcesses[atIndices[i]];
  9878. if (foundPostProcess !== postProcess) {
  9879. result.push(i);
  9880. continue;
  9881. }
  9882. delete this._postProcesses[atIndices[i]];
  9883. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9884. this._postProcessesTakenIndices.splice(index, 1);
  9885. }
  9886. }
  9887. return result;
  9888. };
  9889. Camera.prototype.getWorldMatrix = function () {
  9890. if (!this._worldMatrix) {
  9891. this._worldMatrix = BABYLON.Matrix.Identity();
  9892. }
  9893. var viewMatrix = this.getViewMatrix();
  9894. viewMatrix.invertToRef(this._worldMatrix);
  9895. return this._worldMatrix;
  9896. };
  9897. Camera.prototype._getViewMatrix = function () {
  9898. return BABYLON.Matrix.Identity();
  9899. };
  9900. Camera.prototype.getViewMatrix = function (force) {
  9901. this._computedViewMatrix = this._computeViewMatrix(force);
  9902. if (!force && this._isSynchronizedViewMatrix()) {
  9903. return this._computedViewMatrix;
  9904. }
  9905. if (!this.parent || !this.parent.getWorldMatrix) {
  9906. this._globalPosition.copyFrom(this.position);
  9907. }
  9908. else {
  9909. if (!this._worldMatrix) {
  9910. this._worldMatrix = BABYLON.Matrix.Identity();
  9911. }
  9912. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9913. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9914. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9915. this._computedViewMatrix.invert();
  9916. this._markSyncedWithParent();
  9917. }
  9918. this._currentRenderId = this.getScene().getRenderId();
  9919. return this._computedViewMatrix;
  9920. };
  9921. Camera.prototype._computeViewMatrix = function (force) {
  9922. if (!force && this._isSynchronizedViewMatrix()) {
  9923. return this._computedViewMatrix;
  9924. }
  9925. this._computedViewMatrix = this._getViewMatrix();
  9926. this._currentRenderId = this.getScene().getRenderId();
  9927. return this._computedViewMatrix;
  9928. };
  9929. Camera.prototype.getProjectionMatrix = function (force) {
  9930. if (!force && this._isSynchronizedProjectionMatrix()) {
  9931. return this._projectionMatrix;
  9932. }
  9933. var engine = this.getEngine();
  9934. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9935. if (this.minZ <= 0) {
  9936. this.minZ = 0.1;
  9937. }
  9938. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9939. return this._projectionMatrix;
  9940. }
  9941. var halfWidth = engine.getRenderWidth() / 2.0;
  9942. var halfHeight = engine.getRenderHeight() / 2.0;
  9943. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9944. return this._projectionMatrix;
  9945. };
  9946. Camera.prototype.dispose = function () {
  9947. // Remove from scene
  9948. this.getScene().removeCamera(this);
  9949. while (this.subCameras.length > 0) {
  9950. this.subCameras.pop().dispose();
  9951. }
  9952. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9953. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9954. }
  9955. };
  9956. // ---- 3D cameras section ----
  9957. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9958. if (halfSpace === void 0) { halfSpace = 0; }
  9959. while (this.subCameras.length > 0) {
  9960. this.subCameras.pop().dispose();
  9961. }
  9962. this._subCameraMode = mode;
  9963. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9964. var camA = this.getSubCamera(this.name + "_A", true);
  9965. var camB = this.getSubCamera(this.name + "_B", false);
  9966. var postProcessA;
  9967. var postProcessB;
  9968. switch (this._subCameraMode) {
  9969. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9970. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9971. camA.isIntermediate = true;
  9972. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9973. postProcessB.onApply = function (effect) {
  9974. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  9975. };
  9976. break;
  9977. case Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM:
  9978. case Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM:
  9979. var isStereogramHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9980. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  9981. camA.isIntermediate = true;
  9982. postProcessB = new BABYLON.StereogramInterlacePostProcess("st_interlace", camB, postProcessA, isStereogramHoriz);
  9983. break;
  9984. case Camera.SUB_CAMERA_MODE_VR:
  9985. metrics = metrics || VRCameraMetrics.GetDefault();
  9986. camA._vrMetrics = metrics;
  9987. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9988. camA._vrWorkMatrix = new BABYLON.Matrix();
  9989. camA._vrHMatrix = metrics.leftHMatrix;
  9990. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  9991. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  9992. if (metrics.compensateDistorsion) {
  9993. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  9994. }
  9995. camB._vrMetrics = camA._vrMetrics;
  9996. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9997. camB._vrWorkMatrix = new BABYLON.Matrix();
  9998. camB._vrHMatrix = metrics.rightHMatrix;
  9999. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  10000. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  10001. if (metrics.compensateDistorsion) {
  10002. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  10003. }
  10004. }
  10005. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  10006. this.subCameras.push(camA);
  10007. this.subCameras.push(camB);
  10008. }
  10009. this._update();
  10010. };
  10011. Camera.prototype._getVRProjectionMatrix = function () {
  10012. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10013. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10014. return this._projectionMatrix;
  10015. };
  10016. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10017. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10018. };
  10019. /**
  10020. * May needs to be overridden by children so sub has required properties to be copied
  10021. */
  10022. Camera.prototype.getSubCamera = function (name, isA) {
  10023. return null;
  10024. };
  10025. /**
  10026. * May needs to be overridden by children
  10027. */
  10028. Camera.prototype._updateSubCameras = function () {
  10029. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10030. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10031. camA.minZ = camB.minZ = this.minZ;
  10032. camA.maxZ = camB.maxZ = this.maxZ;
  10033. camA.fov = camB.fov = this.fov;
  10034. // only update viewport, when ANAGLYPH
  10035. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10036. camA.viewport = camB.viewport = this.viewport;
  10037. }
  10038. };
  10039. // Statics
  10040. Camera._PERSPECTIVE_CAMERA = 0;
  10041. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10042. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10043. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10044. Camera._SUB_CAMERA_MODE_NONE = 0;
  10045. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10046. Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM = 2;
  10047. Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM = 3;
  10048. Camera._SUB_CAMERA_MODE_VR = 4;
  10049. Camera._SUB_CAMERAID_A = 0;
  10050. Camera._SUB_CAMERAID_B = 1;
  10051. return Camera;
  10052. })(BABYLON.Node);
  10053. BABYLON.Camera = Camera;
  10054. })(BABYLON || (BABYLON = {}));
  10055. //# sourceMappingURL=babylon.camera.js.map
  10056. var __extends = this.__extends || function (d, b) {
  10057. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10058. function __() { this.constructor = d; }
  10059. __.prototype = b.prototype;
  10060. d.prototype = new __();
  10061. };
  10062. var BABYLON;
  10063. (function (BABYLON) {
  10064. var TargetCamera = (function (_super) {
  10065. __extends(TargetCamera, _super);
  10066. function TargetCamera(name, position, scene) {
  10067. _super.call(this, name, position, scene);
  10068. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10069. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10070. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10071. this.speed = 2.0;
  10072. this.noRotationConstraint = false;
  10073. this.lockedTarget = null;
  10074. this._currentTarget = BABYLON.Vector3.Zero();
  10075. this._viewMatrix = BABYLON.Matrix.Zero();
  10076. this._camMatrix = BABYLON.Matrix.Zero();
  10077. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10078. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10079. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10080. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10081. this._lookAtTemp = BABYLON.Matrix.Zero();
  10082. this._tempMatrix = BABYLON.Matrix.Zero();
  10083. }
  10084. TargetCamera.prototype._getLockedTargetPosition = function () {
  10085. if (!this.lockedTarget) {
  10086. return null;
  10087. }
  10088. return this.lockedTarget.position || this.lockedTarget;
  10089. };
  10090. // Cache
  10091. TargetCamera.prototype._initCache = function () {
  10092. _super.prototype._initCache.call(this);
  10093. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10094. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10095. };
  10096. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10097. if (!ignoreParentClass) {
  10098. _super.prototype._updateCache.call(this);
  10099. }
  10100. var lockedTargetPosition = this._getLockedTargetPosition();
  10101. if (!lockedTargetPosition) {
  10102. this._cache.lockedTarget = null;
  10103. }
  10104. else {
  10105. if (!this._cache.lockedTarget) {
  10106. this._cache.lockedTarget = lockedTargetPosition.clone();
  10107. }
  10108. else {
  10109. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10110. }
  10111. }
  10112. this._cache.rotation.copyFrom(this.rotation);
  10113. };
  10114. // Synchronized
  10115. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10116. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10117. return false;
  10118. }
  10119. var lockedTargetPosition = this._getLockedTargetPosition();
  10120. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  10121. };
  10122. // Methods
  10123. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10124. var engine = this.getEngine();
  10125. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10126. };
  10127. // Target
  10128. TargetCamera.prototype.setTarget = function (target) {
  10129. this.upVector.normalize();
  10130. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10131. this._camMatrix.invert();
  10132. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10133. var vDir = target.subtract(this.position);
  10134. if (vDir.x >= 0.0) {
  10135. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10136. }
  10137. else {
  10138. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10139. }
  10140. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10141. if (isNaN(this.rotation.x)) {
  10142. this.rotation.x = 0;
  10143. }
  10144. if (isNaN(this.rotation.y)) {
  10145. this.rotation.y = 0;
  10146. }
  10147. if (isNaN(this.rotation.z)) {
  10148. this.rotation.z = 0;
  10149. }
  10150. };
  10151. TargetCamera.prototype.getTarget = function () {
  10152. return this._currentTarget;
  10153. };
  10154. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10155. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10156. };
  10157. TargetCamera.prototype._updatePosition = function () {
  10158. this.position.addInPlace(this.cameraDirection);
  10159. };
  10160. TargetCamera.prototype._checkInputs = function () {
  10161. var needToMove = this._decideIfNeedsToMove();
  10162. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10163. // Move
  10164. if (needToMove) {
  10165. this._updatePosition();
  10166. }
  10167. // Rotate
  10168. if (needToRotate) {
  10169. this.rotation.x += this.cameraRotation.x;
  10170. this.rotation.y += this.cameraRotation.y;
  10171. if (!this.noRotationConstraint) {
  10172. var limit = (Math.PI / 2) * 0.95;
  10173. if (this.rotation.x > limit)
  10174. this.rotation.x = limit;
  10175. if (this.rotation.x < -limit)
  10176. this.rotation.x = -limit;
  10177. }
  10178. }
  10179. // Inertia
  10180. if (needToMove) {
  10181. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10182. this.cameraDirection.x = 0;
  10183. }
  10184. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10185. this.cameraDirection.y = 0;
  10186. }
  10187. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10188. this.cameraDirection.z = 0;
  10189. }
  10190. this.cameraDirection.scaleInPlace(this.inertia);
  10191. }
  10192. if (needToRotate) {
  10193. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10194. this.cameraRotation.x = 0;
  10195. }
  10196. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10197. this.cameraRotation.y = 0;
  10198. }
  10199. this.cameraRotation.scaleInPlace(this.inertia);
  10200. }
  10201. _super.prototype._checkInputs.call(this);
  10202. };
  10203. TargetCamera.prototype._getViewMatrix = function () {
  10204. if (!this.lockedTarget) {
  10205. // Compute
  10206. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10207. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10208. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10209. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10210. this._lookAtTemp.invert();
  10211. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10212. }
  10213. else {
  10214. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10215. }
  10216. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10217. // Computing target and final matrix
  10218. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10219. }
  10220. else {
  10221. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10222. }
  10223. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10224. return this._viewMatrix;
  10225. };
  10226. TargetCamera.prototype._getVRViewMatrix = function () {
  10227. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10228. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10229. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10230. // Computing target and final matrix
  10231. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10232. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10233. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10234. return this._viewMatrix;
  10235. };
  10236. /**
  10237. * @override
  10238. * needs to be overridden, so sub has required properties to be copied
  10239. */
  10240. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10241. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10242. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10243. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10244. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10245. }
  10246. return subCamera;
  10247. };
  10248. /**
  10249. * @override
  10250. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10251. */
  10252. TargetCamera.prototype._updateSubCameras = function () {
  10253. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10254. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10255. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10256. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10257. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10258. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10259. camA.position.copyFrom(this.position);
  10260. camB.position.copyFrom(this.position);
  10261. }
  10262. else {
  10263. camA.setTarget(this.getTarget());
  10264. camB.setTarget(this.getTarget());
  10265. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10266. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10267. }
  10268. _super.prototype._updateSubCameras.call(this);
  10269. };
  10270. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10271. if (!this._subCamTransformMatrix) {
  10272. this._subCamTransformMatrix = new BABYLON.Matrix();
  10273. }
  10274. var target = this.getTarget();
  10275. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10276. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10277. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10278. };
  10279. return TargetCamera;
  10280. })(BABYLON.Camera);
  10281. BABYLON.TargetCamera = TargetCamera;
  10282. })(BABYLON || (BABYLON = {}));
  10283. //# sourceMappingURL=babylon.targetCamera.js.map
  10284. var __extends = this.__extends || function (d, b) {
  10285. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10286. function __() { this.constructor = d; }
  10287. __.prototype = b.prototype;
  10288. d.prototype = new __();
  10289. };
  10290. var BABYLON;
  10291. (function (BABYLON) {
  10292. var FreeCamera = (function (_super) {
  10293. __extends(FreeCamera, _super);
  10294. function FreeCamera(name, position, scene) {
  10295. var _this = this;
  10296. _super.call(this, name, position, scene);
  10297. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10298. this.keysUp = [38];
  10299. this.keysDown = [40];
  10300. this.keysLeft = [37];
  10301. this.keysRight = [39];
  10302. this.checkCollisions = false;
  10303. this.applyGravity = false;
  10304. this.angularSensibility = 2000.0;
  10305. this._keys = [];
  10306. this._collider = new BABYLON.Collider();
  10307. this._needMoveForGravity = false;
  10308. this._oldPosition = BABYLON.Vector3.Zero();
  10309. this._diffPosition = BABYLON.Vector3.Zero();
  10310. this._newPosition = BABYLON.Vector3.Zero();
  10311. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10312. if (collidedMesh === void 0) { collidedMesh = null; }
  10313. //TODO move this to the collision coordinator!
  10314. if (_this.getScene().workerCollisions)
  10315. newPosition.multiplyInPlace(_this._collider.radius);
  10316. var updatePosition = function (newPos) {
  10317. _this._newPosition.copyFrom(newPos);
  10318. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10319. var oldPosition = _this.position.clone();
  10320. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10321. _this.position.addInPlace(_this._diffPosition);
  10322. if (_this.onCollide && collidedMesh) {
  10323. _this.onCollide(collidedMesh);
  10324. }
  10325. }
  10326. };
  10327. updatePosition(newPosition);
  10328. };
  10329. }
  10330. // Controls
  10331. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10332. var _this = this;
  10333. var previousPosition;
  10334. var engine = this.getEngine();
  10335. if (this._attachedElement) {
  10336. return;
  10337. }
  10338. this._attachedElement = element;
  10339. if (this._onMouseDown === undefined) {
  10340. this._onMouseDown = function (evt) {
  10341. previousPosition = {
  10342. x: evt.clientX,
  10343. y: evt.clientY
  10344. };
  10345. if (!noPreventDefault) {
  10346. evt.preventDefault();
  10347. }
  10348. };
  10349. this._onMouseUp = function (evt) {
  10350. previousPosition = null;
  10351. if (!noPreventDefault) {
  10352. evt.preventDefault();
  10353. }
  10354. };
  10355. this._onMouseOut = function (evt) {
  10356. previousPosition = null;
  10357. _this._keys = [];
  10358. if (!noPreventDefault) {
  10359. evt.preventDefault();
  10360. }
  10361. };
  10362. this._onMouseMove = function (evt) {
  10363. if (!previousPosition && !engine.isPointerLock) {
  10364. return;
  10365. }
  10366. var offsetX;
  10367. var offsetY;
  10368. if (!engine.isPointerLock) {
  10369. offsetX = evt.clientX - previousPosition.x;
  10370. offsetY = evt.clientY - previousPosition.y;
  10371. }
  10372. else {
  10373. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10374. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10375. }
  10376. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10377. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10378. previousPosition = {
  10379. x: evt.clientX,
  10380. y: evt.clientY
  10381. };
  10382. if (!noPreventDefault) {
  10383. evt.preventDefault();
  10384. }
  10385. };
  10386. this._onKeyDown = function (evt) {
  10387. 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) {
  10388. var index = _this._keys.indexOf(evt.keyCode);
  10389. if (index === -1) {
  10390. _this._keys.push(evt.keyCode);
  10391. }
  10392. if (!noPreventDefault) {
  10393. evt.preventDefault();
  10394. }
  10395. }
  10396. };
  10397. this._onKeyUp = function (evt) {
  10398. 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) {
  10399. var index = _this._keys.indexOf(evt.keyCode);
  10400. if (index >= 0) {
  10401. _this._keys.splice(index, 1);
  10402. }
  10403. if (!noPreventDefault) {
  10404. evt.preventDefault();
  10405. }
  10406. }
  10407. };
  10408. this._onLostFocus = function () {
  10409. _this._keys = [];
  10410. };
  10411. this._reset = function () {
  10412. _this._keys = [];
  10413. previousPosition = null;
  10414. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10415. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10416. };
  10417. }
  10418. element.addEventListener("mousedown", this._onMouseDown, false);
  10419. element.addEventListener("mouseup", this._onMouseUp, false);
  10420. element.addEventListener("mouseout", this._onMouseOut, false);
  10421. element.addEventListener("mousemove", this._onMouseMove, false);
  10422. BABYLON.Tools.RegisterTopRootEvents([
  10423. { name: "keydown", handler: this._onKeyDown },
  10424. { name: "keyup", handler: this._onKeyUp },
  10425. { name: "blur", handler: this._onLostFocus }
  10426. ]);
  10427. };
  10428. FreeCamera.prototype.detachControl = function (element) {
  10429. if (this._attachedElement != element) {
  10430. return;
  10431. }
  10432. element.removeEventListener("mousedown", this._onMouseDown);
  10433. element.removeEventListener("mouseup", this._onMouseUp);
  10434. element.removeEventListener("mouseout", this._onMouseOut);
  10435. element.removeEventListener("mousemove", this._onMouseMove);
  10436. BABYLON.Tools.UnregisterTopRootEvents([
  10437. { name: "keydown", handler: this._onKeyDown },
  10438. { name: "keyup", handler: this._onKeyUp },
  10439. { name: "blur", handler: this._onLostFocus }
  10440. ]);
  10441. this._attachedElement = null;
  10442. if (this._reset) {
  10443. this._reset();
  10444. }
  10445. };
  10446. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10447. var globalPosition;
  10448. if (this.parent) {
  10449. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10450. }
  10451. else {
  10452. globalPosition = this.position;
  10453. }
  10454. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10455. this._collider.radius = this.ellipsoid;
  10456. //add gravity to the velocity to prevent the dual-collision checking
  10457. if (this.applyGravity) {
  10458. velocity.addInPlace(this.getScene().gravity);
  10459. }
  10460. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10461. };
  10462. FreeCamera.prototype._checkInputs = function () {
  10463. if (!this._localDirection) {
  10464. this._localDirection = BABYLON.Vector3.Zero();
  10465. this._transformedDirection = BABYLON.Vector3.Zero();
  10466. }
  10467. for (var index = 0; index < this._keys.length; index++) {
  10468. var keyCode = this._keys[index];
  10469. var speed = this._computeLocalCameraSpeed();
  10470. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10471. this._localDirection.copyFromFloats(-speed, 0, 0);
  10472. }
  10473. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10474. this._localDirection.copyFromFloats(0, 0, speed);
  10475. }
  10476. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10477. this._localDirection.copyFromFloats(speed, 0, 0);
  10478. }
  10479. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10480. this._localDirection.copyFromFloats(0, 0, -speed);
  10481. }
  10482. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10483. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10484. this.cameraDirection.addInPlace(this._transformedDirection);
  10485. }
  10486. _super.prototype._checkInputs.call(this);
  10487. };
  10488. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10489. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10490. };
  10491. FreeCamera.prototype._updatePosition = function () {
  10492. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10493. this._collideWithWorld(this.cameraDirection);
  10494. }
  10495. else {
  10496. this.position.addInPlace(this.cameraDirection);
  10497. }
  10498. };
  10499. return FreeCamera;
  10500. })(BABYLON.TargetCamera);
  10501. BABYLON.FreeCamera = FreeCamera;
  10502. })(BABYLON || (BABYLON = {}));
  10503. //# sourceMappingURL=babylon.freeCamera.js.map
  10504. var __extends = this.__extends || function (d, b) {
  10505. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10506. function __() { this.constructor = d; }
  10507. __.prototype = b.prototype;
  10508. d.prototype = new __();
  10509. };
  10510. var BABYLON;
  10511. (function (BABYLON) {
  10512. var FollowCamera = (function (_super) {
  10513. __extends(FollowCamera, _super);
  10514. function FollowCamera(name, position, scene) {
  10515. _super.call(this, name, position, scene);
  10516. this.radius = 12;
  10517. this.rotationOffset = 0;
  10518. this.heightOffset = 4;
  10519. this.cameraAcceleration = 0.05;
  10520. this.maxCameraSpeed = 20;
  10521. }
  10522. FollowCamera.prototype.getRadians = function (degrees) {
  10523. return degrees * Math.PI / 180;
  10524. };
  10525. FollowCamera.prototype.follow = function (cameraTarget) {
  10526. if (!cameraTarget)
  10527. return;
  10528. var yRotation;
  10529. if (cameraTarget.rotationQuaternion) {
  10530. var rotMatrix = new BABYLON.Matrix();
  10531. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10532. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10533. }
  10534. else {
  10535. yRotation = cameraTarget.rotation.y;
  10536. }
  10537. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10538. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10539. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10540. var dx = targetX - this.position.x;
  10541. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10542. var dz = (targetZ) - this.position.z;
  10543. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10544. var vy = dy * this.cameraAcceleration;
  10545. var vz = dz * this.cameraAcceleration * 2;
  10546. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10547. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10548. }
  10549. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10550. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10551. }
  10552. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10553. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10554. }
  10555. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10556. this.setTarget(cameraTarget.position);
  10557. };
  10558. FollowCamera.prototype._checkInputs = function () {
  10559. _super.prototype._checkInputs.call(this);
  10560. this.follow(this.target);
  10561. };
  10562. return FollowCamera;
  10563. })(BABYLON.TargetCamera);
  10564. BABYLON.FollowCamera = FollowCamera;
  10565. })(BABYLON || (BABYLON = {}));
  10566. //# sourceMappingURL=babylon.followCamera.js.map
  10567. var __extends = this.__extends || function (d, b) {
  10568. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10569. function __() { this.constructor = d; }
  10570. __.prototype = b.prototype;
  10571. d.prototype = new __();
  10572. };
  10573. var BABYLON;
  10574. (function (BABYLON) {
  10575. // We're mainly based on the logic defined into the FreeCamera code
  10576. var TouchCamera = (function (_super) {
  10577. __extends(TouchCamera, _super);
  10578. function TouchCamera(name, position, scene) {
  10579. _super.call(this, name, position, scene);
  10580. this._offsetX = null;
  10581. this._offsetY = null;
  10582. this._pointerCount = 0;
  10583. this._pointerPressed = [];
  10584. this.angularSensibility = 200000.0;
  10585. this.moveSensibility = 500.0;
  10586. }
  10587. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10588. var _this = this;
  10589. var previousPosition;
  10590. if (this._attachedCanvas) {
  10591. return;
  10592. }
  10593. this._attachedCanvas = canvas;
  10594. if (this._onPointerDown === undefined) {
  10595. this._onPointerDown = function (evt) {
  10596. if (!noPreventDefault) {
  10597. evt.preventDefault();
  10598. }
  10599. _this._pointerPressed.push(evt.pointerId);
  10600. if (_this._pointerPressed.length !== 1) {
  10601. return;
  10602. }
  10603. previousPosition = {
  10604. x: evt.clientX,
  10605. y: evt.clientY
  10606. };
  10607. };
  10608. this._onPointerUp = function (evt) {
  10609. if (!noPreventDefault) {
  10610. evt.preventDefault();
  10611. }
  10612. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10613. if (index === -1) {
  10614. return;
  10615. }
  10616. _this._pointerPressed.splice(index, 1);
  10617. if (index != 0) {
  10618. return;
  10619. }
  10620. previousPosition = null;
  10621. _this._offsetX = null;
  10622. _this._offsetY = null;
  10623. };
  10624. this._onPointerMove = function (evt) {
  10625. if (!noPreventDefault) {
  10626. evt.preventDefault();
  10627. }
  10628. if (!previousPosition) {
  10629. return;
  10630. }
  10631. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10632. if (index != 0) {
  10633. return;
  10634. }
  10635. _this._offsetX = evt.clientX - previousPosition.x;
  10636. _this._offsetY = -(evt.clientY - previousPosition.y);
  10637. };
  10638. this._onLostFocus = function () {
  10639. _this._offsetX = null;
  10640. _this._offsetY = null;
  10641. };
  10642. }
  10643. canvas.addEventListener("pointerdown", this._onPointerDown);
  10644. canvas.addEventListener("pointerup", this._onPointerUp);
  10645. canvas.addEventListener("pointerout", this._onPointerUp);
  10646. canvas.addEventListener("pointermove", this._onPointerMove);
  10647. BABYLON.Tools.RegisterTopRootEvents([
  10648. { name: "blur", handler: this._onLostFocus }
  10649. ]);
  10650. };
  10651. TouchCamera.prototype.detachControl = function (canvas) {
  10652. if (this._attachedCanvas != canvas) {
  10653. return;
  10654. }
  10655. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10656. canvas.removeEventListener("pointerup", this._onPointerUp);
  10657. canvas.removeEventListener("pointerout", this._onPointerUp);
  10658. canvas.removeEventListener("pointermove", this._onPointerMove);
  10659. BABYLON.Tools.UnregisterTopRootEvents([
  10660. { name: "blur", handler: this._onLostFocus }
  10661. ]);
  10662. this._attachedCanvas = null;
  10663. };
  10664. TouchCamera.prototype._checkInputs = function () {
  10665. if (!this._offsetX) {
  10666. return;
  10667. }
  10668. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10669. if (this._pointerPressed.length > 1) {
  10670. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10671. }
  10672. else {
  10673. var speed = this._computeLocalCameraSpeed();
  10674. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10675. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10676. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10677. }
  10678. _super.prototype._checkInputs.call(this);
  10679. };
  10680. return TouchCamera;
  10681. })(BABYLON.FreeCamera);
  10682. BABYLON.TouchCamera = TouchCamera;
  10683. })(BABYLON || (BABYLON = {}));
  10684. //# sourceMappingURL=babylon.touchCamera.js.map
  10685. var __extends = this.__extends || function (d, b) {
  10686. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10687. function __() { this.constructor = d; }
  10688. __.prototype = b.prototype;
  10689. d.prototype = new __();
  10690. };
  10691. var BABYLON;
  10692. (function (BABYLON) {
  10693. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10694. var ArcRotateCamera = (function (_super) {
  10695. __extends(ArcRotateCamera, _super);
  10696. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10697. var _this = this;
  10698. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10699. this.alpha = alpha;
  10700. this.beta = beta;
  10701. this.radius = radius;
  10702. this.target = target;
  10703. this.inertialAlphaOffset = 0;
  10704. this.inertialBetaOffset = 0;
  10705. this.inertialRadiusOffset = 0;
  10706. this.lowerAlphaLimit = null;
  10707. this.upperAlphaLimit = null;
  10708. this.lowerBetaLimit = 0.01;
  10709. this.upperBetaLimit = Math.PI;
  10710. this.lowerRadiusLimit = null;
  10711. this.upperRadiusLimit = null;
  10712. this.angularSensibility = 1000.0;
  10713. this.wheelPrecision = 3.0;
  10714. this.pinchPrecision = 2.0;
  10715. this.keysUp = [38];
  10716. this.keysDown = [40];
  10717. this.keysLeft = [37];
  10718. this.keysRight = [39];
  10719. this.zoomOnFactor = 1;
  10720. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10721. this.pinchInwards = true;
  10722. this._keys = [];
  10723. this._viewMatrix = new BABYLON.Matrix();
  10724. this.checkCollisions = false;
  10725. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10726. this._collider = new BABYLON.Collider();
  10727. this._previousPosition = BABYLON.Vector3.Zero();
  10728. this._collisionVelocity = BABYLON.Vector3.Zero();
  10729. this._newPosition = BABYLON.Vector3.Zero();
  10730. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10731. if (collidedMesh === void 0) { collidedMesh = null; }
  10732. if (collisionId != null || collisionId != undefined)
  10733. newPosition.multiplyInPlace(_this._collider.radius);
  10734. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10735. _this.position.copyFrom(_this._previousPosition);
  10736. _this.alpha = _this._previousAlpha;
  10737. _this.beta = _this._previousBeta;
  10738. _this.radius = _this._previousRadius;
  10739. if (_this.onCollide && collidedMesh) {
  10740. _this.onCollide(collidedMesh);
  10741. }
  10742. }
  10743. _this._collisionTriggered = false;
  10744. };
  10745. if (!this.target) {
  10746. this.target = BABYLON.Vector3.Zero();
  10747. }
  10748. this.getViewMatrix();
  10749. }
  10750. ArcRotateCamera.prototype._getTargetPosition = function () {
  10751. return this.target.position || this.target;
  10752. };
  10753. // Cache
  10754. ArcRotateCamera.prototype._initCache = function () {
  10755. _super.prototype._initCache.call(this);
  10756. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10757. this._cache.alpha = undefined;
  10758. this._cache.beta = undefined;
  10759. this._cache.radius = undefined;
  10760. this._cache.targetScreenOffset = undefined;
  10761. };
  10762. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10763. if (!ignoreParentClass) {
  10764. _super.prototype._updateCache.call(this);
  10765. }
  10766. this._cache.target.copyFrom(this._getTargetPosition());
  10767. this._cache.alpha = this.alpha;
  10768. this._cache.beta = this.beta;
  10769. this._cache.radius = this.radius;
  10770. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10771. };
  10772. // Synchronized
  10773. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10774. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10775. return false;
  10776. 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);
  10777. };
  10778. // Methods
  10779. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10780. var _this = this;
  10781. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10782. var previousPinchDistance = 0;
  10783. var pointers = new BABYLON.SmartCollection();
  10784. if (this._attachedElement) {
  10785. return;
  10786. }
  10787. this._attachedElement = element;
  10788. var engine = this.getEngine();
  10789. if (this._onPointerDown === undefined) {
  10790. this._onPointerDown = function (evt) {
  10791. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10792. cacheSoloPointer = pointers.item(evt.pointerId);
  10793. if (!noPreventDefault) {
  10794. evt.preventDefault();
  10795. }
  10796. };
  10797. this._onPointerUp = function (evt) {
  10798. cacheSoloPointer = null;
  10799. previousPinchDistance = 0;
  10800. pointers.remove(evt.pointerId);
  10801. if (!noPreventDefault) {
  10802. evt.preventDefault();
  10803. }
  10804. };
  10805. this._onPointerMove = function (evt) {
  10806. if (!noPreventDefault) {
  10807. evt.preventDefault();
  10808. }
  10809. switch (pointers.count) {
  10810. case 1:
  10811. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10812. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10813. var offsetX = evt.clientX - cacheSoloPointer.x;
  10814. var offsetY = evt.clientY - cacheSoloPointer.y;
  10815. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10816. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10817. //pointers.item(evt.pointerId).x = evt.clientX;
  10818. //pointers.item(evt.pointerId).y = evt.clientY;
  10819. cacheSoloPointer.x = evt.clientX;
  10820. cacheSoloPointer.y = evt.clientY;
  10821. break;
  10822. case 2:
  10823. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10824. pointers.item(evt.pointerId).x = evt.clientX;
  10825. pointers.item(evt.pointerId).y = evt.clientY;
  10826. var direction = _this.pinchInwards ? 1 : -1;
  10827. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10828. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10829. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10830. if (previousPinchDistance === 0) {
  10831. previousPinchDistance = pinchSquaredDistance;
  10832. return;
  10833. }
  10834. if (pinchSquaredDistance !== previousPinchDistance) {
  10835. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10836. previousPinchDistance = pinchSquaredDistance;
  10837. }
  10838. break;
  10839. default:
  10840. if (pointers.item(evt.pointerId)) {
  10841. pointers.item(evt.pointerId).x = evt.clientX;
  10842. pointers.item(evt.pointerId).y = evt.clientY;
  10843. }
  10844. }
  10845. };
  10846. this._onMouseMove = function (evt) {
  10847. if (!engine.isPointerLock) {
  10848. return;
  10849. }
  10850. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10851. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10852. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10853. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10854. if (!noPreventDefault) {
  10855. evt.preventDefault();
  10856. }
  10857. };
  10858. this._wheel = function (event) {
  10859. var delta = 0;
  10860. if (event.wheelDelta) {
  10861. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10862. }
  10863. else if (event.detail) {
  10864. delta = -event.detail / _this.wheelPrecision;
  10865. }
  10866. if (delta)
  10867. _this.inertialRadiusOffset += delta;
  10868. if (event.preventDefault) {
  10869. if (!noPreventDefault) {
  10870. event.preventDefault();
  10871. }
  10872. }
  10873. };
  10874. this._onKeyDown = function (evt) {
  10875. 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) {
  10876. var index = _this._keys.indexOf(evt.keyCode);
  10877. if (index === -1) {
  10878. _this._keys.push(evt.keyCode);
  10879. }
  10880. if (evt.preventDefault) {
  10881. if (!noPreventDefault) {
  10882. evt.preventDefault();
  10883. }
  10884. }
  10885. }
  10886. };
  10887. this._onKeyUp = function (evt) {
  10888. 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) {
  10889. var index = _this._keys.indexOf(evt.keyCode);
  10890. if (index >= 0) {
  10891. _this._keys.splice(index, 1);
  10892. }
  10893. if (evt.preventDefault) {
  10894. if (!noPreventDefault) {
  10895. evt.preventDefault();
  10896. }
  10897. }
  10898. }
  10899. };
  10900. this._onLostFocus = function () {
  10901. _this._keys = [];
  10902. pointers.empty();
  10903. previousPinchDistance = 0;
  10904. cacheSoloPointer = null;
  10905. };
  10906. this._onGestureStart = function (e) {
  10907. if (window.MSGesture === undefined) {
  10908. return;
  10909. }
  10910. if (!_this._MSGestureHandler) {
  10911. _this._MSGestureHandler = new MSGesture();
  10912. _this._MSGestureHandler.target = element;
  10913. }
  10914. _this._MSGestureHandler.addPointer(e.pointerId);
  10915. };
  10916. this._onGesture = function (e) {
  10917. _this.radius *= e.scale;
  10918. if (e.preventDefault) {
  10919. if (!noPreventDefault) {
  10920. e.stopPropagation();
  10921. e.preventDefault();
  10922. }
  10923. }
  10924. };
  10925. this._reset = function () {
  10926. _this._keys = [];
  10927. _this.inertialAlphaOffset = 0;
  10928. _this.inertialBetaOffset = 0;
  10929. _this.inertialRadiusOffset = 0;
  10930. pointers.empty();
  10931. previousPinchDistance = 0;
  10932. cacheSoloPointer = null;
  10933. };
  10934. }
  10935. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10936. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10937. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10938. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10939. element.addEventListener("mousemove", this._onMouseMove, false);
  10940. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10941. element.addEventListener("MSGestureChange", this._onGesture, false);
  10942. element.addEventListener('mousewheel', this._wheel, false);
  10943. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10944. BABYLON.Tools.RegisterTopRootEvents([
  10945. { name: "keydown", handler: this._onKeyDown },
  10946. { name: "keyup", handler: this._onKeyUp },
  10947. { name: "blur", handler: this._onLostFocus }
  10948. ]);
  10949. };
  10950. ArcRotateCamera.prototype.detachControl = function (element) {
  10951. if (this._attachedElement !== element) {
  10952. return;
  10953. }
  10954. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10955. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10956. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10957. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10958. element.removeEventListener("mousemove", this._onMouseMove);
  10959. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10960. element.removeEventListener("MSGestureChange", this._onGesture);
  10961. element.removeEventListener('mousewheel', this._wheel);
  10962. element.removeEventListener('DOMMouseScroll', this._wheel);
  10963. BABYLON.Tools.UnregisterTopRootEvents([
  10964. { name: "keydown", handler: this._onKeyDown },
  10965. { name: "keyup", handler: this._onKeyUp },
  10966. { name: "blur", handler: this._onLostFocus }
  10967. ]);
  10968. this._MSGestureHandler = null;
  10969. this._attachedElement = null;
  10970. if (this._reset) {
  10971. this._reset();
  10972. }
  10973. };
  10974. ArcRotateCamera.prototype._checkInputs = function () {
  10975. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10976. if (this._collisionTriggered) {
  10977. return;
  10978. }
  10979. for (var index = 0; index < this._keys.length; index++) {
  10980. var keyCode = this._keys[index];
  10981. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10982. this.inertialAlphaOffset -= 0.01;
  10983. }
  10984. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10985. this.inertialBetaOffset -= 0.01;
  10986. }
  10987. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10988. this.inertialAlphaOffset += 0.01;
  10989. }
  10990. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10991. this.inertialBetaOffset += 0.01;
  10992. }
  10993. }
  10994. // Inertia
  10995. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10996. this.alpha += this.inertialAlphaOffset;
  10997. this.beta += this.inertialBetaOffset;
  10998. this.radius -= this.inertialRadiusOffset;
  10999. this.inertialAlphaOffset *= this.inertia;
  11000. this.inertialBetaOffset *= this.inertia;
  11001. this.inertialRadiusOffset *= this.inertia;
  11002. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11003. this.inertialAlphaOffset = 0;
  11004. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11005. this.inertialBetaOffset = 0;
  11006. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11007. this.inertialRadiusOffset = 0;
  11008. }
  11009. // Limits
  11010. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11011. this.alpha = this.lowerAlphaLimit;
  11012. }
  11013. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11014. this.alpha = this.upperAlphaLimit;
  11015. }
  11016. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  11017. this.beta = this.lowerBetaLimit;
  11018. }
  11019. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  11020. this.beta = this.upperBetaLimit;
  11021. }
  11022. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11023. this.radius = this.lowerRadiusLimit;
  11024. }
  11025. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11026. this.radius = this.upperRadiusLimit;
  11027. }
  11028. _super.prototype._checkInputs.call(this);
  11029. };
  11030. ArcRotateCamera.prototype.setPosition = function (position) {
  11031. var radiusv3 = position.subtract(this._getTargetPosition());
  11032. this.radius = radiusv3.length();
  11033. // Alpha
  11034. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11035. if (radiusv3.z < 0) {
  11036. this.alpha = 2 * Math.PI - this.alpha;
  11037. }
  11038. // Beta
  11039. this.beta = Math.acos(radiusv3.y / this.radius);
  11040. };
  11041. ArcRotateCamera.prototype._getViewMatrix = function () {
  11042. // Compute
  11043. var cosa = Math.cos(this.alpha);
  11044. var sina = Math.sin(this.alpha);
  11045. var cosb = Math.cos(this.beta);
  11046. var sinb = Math.sin(this.beta);
  11047. var target = this._getTargetPosition();
  11048. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11049. if (this.checkCollisions) {
  11050. this._collider.radius = this.collisionRadius;
  11051. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11052. this._collisionTriggered = true;
  11053. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11054. }
  11055. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  11056. this._previousAlpha = this.alpha;
  11057. this._previousBeta = this.beta;
  11058. this._previousRadius = this.radius;
  11059. this._previousPosition.copyFrom(this.position);
  11060. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11061. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11062. return this._viewMatrix;
  11063. };
  11064. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11065. meshes = meshes || this.getScene().meshes;
  11066. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11067. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11068. this.radius = distance * this.zoomOnFactor;
  11069. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11070. };
  11071. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11072. var meshesOrMinMaxVector;
  11073. var distance;
  11074. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11075. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11076. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11077. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11078. }
  11079. else {
  11080. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11081. distance = meshesOrMinMaxVectorAndDistance.distance;
  11082. }
  11083. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11084. this.maxZ = distance * 2;
  11085. };
  11086. /**
  11087. * @override
  11088. * needs to be overridden, so sub has required properties to be copied
  11089. */
  11090. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11091. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11092. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11093. };
  11094. /**
  11095. * @override
  11096. * needs to be overridden, adding copy of alpha, beta & radius
  11097. */
  11098. ArcRotateCamera.prototype._updateSubCameras = function () {
  11099. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11100. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11101. camA.alpha = this.alpha - this._subCamHalfSpace;
  11102. camB.alpha = this.alpha + this._subCamHalfSpace;
  11103. camA.beta = camB.beta = this.beta;
  11104. camA.radius = camB.radius = this.radius;
  11105. _super.prototype._updateSubCameras.call(this);
  11106. };
  11107. return ArcRotateCamera;
  11108. })(BABYLON.Camera);
  11109. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11110. })(BABYLON || (BABYLON = {}));
  11111. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11112. var __extends = this.__extends || function (d, b) {
  11113. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11114. function __() { this.constructor = d; }
  11115. __.prototype = b.prototype;
  11116. d.prototype = new __();
  11117. };
  11118. var BABYLON;
  11119. (function (BABYLON) {
  11120. // We're mainly based on the logic defined into the FreeCamera code
  11121. var DeviceOrientationCamera = (function (_super) {
  11122. __extends(DeviceOrientationCamera, _super);
  11123. function DeviceOrientationCamera(name, position, scene) {
  11124. var _this = this;
  11125. _super.call(this, name, position, scene);
  11126. this._offsetX = null;
  11127. this._offsetY = null;
  11128. this._orientationGamma = 0;
  11129. this._orientationBeta = 0;
  11130. this._initialOrientationGamma = 0;
  11131. this._initialOrientationBeta = 0;
  11132. this.angularSensibility = 10000.0;
  11133. this.moveSensibility = 50.0;
  11134. window.addEventListener("resize", function () {
  11135. _this._initialOrientationGamma = null;
  11136. }, false);
  11137. }
  11138. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11139. var _this = this;
  11140. if (this._attachedCanvas) {
  11141. return;
  11142. }
  11143. this._attachedCanvas = canvas;
  11144. if (!this._orientationChanged) {
  11145. this._orientationChanged = function (evt) {
  11146. if (!_this._initialOrientationGamma) {
  11147. _this._initialOrientationGamma = evt.gamma;
  11148. _this._initialOrientationBeta = evt.beta;
  11149. }
  11150. _this._orientationGamma = evt.gamma;
  11151. _this._orientationBeta = evt.beta;
  11152. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11153. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11154. };
  11155. }
  11156. window.addEventListener("deviceorientation", this._orientationChanged);
  11157. };
  11158. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11159. if (this._attachedCanvas != canvas) {
  11160. return;
  11161. }
  11162. window.removeEventListener("deviceorientation", this._orientationChanged);
  11163. this._attachedCanvas = null;
  11164. this._orientationGamma = 0;
  11165. this._orientationBeta = 0;
  11166. this._initialOrientationGamma = 0;
  11167. this._initialOrientationBeta = 0;
  11168. };
  11169. DeviceOrientationCamera.prototype._checkInputs = function () {
  11170. if (!this._offsetX) {
  11171. return;
  11172. }
  11173. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11174. var speed = this._computeLocalCameraSpeed();
  11175. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11176. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11177. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11178. _super.prototype._checkInputs.call(this);
  11179. };
  11180. return DeviceOrientationCamera;
  11181. })(BABYLON.FreeCamera);
  11182. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11183. })(BABYLON || (BABYLON = {}));
  11184. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11185. var __extends = this.__extends || function (d, b) {
  11186. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11187. function __() { this.constructor = d; }
  11188. __.prototype = b.prototype;
  11189. d.prototype = new __();
  11190. };
  11191. var BABYLON;
  11192. (function (BABYLON) {
  11193. var Gamepads = (function () {
  11194. function Gamepads(ongamedpadconnected) {
  11195. var _this = this;
  11196. this.babylonGamepads = [];
  11197. this.oneGamepadConnected = false;
  11198. this.isMonitoring = false;
  11199. this.gamepadEventSupported = 'GamepadEvent' in window;
  11200. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11201. 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=";
  11202. this._callbackGamepadConnected = ongamedpadconnected;
  11203. if (this.gamepadSupportAvailable) {
  11204. // Checking if the gamepad connected event is supported (like in Firefox)
  11205. if (this.gamepadEventSupported) {
  11206. window.addEventListener('gamepadconnected', function (evt) {
  11207. _this._onGamepadConnected(evt);
  11208. }, false);
  11209. window.addEventListener('gamepaddisconnected', function (evt) {
  11210. _this._onGamepadDisconnected(evt);
  11211. }, false);
  11212. }
  11213. else {
  11214. this._startMonitoringGamepads();
  11215. }
  11216. if (!this.oneGamepadConnected) {
  11217. this._insertGamepadDOMInstructions();
  11218. }
  11219. }
  11220. else {
  11221. this._insertGamepadDOMNotSupported();
  11222. }
  11223. }
  11224. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11225. Gamepads.gamepadDOMInfo = document.createElement("div");
  11226. var buttonAImage = document.createElement("img");
  11227. buttonAImage.src = this.buttonADataURL;
  11228. var spanMessage = document.createElement("span");
  11229. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11230. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11231. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11232. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11233. Gamepads.gamepadDOMInfo.style.width = "100%";
  11234. Gamepads.gamepadDOMInfo.style.height = "48px";
  11235. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11236. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11237. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11238. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11239. buttonAImage.style.position = "relative";
  11240. buttonAImage.style.bottom = "8px";
  11241. spanMessage.style.position = "relative";
  11242. spanMessage.style.fontSize = "32px";
  11243. spanMessage.style.bottom = "32px";
  11244. spanMessage.style.color = "green";
  11245. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11246. };
  11247. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11248. Gamepads.gamepadDOMInfo = document.createElement("div");
  11249. var spanMessage = document.createElement("span");
  11250. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11251. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11252. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11253. Gamepads.gamepadDOMInfo.style.width = "100%";
  11254. Gamepads.gamepadDOMInfo.style.height = "40px";
  11255. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11256. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11257. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11258. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11259. spanMessage.style.position = "relative";
  11260. spanMessage.style.fontSize = "32px";
  11261. spanMessage.style.color = "red";
  11262. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11263. };
  11264. Gamepads.prototype.dispose = function () {
  11265. if (Gamepads.gamepadDOMInfo) {
  11266. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11267. }
  11268. };
  11269. Gamepads.prototype._onGamepadConnected = function (evt) {
  11270. var newGamepad = this._addNewGamepad(evt.gamepad);
  11271. if (this._callbackGamepadConnected)
  11272. this._callbackGamepadConnected(newGamepad);
  11273. this._startMonitoringGamepads();
  11274. };
  11275. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11276. if (!this.oneGamepadConnected) {
  11277. this.oneGamepadConnected = true;
  11278. if (Gamepads.gamepadDOMInfo) {
  11279. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11280. Gamepads.gamepadDOMInfo = null;
  11281. }
  11282. }
  11283. var newGamepad;
  11284. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11285. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11286. }
  11287. else {
  11288. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11289. }
  11290. this.babylonGamepads.push(newGamepad);
  11291. return newGamepad;
  11292. };
  11293. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11294. for (var i in this.babylonGamepads) {
  11295. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11296. this.babylonGamepads.splice(i, 1);
  11297. break;
  11298. }
  11299. }
  11300. // If no gamepads are left, stop the polling loop.
  11301. if (this.babylonGamepads.length == 0) {
  11302. this._stopMonitoringGamepads();
  11303. }
  11304. };
  11305. Gamepads.prototype._startMonitoringGamepads = function () {
  11306. if (!this.isMonitoring) {
  11307. this.isMonitoring = true;
  11308. this._checkGamepadsStatus();
  11309. }
  11310. };
  11311. Gamepads.prototype._stopMonitoringGamepads = function () {
  11312. this.isMonitoring = false;
  11313. };
  11314. Gamepads.prototype._checkGamepadsStatus = function () {
  11315. var _this = this;
  11316. // updating gamepad objects
  11317. this._updateGamepadObjects();
  11318. for (var i in this.babylonGamepads) {
  11319. this.babylonGamepads[i].update();
  11320. }
  11321. if (this.isMonitoring) {
  11322. if (window.requestAnimationFrame) {
  11323. window.requestAnimationFrame(function () {
  11324. _this._checkGamepadsStatus();
  11325. });
  11326. }
  11327. else if (window.mozRequestAnimationFrame) {
  11328. window.mozRequestAnimationFrame(function () {
  11329. _this._checkGamepadsStatus();
  11330. });
  11331. }
  11332. else if (window.webkitRequestAnimationFrame) {
  11333. window.webkitRequestAnimationFrame(function () {
  11334. _this._checkGamepadsStatus();
  11335. });
  11336. }
  11337. }
  11338. };
  11339. // This function is called only on Chrome, which does not yet support
  11340. // connection/disconnection events, but requires you to monitor
  11341. // an array for changes.
  11342. Gamepads.prototype._updateGamepadObjects = function () {
  11343. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11344. for (var i = 0; i < gamepads.length; i++) {
  11345. if (gamepads[i]) {
  11346. if (!(gamepads[i].index in this.babylonGamepads)) {
  11347. var newGamepad = this._addNewGamepad(gamepads[i]);
  11348. if (this._callbackGamepadConnected) {
  11349. this._callbackGamepadConnected(newGamepad);
  11350. }
  11351. }
  11352. else {
  11353. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11354. }
  11355. }
  11356. }
  11357. };
  11358. return Gamepads;
  11359. })();
  11360. BABYLON.Gamepads = Gamepads;
  11361. var StickValues = (function () {
  11362. function StickValues(x, y) {
  11363. this.x = x;
  11364. this.y = y;
  11365. }
  11366. return StickValues;
  11367. })();
  11368. BABYLON.StickValues = StickValues;
  11369. var Gamepad = (function () {
  11370. function Gamepad(id, index, browserGamepad) {
  11371. this.id = id;
  11372. this.index = index;
  11373. this.browserGamepad = browserGamepad;
  11374. if (this.browserGamepad.axes.length >= 2) {
  11375. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11376. }
  11377. if (this.browserGamepad.axes.length >= 4) {
  11378. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11379. }
  11380. }
  11381. Gamepad.prototype.onleftstickchanged = function (callback) {
  11382. this._onleftstickchanged = callback;
  11383. };
  11384. Gamepad.prototype.onrightstickchanged = function (callback) {
  11385. this._onrightstickchanged = callback;
  11386. };
  11387. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11388. get: function () {
  11389. return this._leftStick;
  11390. },
  11391. set: function (newValues) {
  11392. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11393. this._onleftstickchanged(newValues);
  11394. }
  11395. this._leftStick = newValues;
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11401. get: function () {
  11402. return this._rightStick;
  11403. },
  11404. set: function (newValues) {
  11405. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11406. this._onrightstickchanged(newValues);
  11407. }
  11408. this._rightStick = newValues;
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Gamepad.prototype.update = function () {
  11414. if (this._leftStick) {
  11415. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11416. }
  11417. if (this._rightStick) {
  11418. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11419. }
  11420. };
  11421. return Gamepad;
  11422. })();
  11423. BABYLON.Gamepad = Gamepad;
  11424. var GenericPad = (function (_super) {
  11425. __extends(GenericPad, _super);
  11426. function GenericPad(id, index, gamepad) {
  11427. _super.call(this, id, index, gamepad);
  11428. this.id = id;
  11429. this.index = index;
  11430. this.gamepad = gamepad;
  11431. this._buttons = new Array(gamepad.buttons.length);
  11432. }
  11433. GenericPad.prototype.onbuttondown = function (callback) {
  11434. this._onbuttondown = callback;
  11435. };
  11436. GenericPad.prototype.onbuttonup = function (callback) {
  11437. this._onbuttonup = callback;
  11438. };
  11439. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11440. if (newValue !== currentValue) {
  11441. if (this._onbuttondown && newValue === 1) {
  11442. this._onbuttondown(buttonIndex);
  11443. }
  11444. if (this._onbuttonup && newValue === 0) {
  11445. this._onbuttonup(buttonIndex);
  11446. }
  11447. }
  11448. return newValue;
  11449. };
  11450. GenericPad.prototype.update = function () {
  11451. _super.prototype.update.call(this);
  11452. for (var index = 0; index < this._buttons.length; index++) {
  11453. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11454. }
  11455. };
  11456. return GenericPad;
  11457. })(Gamepad);
  11458. BABYLON.GenericPad = GenericPad;
  11459. (function (Xbox360Button) {
  11460. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11461. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11462. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11463. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11464. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11465. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11466. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11467. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11468. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11469. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11470. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11471. var Xbox360Button = BABYLON.Xbox360Button;
  11472. (function (Xbox360Dpad) {
  11473. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11474. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11475. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11476. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11477. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11478. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11479. var Xbox360Pad = (function (_super) {
  11480. __extends(Xbox360Pad, _super);
  11481. function Xbox360Pad() {
  11482. _super.apply(this, arguments);
  11483. this._leftTrigger = 0;
  11484. this._rightTrigger = 0;
  11485. this._buttonA = 0;
  11486. this._buttonB = 0;
  11487. this._buttonX = 0;
  11488. this._buttonY = 0;
  11489. this._buttonBack = 0;
  11490. this._buttonStart = 0;
  11491. this._buttonLB = 0;
  11492. this._buttonRB = 0;
  11493. this._buttonLeftStick = 0;
  11494. this._buttonRightStick = 0;
  11495. this._dPadUp = 0;
  11496. this._dPadDown = 0;
  11497. this._dPadLeft = 0;
  11498. this._dPadRight = 0;
  11499. }
  11500. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11501. this._onlefttriggerchanged = callback;
  11502. };
  11503. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11504. this._onrighttriggerchanged = callback;
  11505. };
  11506. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11507. get: function () {
  11508. return this._leftTrigger;
  11509. },
  11510. set: function (newValue) {
  11511. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11512. this._onlefttriggerchanged(newValue);
  11513. }
  11514. this._leftTrigger = newValue;
  11515. },
  11516. enumerable: true,
  11517. configurable: true
  11518. });
  11519. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11520. get: function () {
  11521. return this._rightTrigger;
  11522. },
  11523. set: function (newValue) {
  11524. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11525. this._onrighttriggerchanged(newValue);
  11526. }
  11527. this._rightTrigger = newValue;
  11528. },
  11529. enumerable: true,
  11530. configurable: true
  11531. });
  11532. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11533. this._onbuttondown = callback;
  11534. };
  11535. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11536. this._onbuttonup = callback;
  11537. };
  11538. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11539. this._ondpaddown = callback;
  11540. };
  11541. Xbox360Pad.prototype.ondpadup = function (callback) {
  11542. this._ondpadup = callback;
  11543. };
  11544. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11545. if (newValue !== currentValue) {
  11546. if (this._onbuttondown && newValue === 1) {
  11547. this._onbuttondown(buttonType);
  11548. }
  11549. if (this._onbuttonup && newValue === 0) {
  11550. this._onbuttonup(buttonType);
  11551. }
  11552. }
  11553. return newValue;
  11554. };
  11555. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11556. if (newValue !== currentValue) {
  11557. if (this._ondpaddown && newValue === 1) {
  11558. this._ondpaddown(buttonType);
  11559. }
  11560. if (this._ondpadup && newValue === 0) {
  11561. this._ondpadup(buttonType);
  11562. }
  11563. }
  11564. return newValue;
  11565. };
  11566. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11567. get: function () {
  11568. return this._buttonA;
  11569. },
  11570. set: function (value) {
  11571. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11577. get: function () {
  11578. return this._buttonB;
  11579. },
  11580. set: function (value) {
  11581. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11587. get: function () {
  11588. return this._buttonX;
  11589. },
  11590. set: function (value) {
  11591. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11597. get: function () {
  11598. return this._buttonY;
  11599. },
  11600. set: function (value) {
  11601. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11607. get: function () {
  11608. return this._buttonStart;
  11609. },
  11610. set: function (value) {
  11611. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11617. get: function () {
  11618. return this._buttonBack;
  11619. },
  11620. set: function (value) {
  11621. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11627. get: function () {
  11628. return this._buttonLB;
  11629. },
  11630. set: function (value) {
  11631. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11637. get: function () {
  11638. return this._buttonRB;
  11639. },
  11640. set: function (value) {
  11641. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11647. get: function () {
  11648. return this._buttonLeftStick;
  11649. },
  11650. set: function (value) {
  11651. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11657. get: function () {
  11658. return this._buttonRightStick;
  11659. },
  11660. set: function (value) {
  11661. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11667. get: function () {
  11668. return this._dPadUp;
  11669. },
  11670. set: function (value) {
  11671. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11677. get: function () {
  11678. return this._dPadDown;
  11679. },
  11680. set: function (value) {
  11681. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11687. get: function () {
  11688. return this._dPadLeft;
  11689. },
  11690. set: function (value) {
  11691. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11697. get: function () {
  11698. return this._dPadRight;
  11699. },
  11700. set: function (value) {
  11701. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Xbox360Pad.prototype.update = function () {
  11707. _super.prototype.update.call(this);
  11708. this.buttonA = this.browserGamepad.buttons[0].value;
  11709. this.buttonB = this.browserGamepad.buttons[1].value;
  11710. this.buttonX = this.browserGamepad.buttons[2].value;
  11711. this.buttonY = this.browserGamepad.buttons[3].value;
  11712. this.buttonLB = this.browserGamepad.buttons[4].value;
  11713. this.buttonRB = this.browserGamepad.buttons[5].value;
  11714. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11715. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11716. this.buttonBack = this.browserGamepad.buttons[8].value;
  11717. this.buttonStart = this.browserGamepad.buttons[9].value;
  11718. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11719. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11720. this.dPadUp = this.browserGamepad.buttons[12].value;
  11721. this.dPadDown = this.browserGamepad.buttons[13].value;
  11722. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11723. this.dPadRight = this.browserGamepad.buttons[15].value;
  11724. };
  11725. return Xbox360Pad;
  11726. })(Gamepad);
  11727. BABYLON.Xbox360Pad = Xbox360Pad;
  11728. })(BABYLON || (BABYLON = {}));
  11729. //# sourceMappingURL=babylon.gamepads.js.map
  11730. var __extends = this.__extends || function (d, b) {
  11731. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11732. function __() { this.constructor = d; }
  11733. __.prototype = b.prototype;
  11734. d.prototype = new __();
  11735. };
  11736. var BABYLON;
  11737. (function (BABYLON) {
  11738. // We're mainly based on the logic defined into the FreeCamera code
  11739. var GamepadCamera = (function (_super) {
  11740. __extends(GamepadCamera, _super);
  11741. function GamepadCamera(name, position, scene) {
  11742. var _this = this;
  11743. _super.call(this, name, position, scene);
  11744. this.angularSensibility = 200;
  11745. this.moveSensibility = 75;
  11746. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  11747. _this._onNewGameConnected(gamepad);
  11748. });
  11749. }
  11750. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11751. // Only the first gamepad can control the camera
  11752. if (gamepad.index === 0) {
  11753. this._gamepad = gamepad;
  11754. }
  11755. };
  11756. GamepadCamera.prototype._checkInputs = function () {
  11757. if (this._gamepad) {
  11758. var LSValues = this._gamepad.leftStick;
  11759. var normalizedLX = LSValues.x / this.moveSensibility;
  11760. var normalizedLY = LSValues.y / this.moveSensibility;
  11761. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11762. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11763. var RSValues = this._gamepad.rightStick;
  11764. var normalizedRX = RSValues.x / this.angularSensibility;
  11765. var normalizedRY = RSValues.y / this.angularSensibility;
  11766. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11767. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11768. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11769. var speed = this._computeLocalCameraSpeed() * 50.0;
  11770. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11771. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11772. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11773. }
  11774. _super.prototype._checkInputs.call(this);
  11775. };
  11776. GamepadCamera.prototype.dispose = function () {
  11777. this._gamepads.dispose();
  11778. _super.prototype.dispose.call(this);
  11779. };
  11780. return GamepadCamera;
  11781. })(BABYLON.FreeCamera);
  11782. BABYLON.GamepadCamera = GamepadCamera;
  11783. })(BABYLON || (BABYLON = {}));
  11784. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11785. var BABYLON;
  11786. (function (BABYLON) {
  11787. var RenderingManager = (function () {
  11788. function RenderingManager(scene) {
  11789. this._renderingGroups = new Array();
  11790. this._scene = scene;
  11791. }
  11792. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11793. if (this._scene._activeParticleSystems.length === 0) {
  11794. return;
  11795. }
  11796. // Particles
  11797. var beforeParticlesDate = BABYLON.Tools.Now;
  11798. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11799. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11800. if (particleSystem.renderingGroupId !== index) {
  11801. continue;
  11802. }
  11803. this._clearDepthBuffer();
  11804. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11805. this._scene._activeParticles += particleSystem.render();
  11806. }
  11807. }
  11808. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11809. };
  11810. RenderingManager.prototype._renderSprites = function (index) {
  11811. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11812. return;
  11813. }
  11814. // Sprites
  11815. var beforeSpritessDate = BABYLON.Tools.Now;
  11816. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11817. var spriteManager = this._scene.spriteManagers[id];
  11818. if (spriteManager.renderingGroupId === index) {
  11819. this._clearDepthBuffer();
  11820. spriteManager.render();
  11821. }
  11822. }
  11823. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11824. };
  11825. RenderingManager.prototype._clearDepthBuffer = function () {
  11826. if (this._depthBufferAlreadyCleaned) {
  11827. return;
  11828. }
  11829. this._scene.getEngine().clear(0, false, true);
  11830. this._depthBufferAlreadyCleaned = true;
  11831. };
  11832. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11833. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11834. this._depthBufferAlreadyCleaned = false;
  11835. var renderingGroup = this._renderingGroups[index];
  11836. var needToStepBack = false;
  11837. if (renderingGroup) {
  11838. this._clearDepthBuffer();
  11839. if (!renderingGroup.render(customRenderFunction)) {
  11840. this._renderingGroups.splice(index, 1);
  11841. needToStepBack = true;
  11842. }
  11843. }
  11844. if (renderSprites) {
  11845. this._renderSprites(index);
  11846. }
  11847. if (renderParticles) {
  11848. this._renderParticles(index, activeMeshes);
  11849. }
  11850. if (needToStepBack) {
  11851. index--;
  11852. }
  11853. }
  11854. };
  11855. RenderingManager.prototype.reset = function () {
  11856. for (var index in this._renderingGroups) {
  11857. var renderingGroup = this._renderingGroups[index];
  11858. renderingGroup.prepare();
  11859. }
  11860. };
  11861. RenderingManager.prototype.dispatch = function (subMesh) {
  11862. var mesh = subMesh.getMesh();
  11863. var renderingGroupId = mesh.renderingGroupId || 0;
  11864. if (!this._renderingGroups[renderingGroupId]) {
  11865. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11866. }
  11867. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11868. };
  11869. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11870. return RenderingManager;
  11871. })();
  11872. BABYLON.RenderingManager = RenderingManager;
  11873. })(BABYLON || (BABYLON = {}));
  11874. //# sourceMappingURL=babylon.renderingManager.js.map
  11875. var BABYLON;
  11876. (function (BABYLON) {
  11877. var RenderingGroup = (function () {
  11878. function RenderingGroup(index, scene) {
  11879. this.index = index;
  11880. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11881. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11882. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11883. this._scene = scene;
  11884. }
  11885. RenderingGroup.prototype.render = function (customRenderFunction) {
  11886. if (customRenderFunction) {
  11887. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11888. return true;
  11889. }
  11890. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11891. return false;
  11892. }
  11893. var engine = this._scene.getEngine();
  11894. // Opaque
  11895. var subIndex;
  11896. var submesh;
  11897. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11898. submesh = this._opaqueSubMeshes.data[subIndex];
  11899. submesh.render();
  11900. }
  11901. // Alpha test
  11902. engine.setAlphaTesting(true);
  11903. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11904. submesh = this._alphaTestSubMeshes.data[subIndex];
  11905. submesh.render();
  11906. }
  11907. engine.setAlphaTesting(false);
  11908. // Transparent
  11909. if (this._transparentSubMeshes.length) {
  11910. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11911. submesh = this._transparentSubMeshes.data[subIndex];
  11912. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11913. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11914. }
  11915. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11916. sortedArray.sort(function (a, b) {
  11917. // Alpha index first
  11918. if (a._alphaIndex > b._alphaIndex) {
  11919. return 1;
  11920. }
  11921. if (a._alphaIndex < b._alphaIndex) {
  11922. return -1;
  11923. }
  11924. // Then distance to camera
  11925. if (a._distanceToCamera < b._distanceToCamera) {
  11926. return 1;
  11927. }
  11928. if (a._distanceToCamera > b._distanceToCamera) {
  11929. return -1;
  11930. }
  11931. return 0;
  11932. });
  11933. // Rendering
  11934. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11935. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11936. submesh = sortedArray[subIndex];
  11937. submesh.render();
  11938. }
  11939. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11940. }
  11941. return true;
  11942. };
  11943. RenderingGroup.prototype.prepare = function () {
  11944. this._opaqueSubMeshes.reset();
  11945. this._transparentSubMeshes.reset();
  11946. this._alphaTestSubMeshes.reset();
  11947. };
  11948. RenderingGroup.prototype.dispatch = function (subMesh) {
  11949. var material = subMesh.getMaterial();
  11950. var mesh = subMesh.getMesh();
  11951. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11952. this._transparentSubMeshes.push(subMesh);
  11953. }
  11954. else if (material.needAlphaTesting()) {
  11955. this._alphaTestSubMeshes.push(subMesh);
  11956. }
  11957. else {
  11958. this._opaqueSubMeshes.push(subMesh); // Opaque
  11959. }
  11960. };
  11961. return RenderingGroup;
  11962. })();
  11963. BABYLON.RenderingGroup = RenderingGroup;
  11964. })(BABYLON || (BABYLON = {}));
  11965. //# sourceMappingURL=babylon.renderingGroup.js.map
  11966. var BABYLON;
  11967. (function (BABYLON) {
  11968. /**
  11969. * Represents a scene to be rendered by the engine.
  11970. * @see http://doc.babylonjs.com/page.php?p=21911
  11971. */
  11972. var Scene = (function () {
  11973. /**
  11974. * @constructor
  11975. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11976. */
  11977. function Scene(engine) {
  11978. // Members
  11979. this.autoClear = true;
  11980. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11981. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11982. this.forceWireframe = false;
  11983. this.forcePointsCloud = false;
  11984. this.forceShowBoundingBoxes = false;
  11985. this.animationsEnabled = true;
  11986. 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
  11987. // Fog
  11988. /**
  11989. * is fog enabled on this scene.
  11990. * @type {boolean}
  11991. */
  11992. this.fogEnabled = true;
  11993. this.fogMode = Scene.FOGMODE_NONE;
  11994. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11995. this.fogDensity = 0.1;
  11996. this.fogStart = 0;
  11997. this.fogEnd = 1000.0;
  11998. // Lights
  11999. /**
  12000. * is shadow enabled on this scene.
  12001. * @type {boolean}
  12002. */
  12003. this.shadowsEnabled = true;
  12004. /**
  12005. * is light enabled on this scene.
  12006. * @type {boolean}
  12007. */
  12008. this.lightsEnabled = true;
  12009. /**
  12010. * All of the lights added to this scene.
  12011. * @see BABYLON.Light
  12012. * @type {BABYLON.Light[]}
  12013. */
  12014. this.lights = new Array();
  12015. // Cameras
  12016. /**
  12017. * All of the cameras added to this scene.
  12018. * @see BABYLON.Camera
  12019. * @type {BABYLON.Camera[]}
  12020. */
  12021. this.cameras = new Array();
  12022. this.activeCameras = new Array();
  12023. // Meshes
  12024. /**
  12025. * All of the (abstract) meshes added to this scene.
  12026. * @see BABYLON.AbstractMesh
  12027. * @type {BABYLON.AbstractMesh[]}
  12028. */
  12029. this.meshes = new Array();
  12030. // Geometries
  12031. this._geometries = new Array();
  12032. this.materials = new Array();
  12033. this.multiMaterials = new Array();
  12034. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12035. // Textures
  12036. this.texturesEnabled = true;
  12037. this.textures = new Array();
  12038. // Particles
  12039. this.particlesEnabled = true;
  12040. this.particleSystems = new Array();
  12041. // Sprites
  12042. this.spritesEnabled = true;
  12043. this.spriteManagers = new Array();
  12044. // Layers
  12045. this.layers = new Array();
  12046. // Skeletons
  12047. this.skeletonsEnabled = true;
  12048. this.skeletons = new Array();
  12049. // Lens flares
  12050. this.lensFlaresEnabled = true;
  12051. this.lensFlareSystems = new Array();
  12052. // Collisions
  12053. this.collisionsEnabled = true;
  12054. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12055. // Postprocesses
  12056. this.postProcessesEnabled = true;
  12057. // Customs render targets
  12058. this.renderTargetsEnabled = true;
  12059. this.dumpNextRenderTargets = false;
  12060. this.customRenderTargets = new Array();
  12061. // Imported meshes
  12062. this.importedMeshesFiles = new Array();
  12063. this._actionManagers = new Array();
  12064. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12065. // Procedural textures
  12066. this.proceduralTexturesEnabled = true;
  12067. this._proceduralTextures = new Array();
  12068. this.soundTracks = new Array();
  12069. this._audioEnabled = true;
  12070. this._headphone = false;
  12071. this._totalVertices = 0;
  12072. this._activeIndices = 0;
  12073. this._activeParticles = 0;
  12074. this._lastFrameDuration = 0;
  12075. this._evaluateActiveMeshesDuration = 0;
  12076. this._renderTargetsDuration = 0;
  12077. this._particlesDuration = 0;
  12078. this._renderDuration = 0;
  12079. this._spritesDuration = 0;
  12080. this._animationRatio = 0;
  12081. this._renderId = 0;
  12082. this._executeWhenReadyTimeoutId = -1;
  12083. this._toBeDisposed = new BABYLON.SmartArray(256);
  12084. this._onReadyCallbacks = new Array();
  12085. this._pendingData = []; //ANY
  12086. this._onBeforeRenderCallbacks = new Array();
  12087. this._onAfterRenderCallbacks = new Array();
  12088. this._activeMeshes = new BABYLON.SmartArray(256);
  12089. this._processedMaterials = new BABYLON.SmartArray(256);
  12090. this._renderTargets = new BABYLON.SmartArray(256);
  12091. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12092. this._activeSkeletons = new BABYLON.SmartArray(32);
  12093. this._activeBones = 0;
  12094. this._activeAnimatables = new Array();
  12095. this._transformMatrix = BABYLON.Matrix.Zero();
  12096. this._uniqueIdCounter = 0;
  12097. this._engine = engine;
  12098. engine.scenes.push(this);
  12099. this._renderingManager = new BABYLON.RenderingManager(this);
  12100. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12101. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12102. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12103. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12104. this.attachControl();
  12105. this._debugLayer = new BABYLON.DebugLayer(this);
  12106. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12107. //simplification queue
  12108. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12109. //collision coordinator initialization. For now legacy per default.
  12110. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12111. }
  12112. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12113. get: function () {
  12114. return Scene._FOGMODE_NONE;
  12115. },
  12116. enumerable: true,
  12117. configurable: true
  12118. });
  12119. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12120. get: function () {
  12121. return Scene._FOGMODE_EXP;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12127. get: function () {
  12128. return Scene._FOGMODE_EXP2;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12134. get: function () {
  12135. return Scene._FOGMODE_LINEAR;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "debugLayer", {
  12141. // Properties
  12142. get: function () {
  12143. return this._debugLayer;
  12144. },
  12145. enumerable: true,
  12146. configurable: true
  12147. });
  12148. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12149. get: function () {
  12150. return this._workerCollisions;
  12151. },
  12152. set: function (enabled) {
  12153. enabled = (enabled && !!Worker);
  12154. this._workerCollisions = enabled;
  12155. if (this.collisionCoordinator) {
  12156. this.collisionCoordinator.destroy();
  12157. }
  12158. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12159. this.collisionCoordinator.init(this);
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12165. /**
  12166. * The mesh that is currently under the pointer.
  12167. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12168. */
  12169. get: function () {
  12170. return this._meshUnderPointer;
  12171. },
  12172. enumerable: true,
  12173. configurable: true
  12174. });
  12175. Object.defineProperty(Scene.prototype, "pointerX", {
  12176. /**
  12177. * Current on-screen X position of the pointer
  12178. * @return {number} X position of the pointer
  12179. */
  12180. get: function () {
  12181. return this._pointerX;
  12182. },
  12183. enumerable: true,
  12184. configurable: true
  12185. });
  12186. Object.defineProperty(Scene.prototype, "pointerY", {
  12187. /**
  12188. * Current on-screen Y position of the pointer
  12189. * @return {number} Y position of the pointer
  12190. */
  12191. get: function () {
  12192. return this._pointerY;
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. Scene.prototype.getCachedMaterial = function () {
  12198. return this._cachedMaterial;
  12199. };
  12200. Scene.prototype.getBoundingBoxRenderer = function () {
  12201. return this._boundingBoxRenderer;
  12202. };
  12203. Scene.prototype.getOutlineRenderer = function () {
  12204. return this._outlineRenderer;
  12205. };
  12206. Scene.prototype.getEngine = function () {
  12207. return this._engine;
  12208. };
  12209. Scene.prototype.getTotalVertices = function () {
  12210. return this._totalVertices;
  12211. };
  12212. Scene.prototype.getActiveIndices = function () {
  12213. return this._activeIndices;
  12214. };
  12215. Scene.prototype.getActiveParticles = function () {
  12216. return this._activeParticles;
  12217. };
  12218. Scene.prototype.getActiveBones = function () {
  12219. return this._activeBones;
  12220. };
  12221. // Stats
  12222. Scene.prototype.getLastFrameDuration = function () {
  12223. return this._lastFrameDuration;
  12224. };
  12225. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12226. return this._evaluateActiveMeshesDuration;
  12227. };
  12228. Scene.prototype.getActiveMeshes = function () {
  12229. return this._activeMeshes;
  12230. };
  12231. Scene.prototype.getRenderTargetsDuration = function () {
  12232. return this._renderTargetsDuration;
  12233. };
  12234. Scene.prototype.getRenderDuration = function () {
  12235. return this._renderDuration;
  12236. };
  12237. Scene.prototype.getParticlesDuration = function () {
  12238. return this._particlesDuration;
  12239. };
  12240. Scene.prototype.getSpritesDuration = function () {
  12241. return this._spritesDuration;
  12242. };
  12243. Scene.prototype.getAnimationRatio = function () {
  12244. return this._animationRatio;
  12245. };
  12246. Scene.prototype.getRenderId = function () {
  12247. return this._renderId;
  12248. };
  12249. Scene.prototype.incrementRenderId = function () {
  12250. this._renderId++;
  12251. };
  12252. Scene.prototype._updatePointerPosition = function (evt) {
  12253. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12254. this._pointerX = evt.clientX - canvasRect.left;
  12255. this._pointerY = evt.clientY - canvasRect.top;
  12256. if (this.cameraToUseForPointers) {
  12257. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12258. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12259. }
  12260. };
  12261. // Pointers handling
  12262. Scene.prototype.attachControl = function () {
  12263. var _this = this;
  12264. this._onPointerMove = function (evt) {
  12265. var canvas = _this._engine.getRenderingCanvas();
  12266. _this._updatePointerPosition(evt);
  12267. 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);
  12268. if (pickResult.hit) {
  12269. _this._meshUnderPointer = pickResult.pickedMesh;
  12270. _this.setPointerOverMesh(pickResult.pickedMesh);
  12271. canvas.style.cursor = "pointer";
  12272. }
  12273. else {
  12274. _this.setPointerOverMesh(null);
  12275. canvas.style.cursor = "";
  12276. _this._meshUnderPointer = null;
  12277. }
  12278. };
  12279. this._onPointerDown = function (evt) {
  12280. var predicate = null;
  12281. if (!_this.onPointerDown) {
  12282. predicate = function (mesh) {
  12283. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12284. };
  12285. }
  12286. _this._updatePointerPosition(evt);
  12287. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12288. if (pickResult.hit) {
  12289. if (pickResult.pickedMesh.actionManager) {
  12290. switch (evt.button) {
  12291. case 0:
  12292. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12293. break;
  12294. case 1:
  12295. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12296. break;
  12297. case 2:
  12298. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12299. break;
  12300. }
  12301. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12302. }
  12303. }
  12304. if (_this.onPointerDown) {
  12305. _this.onPointerDown(evt, pickResult);
  12306. }
  12307. };
  12308. this._onPointerUp = function (evt) {
  12309. var predicate = null;
  12310. if (!_this.onPointerUp) {
  12311. predicate = function (mesh) {
  12312. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12313. };
  12314. }
  12315. _this._updatePointerPosition(evt);
  12316. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12317. if (pickResult.hit) {
  12318. if (pickResult.pickedMesh.actionManager) {
  12319. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12320. }
  12321. }
  12322. if (_this.onPointerUp) {
  12323. _this.onPointerUp(evt, pickResult);
  12324. }
  12325. };
  12326. this._onKeyDown = function (evt) {
  12327. if (_this.actionManager) {
  12328. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12329. }
  12330. };
  12331. this._onKeyUp = function (evt) {
  12332. if (_this.actionManager) {
  12333. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12334. }
  12335. };
  12336. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12337. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12338. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12339. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12340. BABYLON.Tools.RegisterTopRootEvents([
  12341. { name: "keydown", handler: this._onKeyDown },
  12342. { name: "keyup", handler: this._onKeyUp }
  12343. ]);
  12344. };
  12345. Scene.prototype.detachControl = function () {
  12346. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12347. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12348. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12349. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12350. BABYLON.Tools.UnregisterTopRootEvents([
  12351. { name: "keydown", handler: this._onKeyDown },
  12352. { name: "keyup", handler: this._onKeyUp }
  12353. ]);
  12354. };
  12355. // Ready
  12356. Scene.prototype.isReady = function () {
  12357. if (this._pendingData.length > 0) {
  12358. return false;
  12359. }
  12360. for (var index = 0; index < this._geometries.length; index++) {
  12361. var geometry = this._geometries[index];
  12362. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12363. return false;
  12364. }
  12365. }
  12366. for (index = 0; index < this.meshes.length; index++) {
  12367. var mesh = this.meshes[index];
  12368. if (!mesh.isReady()) {
  12369. return false;
  12370. }
  12371. var mat = mesh.material;
  12372. if (mat) {
  12373. if (!mat.isReady(mesh)) {
  12374. return false;
  12375. }
  12376. }
  12377. }
  12378. return true;
  12379. };
  12380. Scene.prototype.resetCachedMaterial = function () {
  12381. this._cachedMaterial = null;
  12382. };
  12383. Scene.prototype.registerBeforeRender = function (func) {
  12384. this._onBeforeRenderCallbacks.push(func);
  12385. };
  12386. Scene.prototype.unregisterBeforeRender = function (func) {
  12387. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12388. if (index > -1) {
  12389. this._onBeforeRenderCallbacks.splice(index, 1);
  12390. }
  12391. };
  12392. Scene.prototype.registerAfterRender = function (func) {
  12393. this._onAfterRenderCallbacks.push(func);
  12394. };
  12395. Scene.prototype.unregisterAfterRender = function (func) {
  12396. var index = this._onAfterRenderCallbacks.indexOf(func);
  12397. if (index > -1) {
  12398. this._onAfterRenderCallbacks.splice(index, 1);
  12399. }
  12400. };
  12401. Scene.prototype._addPendingData = function (data) {
  12402. this._pendingData.push(data);
  12403. };
  12404. Scene.prototype._removePendingData = function (data) {
  12405. var index = this._pendingData.indexOf(data);
  12406. if (index !== -1) {
  12407. this._pendingData.splice(index, 1);
  12408. }
  12409. };
  12410. Scene.prototype.getWaitingItemsCount = function () {
  12411. return this._pendingData.length;
  12412. };
  12413. /**
  12414. * Registers a function to be executed when the scene is ready.
  12415. * @param {Function} func - the function to be executed.
  12416. */
  12417. Scene.prototype.executeWhenReady = function (func) {
  12418. var _this = this;
  12419. this._onReadyCallbacks.push(func);
  12420. if (this._executeWhenReadyTimeoutId !== -1) {
  12421. return;
  12422. }
  12423. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12424. _this._checkIsReady();
  12425. }, 150);
  12426. };
  12427. Scene.prototype._checkIsReady = function () {
  12428. var _this = this;
  12429. if (this.isReady()) {
  12430. this._onReadyCallbacks.forEach(function (func) {
  12431. func();
  12432. });
  12433. this._onReadyCallbacks = [];
  12434. this._executeWhenReadyTimeoutId = -1;
  12435. return;
  12436. }
  12437. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12438. _this._checkIsReady();
  12439. }, 150);
  12440. };
  12441. // Animations
  12442. /**
  12443. * Will start the animation sequence of a given target
  12444. * @param target - the target
  12445. * @param {number} from - from which frame should animation start
  12446. * @param {number} to - till which frame should animation run.
  12447. * @param {boolean} [loop] - should the animation loop
  12448. * @param {number} [speedRatio] - the speed in which to run the animation
  12449. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12450. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12451. * @return {BABYLON.Animatable} the animatable object created for this animation
  12452. * @see BABYLON.Animatable
  12453. * @see http://doc.babylonjs.com/page.php?p=22081
  12454. */
  12455. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12456. if (speedRatio === undefined) {
  12457. speedRatio = 1.0;
  12458. }
  12459. this.stopAnimation(target);
  12460. if (!animatable) {
  12461. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12462. }
  12463. // Local animations
  12464. if (target.animations) {
  12465. animatable.appendAnimations(target, target.animations);
  12466. }
  12467. // Children animations
  12468. if (target.getAnimatables) {
  12469. var animatables = target.getAnimatables();
  12470. for (var index = 0; index < animatables.length; index++) {
  12471. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12472. }
  12473. }
  12474. return animatable;
  12475. };
  12476. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12477. if (speedRatio === undefined) {
  12478. speedRatio = 1.0;
  12479. }
  12480. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12481. return animatable;
  12482. };
  12483. Scene.prototype.getAnimatableByTarget = function (target) {
  12484. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12485. if (this._activeAnimatables[index].target === target) {
  12486. return this._activeAnimatables[index];
  12487. }
  12488. }
  12489. return null;
  12490. };
  12491. /**
  12492. * Will stop the animation of the given target
  12493. * @param target - the target
  12494. * @see beginAnimation
  12495. */
  12496. Scene.prototype.stopAnimation = function (target) {
  12497. var animatable = this.getAnimatableByTarget(target);
  12498. if (animatable) {
  12499. animatable.stop();
  12500. }
  12501. };
  12502. Scene.prototype._animate = function () {
  12503. if (!this.animationsEnabled) {
  12504. return;
  12505. }
  12506. if (!this._animationStartDate) {
  12507. this._animationStartDate = BABYLON.Tools.Now;
  12508. }
  12509. // Getting time
  12510. var now = BABYLON.Tools.Now;
  12511. var delay = now - this._animationStartDate;
  12512. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12513. this._activeAnimatables[index]._animate(delay);
  12514. }
  12515. };
  12516. // Matrix
  12517. Scene.prototype.getViewMatrix = function () {
  12518. return this._viewMatrix;
  12519. };
  12520. Scene.prototype.getProjectionMatrix = function () {
  12521. return this._projectionMatrix;
  12522. };
  12523. Scene.prototype.getTransformMatrix = function () {
  12524. return this._transformMatrix;
  12525. };
  12526. Scene.prototype.setTransformMatrix = function (view, projection) {
  12527. this._viewMatrix = view;
  12528. this._projectionMatrix = projection;
  12529. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12530. };
  12531. // Methods
  12532. Scene.prototype.addMesh = function (newMesh) {
  12533. newMesh.uniqueId = this._uniqueIdCounter++;
  12534. var position = this.meshes.push(newMesh);
  12535. //notify the collision coordinator
  12536. this.collisionCoordinator.onMeshAdded(newMesh);
  12537. if (this.onNewMeshAdded) {
  12538. this.onNewMeshAdded(newMesh, position, this);
  12539. }
  12540. };
  12541. Scene.prototype.removeMesh = function (toRemove) {
  12542. var index = this.meshes.indexOf(toRemove);
  12543. if (index !== -1) {
  12544. // Remove from the scene if mesh found
  12545. this.meshes.splice(index, 1);
  12546. }
  12547. //notify the collision coordinator
  12548. this.collisionCoordinator.onMeshRemoved(toRemove);
  12549. if (this.onMeshRemoved) {
  12550. this.onMeshRemoved(toRemove);
  12551. }
  12552. return index;
  12553. };
  12554. Scene.prototype.removeLight = function (toRemove) {
  12555. var index = this.lights.indexOf(toRemove);
  12556. if (index !== -1) {
  12557. // Remove from the scene if mesh found
  12558. this.lights.splice(index, 1);
  12559. }
  12560. if (this.onLightRemoved) {
  12561. this.onLightRemoved(toRemove);
  12562. }
  12563. return index;
  12564. };
  12565. Scene.prototype.removeCamera = function (toRemove) {
  12566. var index = this.cameras.indexOf(toRemove);
  12567. if (index !== -1) {
  12568. // Remove from the scene if mesh found
  12569. this.cameras.splice(index, 1);
  12570. }
  12571. // Remove from activeCameras
  12572. var index2 = this.activeCameras.indexOf(toRemove);
  12573. if (index2 !== -1) {
  12574. // Remove from the scene if mesh found
  12575. this.activeCameras.splice(index2, 1);
  12576. }
  12577. // Reset the activeCamera
  12578. if (this.activeCamera === toRemove) {
  12579. if (this.cameras.length > 0) {
  12580. this.activeCamera = this.cameras[0];
  12581. }
  12582. else {
  12583. this.activeCamera = null;
  12584. }
  12585. }
  12586. if (this.onCameraRemoved) {
  12587. this.onCameraRemoved(toRemove);
  12588. }
  12589. return index;
  12590. };
  12591. Scene.prototype.addLight = function (newLight) {
  12592. newLight.uniqueId = this._uniqueIdCounter++;
  12593. var position = this.lights.push(newLight);
  12594. if (this.onNewLightAdded) {
  12595. this.onNewLightAdded(newLight, position, this);
  12596. }
  12597. };
  12598. Scene.prototype.addCamera = function (newCamera) {
  12599. newCamera.uniqueId = this._uniqueIdCounter++;
  12600. var position = this.cameras.push(newCamera);
  12601. if (this.onNewCameraAdded) {
  12602. this.onNewCameraAdded(newCamera, position, this);
  12603. }
  12604. };
  12605. /**
  12606. * sets the active camera of the scene using its ID
  12607. * @param {string} id - the camera's ID
  12608. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12609. * @see activeCamera
  12610. */
  12611. Scene.prototype.setActiveCameraByID = function (id) {
  12612. var camera = this.getCameraByID(id);
  12613. if (camera) {
  12614. this.activeCamera = camera;
  12615. return camera;
  12616. }
  12617. return null;
  12618. };
  12619. /**
  12620. * sets the active camera of the scene using its name
  12621. * @param {string} name - the camera's name
  12622. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12623. * @see activeCamera
  12624. */
  12625. Scene.prototype.setActiveCameraByName = function (name) {
  12626. var camera = this.getCameraByName(name);
  12627. if (camera) {
  12628. this.activeCamera = camera;
  12629. return camera;
  12630. }
  12631. return null;
  12632. };
  12633. /**
  12634. * get a material using its id
  12635. * @param {string} the material's ID
  12636. * @return {BABYLON.Material|null} the material or null if none found.
  12637. */
  12638. Scene.prototype.getMaterialByID = function (id) {
  12639. for (var index = 0; index < this.materials.length; index++) {
  12640. if (this.materials[index].id === id) {
  12641. return this.materials[index];
  12642. }
  12643. }
  12644. return null;
  12645. };
  12646. /**
  12647. * get a material using its name
  12648. * @param {string} the material's name
  12649. * @return {BABYLON.Material|null} the material or null if none found.
  12650. */
  12651. Scene.prototype.getMaterialByName = function (name) {
  12652. for (var index = 0; index < this.materials.length; index++) {
  12653. if (this.materials[index].name === name) {
  12654. return this.materials[index];
  12655. }
  12656. }
  12657. return null;
  12658. };
  12659. Scene.prototype.getCameraByID = function (id) {
  12660. for (var index = 0; index < this.cameras.length; index++) {
  12661. if (this.cameras[index].id === id) {
  12662. return this.cameras[index];
  12663. }
  12664. }
  12665. return null;
  12666. };
  12667. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12668. for (var index = 0; index < this.cameras.length; index++) {
  12669. if (this.cameras[index].uniqueId === uniqueId) {
  12670. return this.cameras[index];
  12671. }
  12672. }
  12673. return null;
  12674. };
  12675. /**
  12676. * get a camera using its name
  12677. * @param {string} the camera's name
  12678. * @return {BABYLON.Camera|null} the camera or null if none found.
  12679. */
  12680. Scene.prototype.getCameraByName = function (name) {
  12681. for (var index = 0; index < this.cameras.length; index++) {
  12682. if (this.cameras[index].name === name) {
  12683. return this.cameras[index];
  12684. }
  12685. }
  12686. return null;
  12687. };
  12688. /**
  12689. * get a light node using its name
  12690. * @param {string} the light's name
  12691. * @return {BABYLON.Light|null} the light or null if none found.
  12692. */
  12693. Scene.prototype.getLightByName = function (name) {
  12694. for (var index = 0; index < this.lights.length; index++) {
  12695. if (this.lights[index].name === name) {
  12696. return this.lights[index];
  12697. }
  12698. }
  12699. return null;
  12700. };
  12701. /**
  12702. * get a light node using its ID
  12703. * @param {string} the light's id
  12704. * @return {BABYLON.Light|null} the light or null if none found.
  12705. */
  12706. Scene.prototype.getLightByID = function (id) {
  12707. for (var index = 0; index < this.lights.length; index++) {
  12708. if (this.lights[index].id === id) {
  12709. return this.lights[index];
  12710. }
  12711. }
  12712. return null;
  12713. };
  12714. /**
  12715. * get a light node using its scene-generated unique ID
  12716. * @param {number} the light's unique id
  12717. * @return {BABYLON.Light|null} the light or null if none found.
  12718. */
  12719. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12720. for (var index = 0; index < this.lights.length; index++) {
  12721. if (this.lights[index].uniqueId === uniqueId) {
  12722. return this.lights[index];
  12723. }
  12724. }
  12725. return null;
  12726. };
  12727. /**
  12728. * get a geometry using its ID
  12729. * @param {string} the geometry's id
  12730. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12731. */
  12732. Scene.prototype.getGeometryByID = function (id) {
  12733. for (var index = 0; index < this._geometries.length; index++) {
  12734. if (this._geometries[index].id === id) {
  12735. return this._geometries[index];
  12736. }
  12737. }
  12738. return null;
  12739. };
  12740. /**
  12741. * add a new geometry to this scene.
  12742. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12743. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12744. * @return {boolean} was the geometry added or not
  12745. */
  12746. Scene.prototype.pushGeometry = function (geometry, force) {
  12747. if (!force && this.getGeometryByID(geometry.id)) {
  12748. return false;
  12749. }
  12750. this._geometries.push(geometry);
  12751. //notify the collision coordinator
  12752. this.collisionCoordinator.onGeometryAdded(geometry);
  12753. if (this.onGeometryAdded) {
  12754. this.onGeometryAdded(geometry);
  12755. }
  12756. return true;
  12757. };
  12758. /**
  12759. * Removes an existing geometry
  12760. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12761. * @return {boolean} was the geometry removed or not
  12762. */
  12763. Scene.prototype.removeGeometry = function (geometry) {
  12764. var index = this._geometries.indexOf(geometry);
  12765. if (index > -1) {
  12766. this._geometries.splice(index, 1);
  12767. //notify the collision coordinator
  12768. this.collisionCoordinator.onGeometryDeleted(geometry);
  12769. if (this.onGeometryRemoved) {
  12770. this.onGeometryRemoved(geometry);
  12771. }
  12772. return true;
  12773. }
  12774. return false;
  12775. };
  12776. Scene.prototype.getGeometries = function () {
  12777. return this._geometries;
  12778. };
  12779. /**
  12780. * Get the first added mesh found of a given ID
  12781. * @param {string} id - the id to search for
  12782. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12783. */
  12784. Scene.prototype.getMeshByID = function (id) {
  12785. for (var index = 0; index < this.meshes.length; index++) {
  12786. if (this.meshes[index].id === id) {
  12787. return this.meshes[index];
  12788. }
  12789. }
  12790. return null;
  12791. };
  12792. /**
  12793. * Get a mesh with its auto-generated unique id
  12794. * @param {number} uniqueId - the unique id to search for
  12795. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12796. */
  12797. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12798. for (var index = 0; index < this.meshes.length; index++) {
  12799. if (this.meshes[index].uniqueId === uniqueId) {
  12800. return this.meshes[index];
  12801. }
  12802. }
  12803. return null;
  12804. };
  12805. /**
  12806. * Get a the last added mesh found of a given ID
  12807. * @param {string} id - the id to search for
  12808. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12809. */
  12810. Scene.prototype.getLastMeshByID = function (id) {
  12811. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12812. if (this.meshes[index].id === id) {
  12813. return this.meshes[index];
  12814. }
  12815. }
  12816. return null;
  12817. };
  12818. /**
  12819. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12820. * @param {string} id - the id to search for
  12821. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12822. */
  12823. Scene.prototype.getLastEntryByID = function (id) {
  12824. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12825. if (this.meshes[index].id === id) {
  12826. return this.meshes[index];
  12827. }
  12828. }
  12829. for (index = this.cameras.length - 1; index >= 0; index--) {
  12830. if (this.cameras[index].id === id) {
  12831. return this.cameras[index];
  12832. }
  12833. }
  12834. for (index = this.lights.length - 1; index >= 0; index--) {
  12835. if (this.lights[index].id === id) {
  12836. return this.lights[index];
  12837. }
  12838. }
  12839. return null;
  12840. };
  12841. Scene.prototype.getNodeByName = function (name) {
  12842. var mesh = this.getMeshByName(name);
  12843. if (mesh) {
  12844. return mesh;
  12845. }
  12846. var light = this.getLightByName(name);
  12847. if (light) {
  12848. return light;
  12849. }
  12850. return this.getCameraByName(name);
  12851. };
  12852. Scene.prototype.getMeshByName = function (name) {
  12853. for (var index = 0; index < this.meshes.length; index++) {
  12854. if (this.meshes[index].name === name) {
  12855. return this.meshes[index];
  12856. }
  12857. }
  12858. return null;
  12859. };
  12860. Scene.prototype.getSoundByName = function (name) {
  12861. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12862. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12863. return this.mainSoundTrack.soundCollection[index];
  12864. }
  12865. }
  12866. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12867. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12868. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12869. return this.soundTracks[sdIndex].soundCollection[index];
  12870. }
  12871. }
  12872. }
  12873. return null;
  12874. };
  12875. Scene.prototype.getLastSkeletonByID = function (id) {
  12876. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12877. if (this.skeletons[index].id === id) {
  12878. return this.skeletons[index];
  12879. }
  12880. }
  12881. return null;
  12882. };
  12883. Scene.prototype.getSkeletonById = function (id) {
  12884. for (var index = 0; index < this.skeletons.length; index++) {
  12885. if (this.skeletons[index].id === id) {
  12886. return this.skeletons[index];
  12887. }
  12888. }
  12889. return null;
  12890. };
  12891. Scene.prototype.getSkeletonByName = function (name) {
  12892. for (var index = 0; index < this.skeletons.length; index++) {
  12893. if (this.skeletons[index].name === name) {
  12894. return this.skeletons[index];
  12895. }
  12896. }
  12897. return null;
  12898. };
  12899. Scene.prototype.isActiveMesh = function (mesh) {
  12900. return (this._activeMeshes.indexOf(mesh) !== -1);
  12901. };
  12902. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12903. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12904. var material = subMesh.getMaterial();
  12905. if (mesh.showSubMeshesBoundingBox) {
  12906. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12907. }
  12908. if (material) {
  12909. // Render targets
  12910. if (material.getRenderTargetTextures) {
  12911. if (this._processedMaterials.indexOf(material) === -1) {
  12912. this._processedMaterials.push(material);
  12913. this._renderTargets.concat(material.getRenderTargetTextures());
  12914. }
  12915. }
  12916. // Dispatch
  12917. this._activeIndices += subMesh.indexCount;
  12918. this._renderingManager.dispatch(subMesh);
  12919. }
  12920. }
  12921. };
  12922. Scene.prototype._evaluateActiveMeshes = function () {
  12923. this.activeCamera._activeMeshes.reset();
  12924. this._activeMeshes.reset();
  12925. this._renderingManager.reset();
  12926. this._processedMaterials.reset();
  12927. this._activeParticleSystems.reset();
  12928. this._activeSkeletons.reset();
  12929. this._boundingBoxRenderer.reset();
  12930. if (!this._frustumPlanes) {
  12931. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12932. }
  12933. else {
  12934. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12935. }
  12936. // Meshes
  12937. var meshes;
  12938. var len;
  12939. if (this._selectionOctree) {
  12940. var selection = this._selectionOctree.select(this._frustumPlanes);
  12941. meshes = selection.data;
  12942. len = selection.length;
  12943. }
  12944. else {
  12945. len = this.meshes.length;
  12946. meshes = this.meshes;
  12947. }
  12948. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12949. var mesh = meshes[meshIndex];
  12950. if (mesh.isBlocked) {
  12951. continue;
  12952. }
  12953. this._totalVertices += mesh.getTotalVertices();
  12954. if (!mesh.isReady() || !mesh.isEnabled()) {
  12955. continue;
  12956. }
  12957. mesh.computeWorldMatrix();
  12958. // Intersections
  12959. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12960. this._meshesForIntersections.pushNoDuplicate(mesh);
  12961. }
  12962. // Switch to current LOD
  12963. var meshLOD = mesh.getLOD(this.activeCamera);
  12964. if (!meshLOD) {
  12965. continue;
  12966. }
  12967. mesh._preActivate();
  12968. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12969. this._activeMeshes.push(mesh);
  12970. this.activeCamera._activeMeshes.push(mesh);
  12971. mesh._activate(this._renderId);
  12972. this._activeMesh(meshLOD);
  12973. }
  12974. }
  12975. // Particle systems
  12976. var beforeParticlesDate = BABYLON.Tools.Now;
  12977. if (this.particlesEnabled) {
  12978. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12979. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12980. var particleSystem = this.particleSystems[particleIndex];
  12981. if (!particleSystem.isStarted()) {
  12982. continue;
  12983. }
  12984. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12985. this._activeParticleSystems.push(particleSystem);
  12986. particleSystem.animate();
  12987. }
  12988. }
  12989. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12990. }
  12991. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12992. };
  12993. Scene.prototype._activeMesh = function (mesh) {
  12994. if (mesh.skeleton && this.skeletonsEnabled) {
  12995. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12996. }
  12997. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12998. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12999. }
  13000. if (mesh && mesh.subMeshes) {
  13001. // Submeshes Octrees
  13002. var len;
  13003. var subMeshes;
  13004. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13005. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13006. len = intersections.length;
  13007. subMeshes = intersections.data;
  13008. }
  13009. else {
  13010. subMeshes = mesh.subMeshes;
  13011. len = subMeshes.length;
  13012. }
  13013. for (var subIndex = 0; subIndex < len; subIndex++) {
  13014. var subMesh = subMeshes[subIndex];
  13015. this._evaluateSubMesh(subMesh, mesh);
  13016. }
  13017. }
  13018. };
  13019. Scene.prototype.updateTransformMatrix = function (force) {
  13020. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13021. };
  13022. Scene.prototype._renderForCamera = function (camera) {
  13023. var engine = this._engine;
  13024. this.activeCamera = camera;
  13025. if (!this.activeCamera)
  13026. throw new Error("Active camera not set");
  13027. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13028. // Viewport
  13029. engine.setViewport(this.activeCamera.viewport);
  13030. // Camera
  13031. this.resetCachedMaterial();
  13032. this._renderId++;
  13033. this.updateTransformMatrix();
  13034. if (this.beforeCameraRender) {
  13035. this.beforeCameraRender(this.activeCamera);
  13036. }
  13037. // Meshes
  13038. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13039. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13040. this._evaluateActiveMeshes();
  13041. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13042. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13043. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13044. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13045. skeleton.prepare();
  13046. }
  13047. // Render targets
  13048. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13049. if (this.renderTargetsEnabled) {
  13050. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13051. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13052. var renderTarget = this._renderTargets.data[renderIndex];
  13053. if (renderTarget._shouldRender()) {
  13054. this._renderId++;
  13055. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13056. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13057. }
  13058. }
  13059. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13060. this._renderId++;
  13061. }
  13062. if (this._renderTargets.length > 0) {
  13063. engine.restoreDefaultFramebuffer();
  13064. }
  13065. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13066. // Prepare Frame
  13067. this.postProcessManager._prepareFrame();
  13068. var beforeRenderDate = BABYLON.Tools.Now;
  13069. // Backgrounds
  13070. if (this.layers.length) {
  13071. engine.setDepthBuffer(false);
  13072. var layerIndex;
  13073. var layer;
  13074. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13075. layer = this.layers[layerIndex];
  13076. if (layer.isBackground) {
  13077. layer.render();
  13078. }
  13079. }
  13080. engine.setDepthBuffer(true);
  13081. }
  13082. // Render
  13083. BABYLON.Tools.StartPerformanceCounter("Main render");
  13084. this._renderingManager.render(null, null, true, true);
  13085. BABYLON.Tools.EndPerformanceCounter("Main render");
  13086. // Bounding boxes
  13087. this._boundingBoxRenderer.render();
  13088. // Lens flares
  13089. if (this.lensFlaresEnabled) {
  13090. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13091. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13092. this.lensFlareSystems[lensFlareSystemIndex].render();
  13093. }
  13094. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13095. }
  13096. // Foregrounds
  13097. if (this.layers.length) {
  13098. engine.setDepthBuffer(false);
  13099. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13100. layer = this.layers[layerIndex];
  13101. if (!layer.isBackground) {
  13102. layer.render();
  13103. }
  13104. }
  13105. engine.setDepthBuffer(true);
  13106. }
  13107. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13108. // Finalize frame
  13109. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13110. // Update camera
  13111. this.activeCamera._updateFromScene();
  13112. // Reset some special arrays
  13113. this._renderTargets.reset();
  13114. if (this.afterCameraRender) {
  13115. this.afterCameraRender(this.activeCamera);
  13116. }
  13117. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13118. };
  13119. Scene.prototype._processSubCameras = function (camera) {
  13120. if (camera.subCameras.length === 0) {
  13121. this._renderForCamera(camera);
  13122. return;
  13123. }
  13124. for (var index = 0; index < camera.subCameras.length; index++) {
  13125. this._renderForCamera(camera.subCameras[index]);
  13126. }
  13127. this.activeCamera = camera;
  13128. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13129. // Update camera
  13130. this.activeCamera._updateFromScene();
  13131. };
  13132. Scene.prototype._checkIntersections = function () {
  13133. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13134. var sourceMesh = this._meshesForIntersections.data[index];
  13135. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13136. var action = sourceMesh.actionManager.actions[actionIndex];
  13137. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13138. var parameters = action.getTriggerParameter();
  13139. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13140. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13141. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13142. if (areIntersecting && currentIntersectionInProgress === -1) {
  13143. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13144. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13145. sourceMesh._intersectionsInProgress.push(otherMesh);
  13146. }
  13147. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13148. sourceMesh._intersectionsInProgress.push(otherMesh);
  13149. }
  13150. }
  13151. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13152. //They intersected, and now they don't.
  13153. //is this trigger an exit trigger? execute an event.
  13154. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13155. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13156. }
  13157. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13158. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13159. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13160. }
  13161. }
  13162. }
  13163. }
  13164. }
  13165. };
  13166. Scene.prototype.render = function () {
  13167. var startDate = BABYLON.Tools.Now;
  13168. this._particlesDuration = 0;
  13169. this._spritesDuration = 0;
  13170. this._activeParticles = 0;
  13171. this._renderDuration = 0;
  13172. this._renderTargetsDuration = 0;
  13173. this._evaluateActiveMeshesDuration = 0;
  13174. this._totalVertices = 0;
  13175. this._activeIndices = 0;
  13176. this._activeBones = 0;
  13177. this.getEngine().resetDrawCalls();
  13178. this._meshesForIntersections.reset();
  13179. this.resetCachedMaterial();
  13180. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13181. // Actions
  13182. if (this.actionManager) {
  13183. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13184. }
  13185. //Simplification Queue
  13186. if (!this.simplificationQueue.running) {
  13187. this.simplificationQueue.executeNext();
  13188. }
  13189. // Before render
  13190. if (this.beforeRender) {
  13191. this.beforeRender();
  13192. }
  13193. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13194. this._onBeforeRenderCallbacks[callbackIndex]();
  13195. }
  13196. // Animations
  13197. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13198. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13199. this._animate();
  13200. // Physics
  13201. if (this._physicsEngine) {
  13202. BABYLON.Tools.StartPerformanceCounter("Physics");
  13203. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13204. BABYLON.Tools.EndPerformanceCounter("Physics");
  13205. }
  13206. // Customs render targets
  13207. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13208. var engine = this.getEngine();
  13209. var currentActiveCamera = this.activeCamera;
  13210. if (this.renderTargetsEnabled) {
  13211. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13212. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13213. var renderTarget = this.customRenderTargets[customIndex];
  13214. if (renderTarget._shouldRender()) {
  13215. this._renderId++;
  13216. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13217. if (!this.activeCamera)
  13218. throw new Error("Active camera not set");
  13219. // Viewport
  13220. engine.setViewport(this.activeCamera.viewport);
  13221. // Camera
  13222. this.updateTransformMatrix();
  13223. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13224. }
  13225. }
  13226. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13227. this._renderId++;
  13228. }
  13229. if (this.customRenderTargets.length > 0) {
  13230. engine.restoreDefaultFramebuffer();
  13231. }
  13232. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13233. this.activeCamera = currentActiveCamera;
  13234. // Procedural textures
  13235. if (this.proceduralTexturesEnabled) {
  13236. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13237. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13238. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13239. if (proceduralTexture._shouldRender()) {
  13240. proceduralTexture.render();
  13241. }
  13242. }
  13243. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13244. }
  13245. // Clear
  13246. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13247. // Shadows
  13248. if (this.shadowsEnabled) {
  13249. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13250. var light = this.lights[lightIndex];
  13251. var shadowGenerator = light.getShadowGenerator();
  13252. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13253. this._renderTargets.push(shadowGenerator.getShadowMap());
  13254. }
  13255. }
  13256. }
  13257. // Depth renderer
  13258. if (this._depthRenderer) {
  13259. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13260. }
  13261. // RenderPipeline
  13262. this.postProcessRenderPipelineManager.update();
  13263. // Multi-cameras?
  13264. if (this.activeCameras.length > 0) {
  13265. var currentRenderId = this._renderId;
  13266. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13267. this._renderId = currentRenderId;
  13268. this._processSubCameras(this.activeCameras[cameraIndex]);
  13269. }
  13270. }
  13271. else {
  13272. if (!this.activeCamera) {
  13273. throw new Error("No camera defined");
  13274. }
  13275. this._processSubCameras(this.activeCamera);
  13276. }
  13277. // Intersection checks
  13278. this._checkIntersections();
  13279. // Update the audio listener attached to the camera
  13280. this._updateAudioParameters();
  13281. // After render
  13282. if (this.afterRender) {
  13283. this.afterRender();
  13284. }
  13285. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13286. this._onAfterRenderCallbacks[callbackIndex]();
  13287. }
  13288. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13289. this._toBeDisposed.data[index].dispose();
  13290. this._toBeDisposed[index] = null;
  13291. }
  13292. this._toBeDisposed.reset();
  13293. if (this.dumpNextRenderTargets) {
  13294. this.dumpNextRenderTargets = false;
  13295. }
  13296. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13297. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13298. };
  13299. Scene.prototype._updateAudioParameters = function () {
  13300. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13301. return;
  13302. }
  13303. var listeningCamera;
  13304. var audioEngine = BABYLON.Engine.audioEngine;
  13305. if (this.activeCameras.length > 0) {
  13306. listeningCamera = this.activeCameras[0];
  13307. }
  13308. else {
  13309. listeningCamera = this.activeCamera;
  13310. }
  13311. if (listeningCamera && audioEngine.canUseWebAudio) {
  13312. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13313. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13314. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13315. cameraDirection.normalize();
  13316. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13317. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13318. var sound = this.mainSoundTrack.soundCollection[i];
  13319. if (sound.useCustomAttenuation) {
  13320. sound.updateDistanceFromListener();
  13321. }
  13322. }
  13323. for (i = 0; i < this.soundTracks.length; i++) {
  13324. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13325. sound = this.soundTracks[i].soundCollection[j];
  13326. if (sound.useCustomAttenuation) {
  13327. sound.updateDistanceFromListener();
  13328. }
  13329. }
  13330. }
  13331. }
  13332. };
  13333. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13334. // Audio
  13335. get: function () {
  13336. return this._audioEnabled;
  13337. },
  13338. set: function (value) {
  13339. this._audioEnabled = value;
  13340. if (this._audioEnabled) {
  13341. this._enableAudio();
  13342. }
  13343. else {
  13344. this._disableAudio();
  13345. }
  13346. },
  13347. enumerable: true,
  13348. configurable: true
  13349. });
  13350. Scene.prototype._disableAudio = function () {
  13351. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13352. this.mainSoundTrack.soundCollection[i].pause();
  13353. }
  13354. for (i = 0; i < this.soundTracks.length; i++) {
  13355. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13356. this.soundTracks[i].soundCollection[j].pause();
  13357. }
  13358. }
  13359. };
  13360. Scene.prototype._enableAudio = function () {
  13361. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13362. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13363. this.mainSoundTrack.soundCollection[i].play();
  13364. }
  13365. }
  13366. for (i = 0; i < this.soundTracks.length; i++) {
  13367. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13368. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13369. this.soundTracks[i].soundCollection[j].play();
  13370. }
  13371. }
  13372. }
  13373. };
  13374. Object.defineProperty(Scene.prototype, "headphone", {
  13375. get: function () {
  13376. return this._headphone;
  13377. },
  13378. set: function (value) {
  13379. this._headphone = value;
  13380. if (this._headphone) {
  13381. this._switchAudioModeForHeadphones();
  13382. }
  13383. else {
  13384. this._switchAudioModeForNormalSpeakers();
  13385. }
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. Scene.prototype._switchAudioModeForHeadphones = function () {
  13391. this.mainSoundTrack.switchPanningModelToHRTF();
  13392. for (var i = 0; i < this.soundTracks.length; i++) {
  13393. this.soundTracks[i].switchPanningModelToHRTF();
  13394. }
  13395. };
  13396. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13397. this.mainSoundTrack.switchPanningModelToEqualPower();
  13398. for (var i = 0; i < this.soundTracks.length; i++) {
  13399. this.soundTracks[i].switchPanningModelToEqualPower();
  13400. }
  13401. };
  13402. Scene.prototype.enableDepthRenderer = function () {
  13403. if (this._depthRenderer) {
  13404. return this._depthRenderer;
  13405. }
  13406. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13407. return this._depthRenderer;
  13408. };
  13409. Scene.prototype.disableDepthRenderer = function () {
  13410. if (!this._depthRenderer) {
  13411. return;
  13412. }
  13413. this._depthRenderer.dispose();
  13414. this._depthRenderer = null;
  13415. };
  13416. Scene.prototype.dispose = function () {
  13417. this.beforeRender = null;
  13418. this.afterRender = null;
  13419. this.skeletons = [];
  13420. this._boundingBoxRenderer.dispose();
  13421. if (this._depthRenderer) {
  13422. this._depthRenderer.dispose();
  13423. }
  13424. // Debug layer
  13425. this.debugLayer.hide();
  13426. // Events
  13427. if (this.onDispose) {
  13428. this.onDispose();
  13429. }
  13430. this._onBeforeRenderCallbacks = [];
  13431. this._onAfterRenderCallbacks = [];
  13432. this.detachControl();
  13433. // Release sounds & sounds tracks
  13434. this.disposeSounds();
  13435. // Detach cameras
  13436. var canvas = this._engine.getRenderingCanvas();
  13437. var index;
  13438. for (index = 0; index < this.cameras.length; index++) {
  13439. this.cameras[index].detachControl(canvas);
  13440. }
  13441. while (this.lights.length) {
  13442. this.lights[0].dispose();
  13443. }
  13444. while (this.meshes.length) {
  13445. this.meshes[0].dispose(true);
  13446. }
  13447. while (this.cameras.length) {
  13448. this.cameras[0].dispose();
  13449. }
  13450. while (this.materials.length) {
  13451. this.materials[0].dispose();
  13452. }
  13453. while (this.particleSystems.length) {
  13454. this.particleSystems[0].dispose();
  13455. }
  13456. while (this.spriteManagers.length) {
  13457. this.spriteManagers[0].dispose();
  13458. }
  13459. while (this.layers.length) {
  13460. this.layers[0].dispose();
  13461. }
  13462. while (this.textures.length) {
  13463. this.textures[0].dispose();
  13464. }
  13465. // Post-processes
  13466. this.postProcessManager.dispose();
  13467. // Physics
  13468. if (this._physicsEngine) {
  13469. this.disablePhysicsEngine();
  13470. }
  13471. // Remove from engine
  13472. index = this._engine.scenes.indexOf(this);
  13473. if (index > -1) {
  13474. this._engine.scenes.splice(index, 1);
  13475. }
  13476. this._engine.wipeCaches();
  13477. };
  13478. // Release sounds & sounds tracks
  13479. Scene.prototype.disposeSounds = function () {
  13480. this.mainSoundTrack.dispose();
  13481. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13482. this.soundTracks[scIndex].dispose();
  13483. }
  13484. };
  13485. // Octrees
  13486. Scene.prototype.getWorldExtends = function () {
  13487. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13488. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13489. for (var index = 0; index < this.meshes.length; index++) {
  13490. var mesh = this.meshes[index];
  13491. mesh.computeWorldMatrix(true);
  13492. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13493. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13494. BABYLON.Tools.CheckExtends(minBox, min, max);
  13495. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13496. }
  13497. return {
  13498. min: min,
  13499. max: max
  13500. };
  13501. };
  13502. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13503. if (maxCapacity === void 0) { maxCapacity = 64; }
  13504. if (maxDepth === void 0) { maxDepth = 2; }
  13505. if (!this._selectionOctree) {
  13506. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13507. }
  13508. var worldExtends = this.getWorldExtends();
  13509. // Update octree
  13510. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13511. return this._selectionOctree;
  13512. };
  13513. // Picking
  13514. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13515. var engine = this._engine;
  13516. if (!camera) {
  13517. if (!this.activeCamera)
  13518. throw new Error("Active camera not set");
  13519. camera = this.activeCamera;
  13520. }
  13521. var cameraViewport = camera.viewport;
  13522. var viewport = cameraViewport.toGlobal(engine);
  13523. // Moving coordinates to local viewport world
  13524. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13525. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13526. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13527. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13528. };
  13529. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13530. var pickingInfo = null;
  13531. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13532. var mesh = this.meshes[meshIndex];
  13533. if (predicate) {
  13534. if (!predicate(mesh)) {
  13535. continue;
  13536. }
  13537. }
  13538. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13539. continue;
  13540. }
  13541. var world = mesh.getWorldMatrix();
  13542. var ray = rayFunction(world);
  13543. var result = mesh.intersects(ray, fastCheck);
  13544. if (!result || !result.hit)
  13545. continue;
  13546. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13547. continue;
  13548. pickingInfo = result;
  13549. if (fastCheck) {
  13550. break;
  13551. }
  13552. }
  13553. return pickingInfo || new BABYLON.PickingInfo();
  13554. };
  13555. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13556. var _this = this;
  13557. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13558. /// <param name="x">X position on screen</param>
  13559. /// <param name="y">Y position on screen</param>
  13560. /// <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>
  13561. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13562. /// <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>
  13563. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13564. };
  13565. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13566. var _this = this;
  13567. return this._internalPick(function (world) {
  13568. if (!_this._pickWithRayInverseMatrix) {
  13569. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13570. }
  13571. world.invertToRef(_this._pickWithRayInverseMatrix);
  13572. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13573. }, predicate, fastCheck);
  13574. };
  13575. Scene.prototype.setPointerOverMesh = function (mesh) {
  13576. if (this._pointerOverMesh === mesh) {
  13577. return;
  13578. }
  13579. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13580. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13581. }
  13582. this._pointerOverMesh = mesh;
  13583. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13584. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13585. }
  13586. };
  13587. Scene.prototype.getPointerOverMesh = function () {
  13588. return this._pointerOverMesh;
  13589. };
  13590. // Physics
  13591. Scene.prototype.getPhysicsEngine = function () {
  13592. return this._physicsEngine;
  13593. };
  13594. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13595. if (this._physicsEngine) {
  13596. return true;
  13597. }
  13598. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13599. if (!this._physicsEngine.isSupported()) {
  13600. this._physicsEngine = null;
  13601. return false;
  13602. }
  13603. this._physicsEngine._initialize(gravity);
  13604. return true;
  13605. };
  13606. Scene.prototype.disablePhysicsEngine = function () {
  13607. if (!this._physicsEngine) {
  13608. return;
  13609. }
  13610. this._physicsEngine.dispose();
  13611. this._physicsEngine = undefined;
  13612. };
  13613. Scene.prototype.isPhysicsEnabled = function () {
  13614. return this._physicsEngine !== undefined;
  13615. };
  13616. Scene.prototype.setGravity = function (gravity) {
  13617. if (!this._physicsEngine) {
  13618. return;
  13619. }
  13620. this._physicsEngine._setGravity(gravity);
  13621. };
  13622. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13623. if (parts.parts) {
  13624. options = parts;
  13625. parts = parts.parts;
  13626. }
  13627. if (!this._physicsEngine) {
  13628. return null;
  13629. }
  13630. for (var index = 0; index < parts.length; index++) {
  13631. var mesh = parts[index].mesh;
  13632. mesh._physicImpostor = parts[index].impostor;
  13633. mesh._physicsMass = options.mass / parts.length;
  13634. mesh._physicsFriction = options.friction;
  13635. mesh._physicRestitution = options.restitution;
  13636. }
  13637. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13638. };
  13639. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13640. for (var index = 0; index < compound.parts.length; index++) {
  13641. var mesh = compound.parts[index].mesh;
  13642. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13643. this._physicsEngine._unregisterMesh(mesh);
  13644. }
  13645. };
  13646. // Misc.
  13647. Scene.prototype.createDefaultCameraOrLight = function () {
  13648. // Light
  13649. if (this.lights.length === 0) {
  13650. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13651. }
  13652. // Camera
  13653. if (!this.activeCamera) {
  13654. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13655. // Compute position
  13656. var worldExtends = this.getWorldExtends();
  13657. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13658. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13659. camera.setTarget(worldCenter);
  13660. this.activeCamera = camera;
  13661. }
  13662. };
  13663. // Tags
  13664. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13665. if (tagsQuery === undefined) {
  13666. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13667. return list;
  13668. }
  13669. var listByTags = [];
  13670. forEach = forEach || (function (item) {
  13671. return;
  13672. });
  13673. for (var i in list) {
  13674. var item = list[i];
  13675. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13676. listByTags.push(item);
  13677. forEach(item);
  13678. }
  13679. }
  13680. return listByTags;
  13681. };
  13682. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13683. return this._getByTags(this.meshes, tagsQuery, forEach);
  13684. };
  13685. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13686. return this._getByTags(this.cameras, tagsQuery, forEach);
  13687. };
  13688. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13689. return this._getByTags(this.lights, tagsQuery, forEach);
  13690. };
  13691. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13692. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13693. };
  13694. // Statics
  13695. Scene._FOGMODE_NONE = 0;
  13696. Scene._FOGMODE_EXP = 1;
  13697. Scene._FOGMODE_EXP2 = 2;
  13698. Scene._FOGMODE_LINEAR = 3;
  13699. Scene.MinDeltaTime = 1.0;
  13700. Scene.MaxDeltaTime = 1000.0;
  13701. return Scene;
  13702. })();
  13703. BABYLON.Scene = Scene;
  13704. })(BABYLON || (BABYLON = {}));
  13705. //# sourceMappingURL=babylon.scene.js.map
  13706. var BABYLON;
  13707. (function (BABYLON) {
  13708. var VertexBuffer = (function () {
  13709. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13710. if (engine instanceof BABYLON.Mesh) {
  13711. this._engine = engine.getScene().getEngine();
  13712. }
  13713. else {
  13714. this._engine = engine;
  13715. }
  13716. this._updatable = updatable;
  13717. this._data = data;
  13718. if (!postponeInternalCreation) {
  13719. this.create();
  13720. }
  13721. this._kind = kind;
  13722. if (stride) {
  13723. this._strideSize = stride;
  13724. return;
  13725. }
  13726. switch (kind) {
  13727. case VertexBuffer.PositionKind:
  13728. this._strideSize = 3;
  13729. break;
  13730. case VertexBuffer.NormalKind:
  13731. this._strideSize = 3;
  13732. break;
  13733. case VertexBuffer.UVKind:
  13734. this._strideSize = 2;
  13735. break;
  13736. case VertexBuffer.UV2Kind:
  13737. this._strideSize = 2;
  13738. break;
  13739. case VertexBuffer.ColorKind:
  13740. this._strideSize = 4;
  13741. break;
  13742. case VertexBuffer.MatricesIndicesKind:
  13743. this._strideSize = 4;
  13744. break;
  13745. case VertexBuffer.MatricesWeightsKind:
  13746. this._strideSize = 4;
  13747. break;
  13748. }
  13749. }
  13750. // Properties
  13751. VertexBuffer.prototype.isUpdatable = function () {
  13752. return this._updatable;
  13753. };
  13754. VertexBuffer.prototype.getData = function () {
  13755. return this._data;
  13756. };
  13757. VertexBuffer.prototype.getBuffer = function () {
  13758. return this._buffer;
  13759. };
  13760. VertexBuffer.prototype.getStrideSize = function () {
  13761. return this._strideSize;
  13762. };
  13763. // Methods
  13764. VertexBuffer.prototype.create = function (data) {
  13765. if (!data && this._buffer) {
  13766. return; // nothing to do
  13767. }
  13768. data = data || this._data;
  13769. if (!this._buffer) {
  13770. if (this._updatable) {
  13771. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13772. }
  13773. else {
  13774. this._buffer = this._engine.createVertexBuffer(data);
  13775. }
  13776. }
  13777. if (this._updatable) {
  13778. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13779. this._data = data;
  13780. }
  13781. };
  13782. VertexBuffer.prototype.update = function (data) {
  13783. this.create(data);
  13784. };
  13785. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13786. if (!this._buffer) {
  13787. return;
  13788. }
  13789. if (this._updatable) {
  13790. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13791. this._data = null;
  13792. }
  13793. };
  13794. VertexBuffer.prototype.dispose = function () {
  13795. if (!this._buffer) {
  13796. return;
  13797. }
  13798. if (this._engine._releaseBuffer(this._buffer)) {
  13799. this._buffer = null;
  13800. }
  13801. };
  13802. Object.defineProperty(VertexBuffer, "PositionKind", {
  13803. get: function () {
  13804. return VertexBuffer._PositionKind;
  13805. },
  13806. enumerable: true,
  13807. configurable: true
  13808. });
  13809. Object.defineProperty(VertexBuffer, "NormalKind", {
  13810. get: function () {
  13811. return VertexBuffer._NormalKind;
  13812. },
  13813. enumerable: true,
  13814. configurable: true
  13815. });
  13816. Object.defineProperty(VertexBuffer, "UVKind", {
  13817. get: function () {
  13818. return VertexBuffer._UVKind;
  13819. },
  13820. enumerable: true,
  13821. configurable: true
  13822. });
  13823. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13824. get: function () {
  13825. return VertexBuffer._UV2Kind;
  13826. },
  13827. enumerable: true,
  13828. configurable: true
  13829. });
  13830. Object.defineProperty(VertexBuffer, "ColorKind", {
  13831. get: function () {
  13832. return VertexBuffer._ColorKind;
  13833. },
  13834. enumerable: true,
  13835. configurable: true
  13836. });
  13837. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13838. get: function () {
  13839. return VertexBuffer._MatricesIndicesKind;
  13840. },
  13841. enumerable: true,
  13842. configurable: true
  13843. });
  13844. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13845. get: function () {
  13846. return VertexBuffer._MatricesWeightsKind;
  13847. },
  13848. enumerable: true,
  13849. configurable: true
  13850. });
  13851. // Enums
  13852. VertexBuffer._PositionKind = "position";
  13853. VertexBuffer._NormalKind = "normal";
  13854. VertexBuffer._UVKind = "uv";
  13855. VertexBuffer._UV2Kind = "uv2";
  13856. VertexBuffer._ColorKind = "color";
  13857. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13858. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13859. return VertexBuffer;
  13860. })();
  13861. BABYLON.VertexBuffer = VertexBuffer;
  13862. })(BABYLON || (BABYLON = {}));
  13863. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13864. var __extends = this.__extends || function (d, b) {
  13865. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13866. function __() { this.constructor = d; }
  13867. __.prototype = b.prototype;
  13868. d.prototype = new __();
  13869. };
  13870. var BABYLON;
  13871. (function (BABYLON) {
  13872. /**
  13873. * Creates an instance based on a source mesh.
  13874. */
  13875. var InstancedMesh = (function (_super) {
  13876. __extends(InstancedMesh, _super);
  13877. function InstancedMesh(name, source) {
  13878. _super.call(this, name, source.getScene());
  13879. source.instances.push(this);
  13880. this._sourceMesh = source;
  13881. this.position.copyFrom(source.position);
  13882. this.rotation.copyFrom(source.rotation);
  13883. this.scaling.copyFrom(source.scaling);
  13884. if (source.rotationQuaternion) {
  13885. this.rotationQuaternion = source.rotationQuaternion.clone();
  13886. }
  13887. this.infiniteDistance = source.infiniteDistance;
  13888. this.setPivotMatrix(source.getPivotMatrix());
  13889. this.refreshBoundingInfo();
  13890. this._syncSubMeshes();
  13891. }
  13892. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13893. // Methods
  13894. get: function () {
  13895. return this._sourceMesh.receiveShadows;
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(InstancedMesh.prototype, "material", {
  13901. get: function () {
  13902. return this._sourceMesh.material;
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13908. get: function () {
  13909. return this._sourceMesh.visibility;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13915. get: function () {
  13916. return this._sourceMesh.skeleton;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. InstancedMesh.prototype.getTotalVertices = function () {
  13922. return this._sourceMesh.getTotalVertices();
  13923. };
  13924. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13925. get: function () {
  13926. return this._sourceMesh;
  13927. },
  13928. enumerable: true,
  13929. configurable: true
  13930. });
  13931. InstancedMesh.prototype.getVerticesData = function (kind) {
  13932. return this._sourceMesh.getVerticesData(kind);
  13933. };
  13934. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13935. return this._sourceMesh.isVerticesDataPresent(kind);
  13936. };
  13937. InstancedMesh.prototype.getIndices = function () {
  13938. return this._sourceMesh.getIndices();
  13939. };
  13940. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13941. get: function () {
  13942. return this._sourceMesh._positions;
  13943. },
  13944. enumerable: true,
  13945. configurable: true
  13946. });
  13947. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13948. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13949. if (data) {
  13950. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13951. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13952. }
  13953. this._updateBoundingInfo();
  13954. };
  13955. InstancedMesh.prototype._preActivate = function () {
  13956. if (this._currentLOD) {
  13957. this._currentLOD._preActivate();
  13958. }
  13959. };
  13960. InstancedMesh.prototype._activate = function (renderId) {
  13961. if (this._currentLOD) {
  13962. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13963. }
  13964. };
  13965. InstancedMesh.prototype.getLOD = function (camera) {
  13966. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13967. if (this._currentLOD === this.sourceMesh) {
  13968. return this;
  13969. }
  13970. return this._currentLOD;
  13971. };
  13972. InstancedMesh.prototype._syncSubMeshes = function () {
  13973. this.releaseSubMeshes();
  13974. if (this._sourceMesh.subMeshes) {
  13975. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13976. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13977. }
  13978. }
  13979. };
  13980. InstancedMesh.prototype._generatePointsArray = function () {
  13981. return this._sourceMesh._generatePointsArray();
  13982. };
  13983. // Clone
  13984. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13985. var result = this._sourceMesh.createInstance(name);
  13986. // Deep copy
  13987. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13988. // Bounding info
  13989. this.refreshBoundingInfo();
  13990. // Parent
  13991. if (newParent) {
  13992. result.parent = newParent;
  13993. }
  13994. if (!doNotCloneChildren) {
  13995. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13996. var mesh = this.getScene().meshes[index];
  13997. if (mesh.parent === this) {
  13998. mesh.clone(mesh.name, result);
  13999. }
  14000. }
  14001. }
  14002. result.computeWorldMatrix(true);
  14003. return result;
  14004. };
  14005. // Dispoe
  14006. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14007. // Remove from mesh
  14008. var index = this._sourceMesh.instances.indexOf(this);
  14009. this._sourceMesh.instances.splice(index, 1);
  14010. _super.prototype.dispose.call(this, doNotRecurse);
  14011. };
  14012. return InstancedMesh;
  14013. })(BABYLON.AbstractMesh);
  14014. BABYLON.InstancedMesh = InstancedMesh;
  14015. })(BABYLON || (BABYLON = {}));
  14016. //# sourceMappingURL=babylon.instancedMesh.js.map
  14017. var __extends = this.__extends || function (d, b) {
  14018. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14019. function __() { this.constructor = d; }
  14020. __.prototype = b.prototype;
  14021. d.prototype = new __();
  14022. };
  14023. var BABYLON;
  14024. (function (BABYLON) {
  14025. var _InstancesBatch = (function () {
  14026. function _InstancesBatch() {
  14027. this.mustReturn = false;
  14028. this.visibleInstances = new Array();
  14029. this.renderSelf = new Array();
  14030. }
  14031. return _InstancesBatch;
  14032. })();
  14033. BABYLON._InstancesBatch = _InstancesBatch;
  14034. var Mesh = (function (_super) {
  14035. __extends(Mesh, _super);
  14036. /**
  14037. * @constructor
  14038. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14039. * @param {Scene} scene - The scene to add this mesh to.
  14040. * @param {Node} parent - The parent of this mesh, if it has one
  14041. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14042. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14043. * When false, achieved by calling a clone(), also passing False.
  14044. * This will make creation of children, recursive.
  14045. */
  14046. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14047. if (parent === void 0) { parent = null; }
  14048. _super.call(this, name, scene);
  14049. // Members
  14050. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14051. this.instances = new Array();
  14052. this._LODLevels = new Array();
  14053. this._onBeforeRenderCallbacks = new Array();
  14054. this._onAfterRenderCallbacks = new Array();
  14055. this._visibleInstances = {};
  14056. this._renderIdForInstances = new Array();
  14057. this._batchCache = new _InstancesBatch();
  14058. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14059. this._sideOrientation = Mesh._DEFAULTSIDE;
  14060. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14061. if (source) {
  14062. // Geometry
  14063. if (source._geometry) {
  14064. source._geometry.applyToMesh(this);
  14065. }
  14066. // Deep copy
  14067. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14068. // Material
  14069. this.material = source.material;
  14070. if (!doNotCloneChildren) {
  14071. for (var index = 0; index < scene.meshes.length; index++) {
  14072. var mesh = scene.meshes[index];
  14073. if (mesh.parent === source) {
  14074. // doNotCloneChildren is always going to be False
  14075. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14076. }
  14077. }
  14078. }
  14079. for (index = 0; index < scene.particleSystems.length; index++) {
  14080. var system = scene.particleSystems[index];
  14081. if (system.emitter === source) {
  14082. system.clone(system.name, this);
  14083. }
  14084. }
  14085. this.computeWorldMatrix(true);
  14086. }
  14087. // Parent
  14088. if (parent !== null) {
  14089. this.parent = parent;
  14090. }
  14091. }
  14092. Object.defineProperty(Mesh, "FRONTSIDE", {
  14093. get: function () {
  14094. return Mesh._FRONTSIDE;
  14095. },
  14096. enumerable: true,
  14097. configurable: true
  14098. });
  14099. Object.defineProperty(Mesh, "BACKSIDE", {
  14100. get: function () {
  14101. return Mesh._BACKSIDE;
  14102. },
  14103. enumerable: true,
  14104. configurable: true
  14105. });
  14106. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14107. get: function () {
  14108. return Mesh._DOUBLESIDE;
  14109. },
  14110. enumerable: true,
  14111. configurable: true
  14112. });
  14113. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14114. get: function () {
  14115. return Mesh._DEFAULTSIDE;
  14116. },
  14117. enumerable: true,
  14118. configurable: true
  14119. });
  14120. Object.defineProperty(Mesh, "NO_CAP", {
  14121. get: function () {
  14122. return Mesh._NO_CAP;
  14123. },
  14124. enumerable: true,
  14125. configurable: true
  14126. });
  14127. Object.defineProperty(Mesh, "CAP_START", {
  14128. get: function () {
  14129. return Mesh._CAP_START;
  14130. },
  14131. enumerable: true,
  14132. configurable: true
  14133. });
  14134. Object.defineProperty(Mesh, "CAP_END", {
  14135. get: function () {
  14136. return Mesh._CAP_END;
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(Mesh, "CAP_ALL", {
  14142. get: function () {
  14143. return Mesh._CAP_ALL;
  14144. },
  14145. enumerable: true,
  14146. configurable: true
  14147. });
  14148. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14149. // Methods
  14150. get: function () {
  14151. return this._LODLevels.length > 0;
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. Mesh.prototype._sortLODLevels = function () {
  14157. this._LODLevels.sort(function (a, b) {
  14158. if (a.distance < b.distance) {
  14159. return 1;
  14160. }
  14161. if (a.distance > b.distance) {
  14162. return -1;
  14163. }
  14164. return 0;
  14165. });
  14166. };
  14167. /**
  14168. * Add a mesh as LOD level triggered at the given distance.
  14169. * @param {number} distance - the distance from the center of the object to show this level
  14170. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14171. * @return {BABYLON.Mesh} this mesh (for chaining)
  14172. */
  14173. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14174. if (mesh && mesh._masterMesh) {
  14175. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14176. return this;
  14177. }
  14178. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14179. this._LODLevels.push(level);
  14180. if (mesh) {
  14181. mesh._masterMesh = this;
  14182. }
  14183. this._sortLODLevels();
  14184. return this;
  14185. };
  14186. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14187. for (var index = 0; index < this._LODLevels.length; index++) {
  14188. var level = this._LODLevels[index];
  14189. if (level.distance === distance) {
  14190. return level.mesh;
  14191. }
  14192. }
  14193. return null;
  14194. };
  14195. /**
  14196. * Remove a mesh from the LOD array
  14197. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14198. * @return {BABYLON.Mesh} this mesh (for chaining)
  14199. */
  14200. Mesh.prototype.removeLODLevel = function (mesh) {
  14201. for (var index = 0; index < this._LODLevels.length; index++) {
  14202. if (this._LODLevels[index].mesh === mesh) {
  14203. this._LODLevels.splice(index, 1);
  14204. if (mesh) {
  14205. mesh._masterMesh = null;
  14206. }
  14207. }
  14208. }
  14209. this._sortLODLevels();
  14210. return this;
  14211. };
  14212. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14213. if (!this._LODLevels || this._LODLevels.length === 0) {
  14214. return this;
  14215. }
  14216. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14217. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14218. if (this.onLODLevelSelection) {
  14219. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14220. }
  14221. return this;
  14222. }
  14223. for (var index = 0; index < this._LODLevels.length; index++) {
  14224. var level = this._LODLevels[index];
  14225. if (level.distance < distanceToCamera) {
  14226. if (level.mesh) {
  14227. level.mesh._preActivate();
  14228. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14229. }
  14230. if (this.onLODLevelSelection) {
  14231. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14232. }
  14233. return level.mesh;
  14234. }
  14235. }
  14236. if (this.onLODLevelSelection) {
  14237. this.onLODLevelSelection(distanceToCamera, this, this);
  14238. }
  14239. return this;
  14240. };
  14241. Object.defineProperty(Mesh.prototype, "geometry", {
  14242. get: function () {
  14243. return this._geometry;
  14244. },
  14245. enumerable: true,
  14246. configurable: true
  14247. });
  14248. Mesh.prototype.getTotalVertices = function () {
  14249. if (!this._geometry) {
  14250. return 0;
  14251. }
  14252. return this._geometry.getTotalVertices();
  14253. };
  14254. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14255. if (!this._geometry) {
  14256. return null;
  14257. }
  14258. return this._geometry.getVerticesData(kind, copyWhenShared);
  14259. };
  14260. Mesh.prototype.getVertexBuffer = function (kind) {
  14261. if (!this._geometry) {
  14262. return undefined;
  14263. }
  14264. return this._geometry.getVertexBuffer(kind);
  14265. };
  14266. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14267. if (!this._geometry) {
  14268. if (this._delayInfo) {
  14269. return this._delayInfo.indexOf(kind) !== -1;
  14270. }
  14271. return false;
  14272. }
  14273. return this._geometry.isVerticesDataPresent(kind);
  14274. };
  14275. Mesh.prototype.getVerticesDataKinds = function () {
  14276. if (!this._geometry) {
  14277. var result = [];
  14278. if (this._delayInfo) {
  14279. for (var kind in this._delayInfo) {
  14280. result.push(kind);
  14281. }
  14282. }
  14283. return result;
  14284. }
  14285. return this._geometry.getVerticesDataKinds();
  14286. };
  14287. Mesh.prototype.getTotalIndices = function () {
  14288. if (!this._geometry) {
  14289. return 0;
  14290. }
  14291. return this._geometry.getTotalIndices();
  14292. };
  14293. Mesh.prototype.getIndices = function (copyWhenShared) {
  14294. if (!this._geometry) {
  14295. return [];
  14296. }
  14297. return this._geometry.getIndices(copyWhenShared);
  14298. };
  14299. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14300. get: function () {
  14301. return this._masterMesh !== null && this._masterMesh !== undefined;
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Mesh.prototype.isReady = function () {
  14307. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14308. return false;
  14309. }
  14310. return _super.prototype.isReady.call(this);
  14311. };
  14312. Mesh.prototype.isDisposed = function () {
  14313. return this._isDisposed;
  14314. };
  14315. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14316. get: function () {
  14317. return this._sideOrientation;
  14318. },
  14319. set: function (sideO) {
  14320. this._sideOrientation = sideO;
  14321. },
  14322. enumerable: true,
  14323. configurable: true
  14324. });
  14325. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14326. get: function () {
  14327. return this._areNormalsFrozen;
  14328. },
  14329. enumerable: true,
  14330. configurable: true
  14331. });
  14332. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14333. Mesh.prototype.freezeNormals = function () {
  14334. this._areNormalsFrozen = true;
  14335. };
  14336. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14337. Mesh.prototype.unfreezeNormals = function () {
  14338. this._areNormalsFrozen = false;
  14339. };
  14340. // Methods
  14341. Mesh.prototype._preActivate = function () {
  14342. var sceneRenderId = this.getScene().getRenderId();
  14343. if (this._preActivateId === sceneRenderId) {
  14344. return;
  14345. }
  14346. this._preActivateId = sceneRenderId;
  14347. this._visibleInstances = null;
  14348. };
  14349. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14350. if (!this._visibleInstances) {
  14351. this._visibleInstances = {};
  14352. this._visibleInstances.defaultRenderId = renderId;
  14353. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14354. }
  14355. if (!this._visibleInstances[renderId]) {
  14356. this._visibleInstances[renderId] = new Array();
  14357. }
  14358. this._visibleInstances[renderId].push(instance);
  14359. };
  14360. Mesh.prototype.refreshBoundingInfo = function () {
  14361. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14362. if (data) {
  14363. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14364. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14365. }
  14366. if (this.subMeshes) {
  14367. for (var index = 0; index < this.subMeshes.length; index++) {
  14368. this.subMeshes[index].refreshBoundingInfo();
  14369. }
  14370. }
  14371. this._updateBoundingInfo();
  14372. };
  14373. Mesh.prototype._createGlobalSubMesh = function () {
  14374. var totalVertices = this.getTotalVertices();
  14375. if (!totalVertices || !this.getIndices()) {
  14376. return null;
  14377. }
  14378. this.releaseSubMeshes();
  14379. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14380. };
  14381. Mesh.prototype.subdivide = function (count) {
  14382. if (count < 1) {
  14383. return;
  14384. }
  14385. var totalIndices = this.getTotalIndices();
  14386. var subdivisionSize = (totalIndices / count) | 0;
  14387. var offset = 0;
  14388. while (subdivisionSize % 3 !== 0) {
  14389. subdivisionSize++;
  14390. }
  14391. this.releaseSubMeshes();
  14392. for (var index = 0; index < count; index++) {
  14393. if (offset >= totalIndices) {
  14394. break;
  14395. }
  14396. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14397. offset += subdivisionSize;
  14398. }
  14399. this.synchronizeInstances();
  14400. };
  14401. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14402. if (kind instanceof Array) {
  14403. var temp = data;
  14404. data = kind;
  14405. kind = temp;
  14406. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14407. }
  14408. if (!this._geometry) {
  14409. var vertexData = new BABYLON.VertexData();
  14410. vertexData.set(data, kind);
  14411. var scene = this.getScene();
  14412. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14413. }
  14414. else {
  14415. this._geometry.setVerticesData(kind, data, updatable, stride);
  14416. }
  14417. };
  14418. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14419. if (!this._geometry) {
  14420. return;
  14421. }
  14422. if (!makeItUnique) {
  14423. this._geometry.updateVerticesData(kind, data, updateExtends);
  14424. }
  14425. else {
  14426. this.makeGeometryUnique();
  14427. this.updateVerticesData(kind, data, updateExtends, false);
  14428. }
  14429. };
  14430. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14431. if (!this._geometry) {
  14432. return;
  14433. }
  14434. if (!makeItUnique) {
  14435. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14436. }
  14437. else {
  14438. this.makeGeometryUnique();
  14439. this.updateVerticesDataDirectly(kind, data, offset, false);
  14440. }
  14441. };
  14442. // Mesh positions update function :
  14443. // updates the mesh positions according to the positionFunction returned values.
  14444. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14445. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14446. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14447. if (computeNormals === void 0) { computeNormals = true; }
  14448. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14449. positionFunction(positions);
  14450. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14451. if (computeNormals) {
  14452. var indices = this.getIndices();
  14453. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14454. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14456. }
  14457. };
  14458. Mesh.prototype.makeGeometryUnique = function () {
  14459. if (!this._geometry) {
  14460. return;
  14461. }
  14462. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14463. geometry.applyToMesh(this);
  14464. };
  14465. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14466. if (!this._geometry) {
  14467. var vertexData = new BABYLON.VertexData();
  14468. vertexData.indices = indices;
  14469. var scene = this.getScene();
  14470. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14471. }
  14472. else {
  14473. this._geometry.setIndices(indices, totalVertices);
  14474. }
  14475. };
  14476. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14477. var engine = this.getScene().getEngine();
  14478. // Wireframe
  14479. var indexToBind;
  14480. switch (fillMode) {
  14481. case BABYLON.Material.PointFillMode:
  14482. indexToBind = null;
  14483. break;
  14484. case BABYLON.Material.WireFrameFillMode:
  14485. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14486. break;
  14487. default:
  14488. case BABYLON.Material.TriangleFillMode:
  14489. indexToBind = this._geometry.getIndexBuffer();
  14490. break;
  14491. }
  14492. // VBOs
  14493. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14494. };
  14495. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14496. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14497. return;
  14498. }
  14499. var engine = this.getScene().getEngine();
  14500. switch (fillMode) {
  14501. case BABYLON.Material.PointFillMode:
  14502. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14503. break;
  14504. case BABYLON.Material.WireFrameFillMode:
  14505. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14506. break;
  14507. default:
  14508. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14509. }
  14510. };
  14511. Mesh.prototype.registerBeforeRender = function (func) {
  14512. this._onBeforeRenderCallbacks.push(func);
  14513. };
  14514. Mesh.prototype.unregisterBeforeRender = function (func) {
  14515. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14516. if (index > -1) {
  14517. this._onBeforeRenderCallbacks.splice(index, 1);
  14518. }
  14519. };
  14520. Mesh.prototype.registerAfterRender = function (func) {
  14521. this._onAfterRenderCallbacks.push(func);
  14522. };
  14523. Mesh.prototype.unregisterAfterRender = function (func) {
  14524. var index = this._onAfterRenderCallbacks.indexOf(func);
  14525. if (index > -1) {
  14526. this._onAfterRenderCallbacks.splice(index, 1);
  14527. }
  14528. };
  14529. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14530. var scene = this.getScene();
  14531. this._batchCache.mustReturn = false;
  14532. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14533. this._batchCache.visibleInstances[subMeshId] = null;
  14534. if (this._visibleInstances) {
  14535. var currentRenderId = scene.getRenderId();
  14536. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14537. var selfRenderId = this._renderId;
  14538. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14539. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14540. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14541. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14542. }
  14543. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14544. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14545. this._batchCache.mustReturn = true;
  14546. return this._batchCache;
  14547. }
  14548. if (currentRenderId !== selfRenderId) {
  14549. this._batchCache.renderSelf[subMeshId] = false;
  14550. }
  14551. }
  14552. this._renderIdForInstances[subMeshId] = currentRenderId;
  14553. }
  14554. return this._batchCache;
  14555. };
  14556. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14557. var visibleInstances = batch.visibleInstances[subMesh._id];
  14558. var matricesCount = visibleInstances.length + 1;
  14559. var bufferSize = matricesCount * 16 * 4;
  14560. while (this._instancesBufferSize < bufferSize) {
  14561. this._instancesBufferSize *= 2;
  14562. }
  14563. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14564. if (this._worldMatricesInstancesBuffer) {
  14565. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14566. }
  14567. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14568. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14569. }
  14570. var offset = 0;
  14571. var instancesCount = 0;
  14572. var world = this.getWorldMatrix();
  14573. if (batch.renderSelf[subMesh._id]) {
  14574. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14575. offset += 16;
  14576. instancesCount++;
  14577. }
  14578. if (visibleInstances) {
  14579. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14580. var instance = visibleInstances[instanceIndex];
  14581. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14582. offset += 16;
  14583. instancesCount++;
  14584. }
  14585. }
  14586. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14587. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14588. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14589. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14590. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14591. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14592. this._draw(subMesh, fillMode, instancesCount);
  14593. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14594. };
  14595. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14596. var scene = this.getScene();
  14597. var engine = scene.getEngine();
  14598. if (hardwareInstancedRendering) {
  14599. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14600. }
  14601. else {
  14602. if (batch.renderSelf[subMesh._id]) {
  14603. // Draw
  14604. if (onBeforeDraw) {
  14605. onBeforeDraw(false, this.getWorldMatrix());
  14606. }
  14607. this._draw(subMesh, fillMode);
  14608. }
  14609. if (batch.visibleInstances[subMesh._id]) {
  14610. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14611. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14612. // World
  14613. var world = instance.getWorldMatrix();
  14614. if (onBeforeDraw) {
  14615. onBeforeDraw(true, world);
  14616. }
  14617. // Draw
  14618. this._draw(subMesh, fillMode);
  14619. }
  14620. }
  14621. }
  14622. };
  14623. Mesh.prototype.render = function (subMesh) {
  14624. var scene = this.getScene();
  14625. // Managing instances
  14626. var batch = this._getInstancesRenderList(subMesh._id);
  14627. if (batch.mustReturn) {
  14628. return;
  14629. }
  14630. // Checking geometry state
  14631. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14632. return;
  14633. }
  14634. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14635. this._onBeforeRenderCallbacks[callbackIndex](this);
  14636. }
  14637. var engine = scene.getEngine();
  14638. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14639. // Material
  14640. var effectiveMaterial = subMesh.getMaterial();
  14641. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14642. return;
  14643. }
  14644. // Outline - step 1
  14645. var savedDepthWrite = engine.getDepthWrite();
  14646. if (this.renderOutline) {
  14647. engine.setDepthWrite(false);
  14648. scene.getOutlineRenderer().render(subMesh, batch);
  14649. engine.setDepthWrite(savedDepthWrite);
  14650. }
  14651. effectiveMaterial._preBind();
  14652. var effect = effectiveMaterial.getEffect();
  14653. // Bind
  14654. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14655. this._bind(subMesh, effect, fillMode);
  14656. var world = this.getWorldMatrix();
  14657. effectiveMaterial.bind(world, this);
  14658. // Draw
  14659. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14660. if (isInstance) {
  14661. effectiveMaterial.bindOnlyWorldMatrix(world);
  14662. }
  14663. });
  14664. // Unbind
  14665. effectiveMaterial.unbind();
  14666. // Outline - step 2
  14667. if (this.renderOutline && savedDepthWrite) {
  14668. engine.setDepthWrite(true);
  14669. engine.setColorWrite(false);
  14670. scene.getOutlineRenderer().render(subMesh, batch);
  14671. engine.setColorWrite(true);
  14672. }
  14673. // Overlay
  14674. if (this.renderOverlay) {
  14675. var currentMode = engine.getAlphaMode();
  14676. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14677. scene.getOutlineRenderer().render(subMesh, batch, true);
  14678. engine.setAlphaMode(currentMode);
  14679. }
  14680. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14681. this._onAfterRenderCallbacks[callbackIndex](this);
  14682. }
  14683. };
  14684. Mesh.prototype.getEmittedParticleSystems = function () {
  14685. var results = new Array();
  14686. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14687. var particleSystem = this.getScene().particleSystems[index];
  14688. if (particleSystem.emitter === this) {
  14689. results.push(particleSystem);
  14690. }
  14691. }
  14692. return results;
  14693. };
  14694. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14695. var results = new Array();
  14696. var descendants = this.getDescendants();
  14697. descendants.push(this);
  14698. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14699. var particleSystem = this.getScene().particleSystems[index];
  14700. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14701. results.push(particleSystem);
  14702. }
  14703. }
  14704. return results;
  14705. };
  14706. Mesh.prototype.getChildren = function () {
  14707. var results = [];
  14708. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14709. var mesh = this.getScene().meshes[index];
  14710. if (mesh.parent === this) {
  14711. results.push(mesh);
  14712. }
  14713. }
  14714. return results;
  14715. };
  14716. Mesh.prototype._checkDelayState = function () {
  14717. var _this = this;
  14718. var that = this;
  14719. var scene = this.getScene();
  14720. if (this._geometry) {
  14721. this._geometry.load(scene);
  14722. }
  14723. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14724. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14725. scene._addPendingData(that);
  14726. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14727. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14728. if (data instanceof ArrayBuffer) {
  14729. _this._delayLoadingFunction(data, _this);
  14730. }
  14731. else {
  14732. _this._delayLoadingFunction(JSON.parse(data), _this);
  14733. }
  14734. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14735. scene._removePendingData(_this);
  14736. }, function () {
  14737. }, scene.database, getBinaryData);
  14738. }
  14739. };
  14740. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14741. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14742. return false;
  14743. }
  14744. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14745. return false;
  14746. }
  14747. this._checkDelayState();
  14748. return true;
  14749. };
  14750. Mesh.prototype.setMaterialByID = function (id) {
  14751. var materials = this.getScene().materials;
  14752. for (var index = 0; index < materials.length; index++) {
  14753. if (materials[index].id === id) {
  14754. this.material = materials[index];
  14755. return;
  14756. }
  14757. }
  14758. // Multi
  14759. var multiMaterials = this.getScene().multiMaterials;
  14760. for (index = 0; index < multiMaterials.length; index++) {
  14761. if (multiMaterials[index].id === id) {
  14762. this.material = multiMaterials[index];
  14763. return;
  14764. }
  14765. }
  14766. };
  14767. Mesh.prototype.getAnimatables = function () {
  14768. var results = [];
  14769. if (this.material) {
  14770. results.push(this.material);
  14771. }
  14772. if (this.skeleton) {
  14773. results.push(this.skeleton);
  14774. }
  14775. return results;
  14776. };
  14777. // Geometry
  14778. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14779. // Position
  14780. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14781. return;
  14782. }
  14783. this._resetPointsArrayCache();
  14784. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14785. var temp = [];
  14786. for (var index = 0; index < data.length; index += 3) {
  14787. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14788. }
  14789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14790. // Normals
  14791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14792. return;
  14793. }
  14794. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14795. temp = [];
  14796. for (index = 0; index < data.length; index += 3) {
  14797. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14798. }
  14799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14800. };
  14801. // Cache
  14802. Mesh.prototype._resetPointsArrayCache = function () {
  14803. this._positions = null;
  14804. };
  14805. Mesh.prototype._generatePointsArray = function () {
  14806. if (this._positions)
  14807. return true;
  14808. this._positions = [];
  14809. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14810. if (!data) {
  14811. return false;
  14812. }
  14813. for (var index = 0; index < data.length; index += 3) {
  14814. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14815. }
  14816. return true;
  14817. };
  14818. // Clone
  14819. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14820. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14821. };
  14822. // Dispose
  14823. Mesh.prototype.dispose = function (doNotRecurse) {
  14824. if (this._geometry) {
  14825. this._geometry.releaseForMesh(this, true);
  14826. }
  14827. // Instances
  14828. if (this._worldMatricesInstancesBuffer) {
  14829. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14830. this._worldMatricesInstancesBuffer = null;
  14831. }
  14832. while (this.instances.length) {
  14833. this.instances[0].dispose();
  14834. }
  14835. _super.prototype.dispose.call(this, doNotRecurse);
  14836. };
  14837. // Geometric tools
  14838. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14839. var _this = this;
  14840. var scene = this.getScene();
  14841. var onload = function (img) {
  14842. // Getting height map data
  14843. var canvas = document.createElement("canvas");
  14844. var context = canvas.getContext("2d");
  14845. var heightMapWidth = img.width;
  14846. var heightMapHeight = img.height;
  14847. canvas.width = heightMapWidth;
  14848. canvas.height = heightMapHeight;
  14849. context.drawImage(img, 0, 0);
  14850. // Create VertexData from map data
  14851. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14852. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14853. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14854. //execute success callback, if set
  14855. if (onSuccess) {
  14856. onSuccess(_this);
  14857. }
  14858. };
  14859. BABYLON.Tools.LoadImage(url, onload, function () {
  14860. }, scene.database);
  14861. };
  14862. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14863. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14864. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14865. return;
  14866. }
  14867. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14868. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14869. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14870. var position = BABYLON.Vector3.Zero();
  14871. var normal = BABYLON.Vector3.Zero();
  14872. var uv = BABYLON.Vector2.Zero();
  14873. for (var index = 0; index < positions.length; index += 3) {
  14874. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14875. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14876. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14877. // Compute height
  14878. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14879. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14880. var pos = (u + v * heightMapWidth) * 4;
  14881. var r = buffer[pos] / 255.0;
  14882. var g = buffer[pos + 1] / 255.0;
  14883. var b = buffer[pos + 2] / 255.0;
  14884. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14885. normal.normalize();
  14886. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14887. position = position.add(normal);
  14888. position.toArray(positions, index);
  14889. }
  14890. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14891. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14892. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14893. };
  14894. Mesh.prototype.convertToFlatShadedMesh = function () {
  14895. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14896. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14897. var kinds = this.getVerticesDataKinds();
  14898. var vbs = [];
  14899. var data = [];
  14900. var newdata = [];
  14901. var updatableNormals = false;
  14902. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14903. var kind = kinds[kindIndex];
  14904. var vertexBuffer = this.getVertexBuffer(kind);
  14905. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14906. updatableNormals = vertexBuffer.isUpdatable();
  14907. kinds.splice(kindIndex, 1);
  14908. kindIndex--;
  14909. continue;
  14910. }
  14911. vbs[kind] = vertexBuffer;
  14912. data[kind] = vbs[kind].getData();
  14913. newdata[kind] = [];
  14914. }
  14915. // Save previous submeshes
  14916. var previousSubmeshes = this.subMeshes.slice(0);
  14917. var indices = this.getIndices();
  14918. var totalIndices = this.getTotalIndices();
  14919. for (var index = 0; index < totalIndices; index++) {
  14920. var vertexIndex = indices[index];
  14921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14922. kind = kinds[kindIndex];
  14923. var stride = vbs[kind].getStrideSize();
  14924. for (var offset = 0; offset < stride; offset++) {
  14925. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14926. }
  14927. }
  14928. }
  14929. // Updating faces & normal
  14930. var normals = [];
  14931. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14932. for (index = 0; index < totalIndices; index += 3) {
  14933. indices[index] = index;
  14934. indices[index + 1] = index + 1;
  14935. indices[index + 2] = index + 2;
  14936. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14937. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14938. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14939. var p1p2 = p1.subtract(p2);
  14940. var p3p2 = p3.subtract(p2);
  14941. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14942. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14943. normals.push(normal.x);
  14944. normals.push(normal.y);
  14945. normals.push(normal.z);
  14946. }
  14947. }
  14948. this.setIndices(indices);
  14949. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14951. kind = kinds[kindIndex];
  14952. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14953. }
  14954. // Updating submeshes
  14955. this.releaseSubMeshes();
  14956. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14957. var previousOne = previousSubmeshes[submeshIndex];
  14958. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14959. }
  14960. this.synchronizeInstances();
  14961. };
  14962. // Instances
  14963. Mesh.prototype.createInstance = function (name) {
  14964. return new BABYLON.InstancedMesh(name, this);
  14965. };
  14966. Mesh.prototype.synchronizeInstances = function () {
  14967. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14968. var instance = this.instances[instanceIndex];
  14969. instance._syncSubMeshes();
  14970. }
  14971. };
  14972. /**
  14973. * Simplify the mesh according to the given array of settings.
  14974. * Function will return immediately and will simplify async.
  14975. * @param settings a collection of simplification settings.
  14976. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14977. * @param type the type of simplification to run.
  14978. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14979. */
  14980. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14981. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14982. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  14983. this.getScene().simplificationQueue.addTask({
  14984. settings: settings,
  14985. parallelProcessing: parallelProcessing,
  14986. mesh: this,
  14987. simplificationType: simplificationType,
  14988. successCallback: successCallback
  14989. });
  14990. };
  14991. /**
  14992. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14993. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14994. * This should be used together with the simplification to avoid disappearing triangles.
  14995. * @param successCallback an optional success callback to be called after the optimization finished.
  14996. */
  14997. Mesh.prototype.optimizeIndices = function (successCallback) {
  14998. var _this = this;
  14999. var indices = this.getIndices();
  15000. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15001. var vectorPositions = [];
  15002. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15003. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15004. }
  15005. var dupes = [];
  15006. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15007. var realPos = vectorPositions.length - 1 - iteration;
  15008. var testedPosition = vectorPositions[realPos];
  15009. for (var j = 0; j < realPos; ++j) {
  15010. var againstPosition = vectorPositions[j];
  15011. if (testedPosition.equals(againstPosition)) {
  15012. dupes[realPos] = j;
  15013. break;
  15014. }
  15015. }
  15016. }, function () {
  15017. for (var i = 0; i < indices.length; ++i) {
  15018. indices[i] = dupes[indices[i]] || indices[i];
  15019. }
  15020. //indices are now reordered
  15021. var originalSubMeshes = _this.subMeshes.slice(0);
  15022. _this.setIndices(indices);
  15023. _this.subMeshes = originalSubMeshes;
  15024. if (successCallback) {
  15025. successCallback(_this);
  15026. }
  15027. });
  15028. };
  15029. // Statics
  15030. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15031. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15032. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15033. if (ribbonInstance) {
  15034. // positionFunction : ribbon case
  15035. // only pathArray and sideOrientation parameters are taken into account for positions update
  15036. var positionFunction = function (positions) {
  15037. var minlg = pathArray[0].length;
  15038. var i = 0;
  15039. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15040. for (var si = 1; si <= ns; si++) {
  15041. for (var p = 0; p < pathArray.length; p++) {
  15042. var path = pathArray[p];
  15043. var l = path.length;
  15044. minlg = (minlg < l) ? minlg : l;
  15045. var j = 0;
  15046. while (j < minlg) {
  15047. positions[i] = path[j].x;
  15048. positions[i + 1] = path[j].y;
  15049. positions[i + 2] = path[j].z;
  15050. j++;
  15051. i += 3;
  15052. }
  15053. }
  15054. }
  15055. };
  15056. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15057. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15058. return ribbonInstance;
  15059. }
  15060. else {
  15061. var ribbon = new Mesh(name, scene);
  15062. ribbon.sideOrientation = sideOrientation;
  15063. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15064. vertexData.applyToMesh(ribbon, updatable);
  15065. return ribbon;
  15066. }
  15067. };
  15068. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15069. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15070. var disc = new Mesh(name, scene);
  15071. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15072. vertexData.applyToMesh(disc, updatable);
  15073. return disc;
  15074. };
  15075. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15076. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15077. var box = new Mesh(name, scene);
  15078. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15079. vertexData.applyToMesh(box, updatable);
  15080. return box;
  15081. };
  15082. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15083. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15084. var sphere = new Mesh(name, scene);
  15085. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15086. vertexData.applyToMesh(sphere, updatable);
  15087. return sphere;
  15088. };
  15089. // Cylinder and cone (Code inspired by SharpDX.org)
  15090. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15091. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15092. // subdivisions is a new parameter, we need to support old signature
  15093. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15094. if (scene !== undefined) {
  15095. updatable = scene;
  15096. }
  15097. scene = subdivisions;
  15098. subdivisions = 1;
  15099. }
  15100. var cylinder = new Mesh(name, scene);
  15101. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15102. vertexData.applyToMesh(cylinder, updatable);
  15103. return cylinder;
  15104. };
  15105. // Torus (Code from SharpDX.org)
  15106. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15107. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15108. var torus = new Mesh(name, scene);
  15109. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15110. vertexData.applyToMesh(torus, updatable);
  15111. return torus;
  15112. };
  15113. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15114. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15115. var torusKnot = new Mesh(name, scene);
  15116. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15117. vertexData.applyToMesh(torusKnot, updatable);
  15118. return torusKnot;
  15119. };
  15120. // Lines
  15121. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15122. if (linesInstance === void 0) { linesInstance = null; }
  15123. if (linesInstance) {
  15124. var positionsOfLines = function (points) {
  15125. var positionFunction = function (positions) {
  15126. var i = 0;
  15127. for (var p = 0; p < points.length; p++) {
  15128. positions[i] = points[p].x;
  15129. positions[i + 1] = points[p].y;
  15130. positions[i + 2] = points[p].z;
  15131. i += 3;
  15132. }
  15133. };
  15134. return positionFunction;
  15135. };
  15136. var positionFunction = positionsOfLines(points);
  15137. linesInstance.updateMeshPositions(positionFunction, false);
  15138. return linesInstance;
  15139. }
  15140. // lines creation
  15141. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15142. var vertexData = BABYLON.VertexData.CreateLines(points);
  15143. vertexData.applyToMesh(lines, updatable);
  15144. return lines;
  15145. };
  15146. // Dashed Lines
  15147. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15148. if (linesInstance === void 0) { linesInstance = null; }
  15149. if (linesInstance) {
  15150. var positionFunction = function (positions) {
  15151. var curvect = BABYLON.Vector3.Zero();
  15152. var nbSeg = positions.length / 6;
  15153. var lg = 0;
  15154. var nb = 0;
  15155. var shft = 0;
  15156. var dashshft = 0;
  15157. var curshft = 0;
  15158. var p = 0;
  15159. var i = 0;
  15160. var j = 0;
  15161. for (i = 0; i < points.length - 1; i++) {
  15162. points[i + 1].subtractToRef(points[i], curvect);
  15163. lg += curvect.length();
  15164. }
  15165. shft = lg / nbSeg;
  15166. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15167. for (i = 0; i < points.length - 1; i++) {
  15168. points[i + 1].subtractToRef(points[i], curvect);
  15169. curvect.normalize();
  15170. nb = Math.floor(curvect.length() / shft);
  15171. j = 0;
  15172. while (j < nb && p < positions.length) {
  15173. curshft = shft * j;
  15174. positions[p] = points[i].x + curshft * curvect.x;
  15175. positions[p + 1] = points[i].y + curshft * curvect.y;
  15176. positions[p + 2] = points[i].z + curshft * curvect.z;
  15177. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15178. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15179. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15180. p += 6;
  15181. j++;
  15182. }
  15183. }
  15184. while (p < positions.length) {
  15185. positions[p] = points[i].x;
  15186. positions[p + 1] = points[i].y;
  15187. positions[p + 2] = points[i].z;
  15188. p += 3;
  15189. }
  15190. };
  15191. linesInstance.updateMeshPositions(positionFunction, false);
  15192. return linesInstance;
  15193. }
  15194. // dashed lines creation
  15195. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15196. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15197. vertexData.applyToMesh(dashedLines, updatable);
  15198. dashedLines.dashSize = dashSize;
  15199. dashedLines.gapSize = gapSize;
  15200. return dashedLines;
  15201. };
  15202. // Extrusion
  15203. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15204. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15205. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15206. scale = scale || 1;
  15207. rotation = rotation || 0;
  15208. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15209. return extruded;
  15210. };
  15211. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15212. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15213. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15214. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15215. return extrudedCustom;
  15216. };
  15217. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15218. // extrusion geometry
  15219. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15220. var tangents = path3D.getTangents();
  15221. var normals = path3D.getNormals();
  15222. var binormals = path3D.getBinormals();
  15223. var distances = path3D.getDistances();
  15224. var angle = 0;
  15225. var returnScale = function (i, distance) {
  15226. return scale;
  15227. };
  15228. var returnRotation = function (i, distance) {
  15229. return rotation;
  15230. };
  15231. var rotate = custom ? rotateFunction : returnRotation;
  15232. var scl = custom ? scaleFunction : returnScale;
  15233. var index = 0;
  15234. for (var i = 0; i < curve.length; i++) {
  15235. var shapePath = new Array();
  15236. var angleStep = rotate(i, distances[i]);
  15237. var scaleRatio = scl(i, distances[i]);
  15238. for (var p = 0; p < shape.length; p++) {
  15239. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15240. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15241. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15242. shapePath.push(rotated);
  15243. }
  15244. shapePaths[index] = shapePath;
  15245. angle += angleStep;
  15246. index++;
  15247. }
  15248. // cap
  15249. var capPath = function (shapePath) {
  15250. var pointCap = Array();
  15251. var barycenter = BABYLON.Vector3.Zero();
  15252. var i;
  15253. for (i = 0; i < shapePath.length; i++) {
  15254. barycenter.addInPlace(shapePath[i]);
  15255. }
  15256. barycenter.scaleInPlace(1 / shapePath.length);
  15257. for (i = 0; i < shapePath.length; i++) {
  15258. pointCap.push(barycenter);
  15259. }
  15260. return pointCap;
  15261. };
  15262. switch (cap) {
  15263. case BABYLON.Mesh.NO_CAP:
  15264. break;
  15265. case BABYLON.Mesh.CAP_START:
  15266. shapePaths.unshift(capPath(shapePaths[0]));
  15267. break;
  15268. case BABYLON.Mesh.CAP_END:
  15269. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15270. break;
  15271. case BABYLON.Mesh.CAP_ALL:
  15272. shapePaths.unshift(capPath(shapePaths[0]));
  15273. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15274. break;
  15275. default:
  15276. break;
  15277. }
  15278. return shapePaths;
  15279. };
  15280. if (instance) {
  15281. var path3D = (instance.path3D).update(curve);
  15282. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15283. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15284. return instance;
  15285. }
  15286. // extruded shape creation
  15287. var path3D = new BABYLON.Path3D(curve);
  15288. var newShapePaths = new Array();
  15289. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15290. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15291. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15292. extrudedGeneric.pathArray = pathArray;
  15293. extrudedGeneric.path3D = path3D;
  15294. extrudedGeneric.cap = cap;
  15295. return extrudedGeneric;
  15296. };
  15297. // Plane & ground
  15298. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15299. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15300. var plane = new Mesh(name, scene);
  15301. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15302. vertexData.applyToMesh(plane, updatable);
  15303. return plane;
  15304. };
  15305. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15306. var ground = new BABYLON.GroundMesh(name, scene);
  15307. ground._setReady(false);
  15308. ground._subdivisions = subdivisions;
  15309. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15310. vertexData.applyToMesh(ground, updatable);
  15311. ground._setReady(true);
  15312. return ground;
  15313. };
  15314. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15315. var tiledGround = new Mesh(name, scene);
  15316. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15317. vertexData.applyToMesh(tiledGround, updatable);
  15318. return tiledGround;
  15319. };
  15320. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15321. var ground = new BABYLON.GroundMesh(name, scene);
  15322. ground._subdivisions = subdivisions;
  15323. ground._setReady(false);
  15324. var onload = function (img) {
  15325. // Getting height map data
  15326. var canvas = document.createElement("canvas");
  15327. var context = canvas.getContext("2d");
  15328. var heightMapWidth = img.width;
  15329. var heightMapHeight = img.height;
  15330. canvas.width = heightMapWidth;
  15331. canvas.height = heightMapHeight;
  15332. context.drawImage(img, 0, 0);
  15333. // Create VertexData from map data
  15334. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15335. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15336. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15337. vertexData.applyToMesh(ground, updatable);
  15338. ground._setReady(true);
  15339. //execute ready callback, if set
  15340. if (onReady) {
  15341. onReady(ground);
  15342. }
  15343. };
  15344. BABYLON.Tools.LoadImage(url, onload, function () {
  15345. }, scene.database);
  15346. return ground;
  15347. };
  15348. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15349. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15350. if (tubeInstance === void 0) { tubeInstance = null; }
  15351. // tube geometry
  15352. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15353. var tangents = path3D.getTangents();
  15354. var normals = path3D.getNormals();
  15355. var distances = path3D.getDistances();
  15356. var pi2 = Math.PI * 2;
  15357. var step = pi2 / tessellation;
  15358. var returnRadius = function (i, distance) { return radius; };
  15359. var radiusFunctionFinal = radiusFunction || returnRadius;
  15360. var circlePath;
  15361. var rad;
  15362. var normal;
  15363. var rotated;
  15364. var rotationMatrix;
  15365. var index = 0;
  15366. for (var i = 0; i < path.length; i++) {
  15367. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15368. circlePath = Array(); // current circle array
  15369. normal = normals[i]; // current normal
  15370. for (var t = 0; t < tessellation; t++) {
  15371. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15372. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15373. circlePath.push(rotated);
  15374. }
  15375. circlePath.push(circlePath[0]);
  15376. circlePaths[index] = circlePath;
  15377. index++;
  15378. }
  15379. // cap
  15380. var capPath = function (nbPoints, pathIndex) {
  15381. var pointCap = Array();
  15382. for (var i = 0; i < nbPoints; i++) {
  15383. pointCap.push(path[pathIndex]);
  15384. }
  15385. return pointCap;
  15386. };
  15387. switch (cap) {
  15388. case BABYLON.Mesh.NO_CAP:
  15389. break;
  15390. case BABYLON.Mesh.CAP_START:
  15391. circlePaths.unshift(capPath(tessellation + 1, 0));
  15392. break;
  15393. case BABYLON.Mesh.CAP_END:
  15394. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15395. break;
  15396. case BABYLON.Mesh.CAP_ALL:
  15397. circlePaths.unshift(capPath(tessellation + 1, 0));
  15398. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15399. break;
  15400. default:
  15401. break;
  15402. }
  15403. return circlePaths;
  15404. };
  15405. if (tubeInstance) {
  15406. var path3D = (tubeInstance.path3D).update(path);
  15407. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15408. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15409. return tubeInstance;
  15410. }
  15411. // tube creation
  15412. var path3D = new BABYLON.Path3D(path);
  15413. var newPathArray = new Array();
  15414. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15415. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15416. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15417. tube.pathArray = pathArray;
  15418. tube.path3D = path3D;
  15419. tube.tessellation = tessellation;
  15420. tube.cap = cap;
  15421. return tube;
  15422. };
  15423. // Decals
  15424. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15425. if (angle === void 0) { angle = 0; }
  15426. var indices = sourceMesh.getIndices();
  15427. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15428. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15429. // Getting correct rotation
  15430. if (!normal) {
  15431. var target = new BABYLON.Vector3(0, 0, 1);
  15432. var camera = sourceMesh.getScene().activeCamera;
  15433. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15434. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15435. }
  15436. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15437. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15438. var pitch = Math.atan2(normal.y, len);
  15439. // Matrix
  15440. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15441. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15442. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15443. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15444. var vertexData = new BABYLON.VertexData();
  15445. vertexData.indices = [];
  15446. vertexData.positions = [];
  15447. vertexData.normals = [];
  15448. vertexData.uvs = [];
  15449. var currentVertexDataIndex = 0;
  15450. var extractDecalVector3 = function (indexId) {
  15451. var vertexId = indices[indexId];
  15452. var result = new BABYLON.PositionNormalVertex();
  15453. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15454. // Send vector to decal local world
  15455. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15456. // Get normal
  15457. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15458. return result;
  15459. };
  15460. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15461. var clip = function (vertices, axis) {
  15462. if (vertices.length === 0) {
  15463. return vertices;
  15464. }
  15465. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15466. var clipVertices = function (v0, v1) {
  15467. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15468. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15469. };
  15470. var result = new Array();
  15471. for (var index = 0; index < vertices.length; index += 3) {
  15472. var v1Out;
  15473. var v2Out;
  15474. var v3Out;
  15475. var total = 0;
  15476. var nV1, nV2, nV3, nV4;
  15477. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15478. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15479. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15480. v1Out = d1 > 0;
  15481. v2Out = d2 > 0;
  15482. v3Out = d3 > 0;
  15483. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15484. switch (total) {
  15485. case 0:
  15486. result.push(vertices[index]);
  15487. result.push(vertices[index + 1]);
  15488. result.push(vertices[index + 2]);
  15489. break;
  15490. case 1:
  15491. if (v1Out) {
  15492. nV1 = vertices[index + 1];
  15493. nV2 = vertices[index + 2];
  15494. nV3 = clipVertices(vertices[index], nV1);
  15495. nV4 = clipVertices(vertices[index], nV2);
  15496. }
  15497. if (v2Out) {
  15498. nV1 = vertices[index];
  15499. nV2 = vertices[index + 2];
  15500. nV3 = clipVertices(vertices[index + 1], nV1);
  15501. nV4 = clipVertices(vertices[index + 1], nV2);
  15502. result.push(nV3);
  15503. result.push(nV2.clone());
  15504. result.push(nV1.clone());
  15505. result.push(nV2.clone());
  15506. result.push(nV3.clone());
  15507. result.push(nV4);
  15508. break;
  15509. }
  15510. if (v3Out) {
  15511. nV1 = vertices[index];
  15512. nV2 = vertices[index + 1];
  15513. nV3 = clipVertices(vertices[index + 2], nV1);
  15514. nV4 = clipVertices(vertices[index + 2], nV2);
  15515. }
  15516. result.push(nV1.clone());
  15517. result.push(nV2.clone());
  15518. result.push(nV3);
  15519. result.push(nV4);
  15520. result.push(nV3.clone());
  15521. result.push(nV2.clone());
  15522. break;
  15523. case 2:
  15524. if (!v1Out) {
  15525. nV1 = vertices[index].clone();
  15526. nV2 = clipVertices(nV1, vertices[index + 1]);
  15527. nV3 = clipVertices(nV1, vertices[index + 2]);
  15528. result.push(nV1);
  15529. result.push(nV2);
  15530. result.push(nV3);
  15531. }
  15532. if (!v2Out) {
  15533. nV1 = vertices[index + 1].clone();
  15534. nV2 = clipVertices(nV1, vertices[index + 2]);
  15535. nV3 = clipVertices(nV1, vertices[index]);
  15536. result.push(nV1);
  15537. result.push(nV2);
  15538. result.push(nV3);
  15539. }
  15540. if (!v3Out) {
  15541. nV1 = vertices[index + 2].clone();
  15542. nV2 = clipVertices(nV1, vertices[index]);
  15543. nV3 = clipVertices(nV1, vertices[index + 1]);
  15544. result.push(nV1);
  15545. result.push(nV2);
  15546. result.push(nV3);
  15547. }
  15548. break;
  15549. case 3:
  15550. break;
  15551. }
  15552. }
  15553. return result;
  15554. };
  15555. for (var index = 0; index < indices.length; index += 3) {
  15556. var faceVertices = new Array();
  15557. faceVertices.push(extractDecalVector3(index));
  15558. faceVertices.push(extractDecalVector3(index + 1));
  15559. faceVertices.push(extractDecalVector3(index + 2));
  15560. // Clip
  15561. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15562. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15563. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15564. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15565. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15566. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15567. if (faceVertices.length === 0) {
  15568. continue;
  15569. }
  15570. // Add UVs and get back to world
  15571. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15572. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15573. var vertex = faceVertices[vIndex];
  15574. vertexData.indices.push(currentVertexDataIndex);
  15575. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15576. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15577. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15578. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15579. currentVertexDataIndex++;
  15580. }
  15581. }
  15582. // Return mesh
  15583. var decal = new Mesh(name, sourceMesh.getScene());
  15584. vertexData.applyToMesh(decal);
  15585. decal.position = position.clone();
  15586. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15587. return decal;
  15588. };
  15589. // Tools
  15590. Mesh.MinMax = function (meshes) {
  15591. var minVector = null;
  15592. var maxVector = null;
  15593. for (var i in meshes) {
  15594. var mesh = meshes[i];
  15595. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15596. if (!minVector) {
  15597. minVector = boundingBox.minimumWorld;
  15598. maxVector = boundingBox.maximumWorld;
  15599. continue;
  15600. }
  15601. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15602. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15603. }
  15604. return {
  15605. min: minVector,
  15606. max: maxVector
  15607. };
  15608. };
  15609. Mesh.Center = function (meshesOrMinMaxVector) {
  15610. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15611. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15612. };
  15613. /**
  15614. * Merge the array of meshes into a single mesh for performance reasons.
  15615. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15616. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15617. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15618. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15619. */
  15620. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15621. if (disposeSource === void 0) { disposeSource = true; }
  15622. if (!allow32BitsIndices) {
  15623. var totalVertices = 0;
  15624. for (var index = 0; index < meshes.length; index++) {
  15625. if (meshes[index]) {
  15626. totalVertices += meshes[index].getTotalVertices();
  15627. if (totalVertices > 65536) {
  15628. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15629. return null;
  15630. }
  15631. }
  15632. }
  15633. }
  15634. // Merge
  15635. var vertexData;
  15636. var otherVertexData;
  15637. var source;
  15638. for (index = 0; index < meshes.length; index++) {
  15639. if (meshes[index]) {
  15640. meshes[index].computeWorldMatrix(true);
  15641. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15642. otherVertexData.transform(meshes[index].getWorldMatrix());
  15643. if (vertexData) {
  15644. vertexData.merge(otherVertexData);
  15645. }
  15646. else {
  15647. vertexData = otherVertexData;
  15648. source = meshes[index];
  15649. }
  15650. }
  15651. }
  15652. if (!meshSubclass) {
  15653. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15654. }
  15655. vertexData.applyToMesh(meshSubclass);
  15656. // Setting properties
  15657. meshSubclass.material = source.material;
  15658. meshSubclass.checkCollisions = source.checkCollisions;
  15659. // Cleaning
  15660. if (disposeSource) {
  15661. for (index = 0; index < meshes.length; index++) {
  15662. if (meshes[index]) {
  15663. meshes[index].dispose();
  15664. }
  15665. }
  15666. }
  15667. return meshSubclass;
  15668. };
  15669. // Consts
  15670. Mesh._FRONTSIDE = 0;
  15671. Mesh._BACKSIDE = 1;
  15672. Mesh._DOUBLESIDE = 2;
  15673. Mesh._DEFAULTSIDE = 0;
  15674. Mesh._NO_CAP = 0;
  15675. Mesh._CAP_START = 1;
  15676. Mesh._CAP_END = 2;
  15677. Mesh._CAP_ALL = 3;
  15678. return Mesh;
  15679. })(BABYLON.AbstractMesh);
  15680. BABYLON.Mesh = Mesh;
  15681. })(BABYLON || (BABYLON = {}));
  15682. //# sourceMappingURL=babylon.mesh.js.map
  15683. var BABYLON;
  15684. (function (BABYLON) {
  15685. var SubMesh = (function () {
  15686. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15687. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15688. this.materialIndex = materialIndex;
  15689. this.verticesStart = verticesStart;
  15690. this.verticesCount = verticesCount;
  15691. this.indexStart = indexStart;
  15692. this.indexCount = indexCount;
  15693. this._renderId = 0;
  15694. this._mesh = mesh;
  15695. this._renderingMesh = renderingMesh || mesh;
  15696. mesh.subMeshes.push(this);
  15697. this._trianglePlanes = [];
  15698. this._id = mesh.subMeshes.length - 1;
  15699. if (createBoundingBox) {
  15700. this.refreshBoundingInfo();
  15701. mesh.computeWorldMatrix(true);
  15702. }
  15703. }
  15704. SubMesh.prototype.getBoundingInfo = function () {
  15705. return this._boundingInfo;
  15706. };
  15707. SubMesh.prototype.getMesh = function () {
  15708. return this._mesh;
  15709. };
  15710. SubMesh.prototype.getRenderingMesh = function () {
  15711. return this._renderingMesh;
  15712. };
  15713. SubMesh.prototype.getMaterial = function () {
  15714. var rootMaterial = this._renderingMesh.material;
  15715. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15716. var multiMaterial = rootMaterial;
  15717. return multiMaterial.getSubMaterial(this.materialIndex);
  15718. }
  15719. if (!rootMaterial) {
  15720. return this._mesh.getScene().defaultMaterial;
  15721. }
  15722. return rootMaterial;
  15723. };
  15724. // Methods
  15725. SubMesh.prototype.refreshBoundingInfo = function () {
  15726. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15727. if (!data) {
  15728. this._boundingInfo = this._mesh._boundingInfo;
  15729. return;
  15730. }
  15731. var indices = this._renderingMesh.getIndices();
  15732. var extend;
  15733. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15734. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15735. }
  15736. else {
  15737. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15738. }
  15739. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15740. };
  15741. SubMesh.prototype._checkCollision = function (collider) {
  15742. return this._boundingInfo._checkCollision(collider);
  15743. };
  15744. SubMesh.prototype.updateBoundingInfo = function (world) {
  15745. if (!this._boundingInfo) {
  15746. this.refreshBoundingInfo();
  15747. }
  15748. this._boundingInfo._update(world);
  15749. };
  15750. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15751. return this._boundingInfo.isInFrustum(frustumPlanes);
  15752. };
  15753. SubMesh.prototype.render = function () {
  15754. this._renderingMesh.render(this);
  15755. };
  15756. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15757. if (!this._linesIndexBuffer) {
  15758. var linesIndices = [];
  15759. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15760. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15761. }
  15762. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15763. this.linesIndexCount = linesIndices.length;
  15764. }
  15765. return this._linesIndexBuffer;
  15766. };
  15767. SubMesh.prototype.canIntersects = function (ray) {
  15768. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15769. };
  15770. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15771. var intersectInfo = null;
  15772. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15773. var p0 = positions[indices[index]];
  15774. var p1 = positions[indices[index + 1]];
  15775. var p2 = positions[indices[index + 2]];
  15776. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15777. if (currentIntersectInfo) {
  15778. if (currentIntersectInfo.distance < 0) {
  15779. continue;
  15780. }
  15781. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15782. intersectInfo = currentIntersectInfo;
  15783. intersectInfo.faceId = index / 3;
  15784. if (fastCheck) {
  15785. break;
  15786. }
  15787. }
  15788. }
  15789. }
  15790. return intersectInfo;
  15791. };
  15792. // Clone
  15793. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15794. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15795. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15796. return result;
  15797. };
  15798. // Dispose
  15799. SubMesh.prototype.dispose = function () {
  15800. if (this._linesIndexBuffer) {
  15801. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15802. this._linesIndexBuffer = null;
  15803. }
  15804. // Remove from mesh
  15805. var index = this._mesh.subMeshes.indexOf(this);
  15806. this._mesh.subMeshes.splice(index, 1);
  15807. };
  15808. // Statics
  15809. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15810. var minVertexIndex = Number.MAX_VALUE;
  15811. var maxVertexIndex = -Number.MAX_VALUE;
  15812. renderingMesh = renderingMesh || mesh;
  15813. var indices = renderingMesh.getIndices();
  15814. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15815. var vertexIndex = indices[index];
  15816. if (vertexIndex < minVertexIndex)
  15817. minVertexIndex = vertexIndex;
  15818. if (vertexIndex > maxVertexIndex)
  15819. maxVertexIndex = vertexIndex;
  15820. }
  15821. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15822. };
  15823. return SubMesh;
  15824. })();
  15825. BABYLON.SubMesh = SubMesh;
  15826. })(BABYLON || (BABYLON = {}));
  15827. //# sourceMappingURL=babylon.subMesh.js.map
  15828. var BABYLON;
  15829. (function (BABYLON) {
  15830. var BaseTexture = (function () {
  15831. function BaseTexture(scene) {
  15832. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15833. this.hasAlpha = false;
  15834. this.getAlphaFromRGB = false;
  15835. this.level = 1;
  15836. this.isCube = false;
  15837. this.isRenderTarget = false;
  15838. this.animations = new Array();
  15839. this.coordinatesIndex = 0;
  15840. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15841. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15842. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15843. this.anisotropicFilteringLevel = 4;
  15844. this._scene = scene;
  15845. this._scene.textures.push(this);
  15846. }
  15847. BaseTexture.prototype.getScene = function () {
  15848. return this._scene;
  15849. };
  15850. BaseTexture.prototype.getTextureMatrix = function () {
  15851. return null;
  15852. };
  15853. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15854. return null;
  15855. };
  15856. BaseTexture.prototype.getInternalTexture = function () {
  15857. return this._texture;
  15858. };
  15859. BaseTexture.prototype.isReady = function () {
  15860. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15861. return true;
  15862. }
  15863. if (this._texture) {
  15864. return this._texture.isReady;
  15865. }
  15866. return false;
  15867. };
  15868. BaseTexture.prototype.getSize = function () {
  15869. if (this._texture._width) {
  15870. return { width: this._texture._width, height: this._texture._height };
  15871. }
  15872. if (this._texture._size) {
  15873. return { width: this._texture._size, height: this._texture._size };
  15874. }
  15875. return { width: 0, height: 0 };
  15876. };
  15877. BaseTexture.prototype.getBaseSize = function () {
  15878. if (!this.isReady())
  15879. return { width: 0, height: 0 };
  15880. if (this._texture._size) {
  15881. return { width: this._texture._size, height: this._texture._size };
  15882. }
  15883. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15884. };
  15885. BaseTexture.prototype.scale = function (ratio) {
  15886. };
  15887. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15888. get: function () {
  15889. return false;
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15895. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15896. for (var index = 0; index < texturesCache.length; index++) {
  15897. var texturesCacheEntry = texturesCache[index];
  15898. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15899. texturesCache.splice(index, 1);
  15900. return;
  15901. }
  15902. }
  15903. };
  15904. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15905. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15906. for (var index = 0; index < texturesCache.length; index++) {
  15907. var texturesCacheEntry = texturesCache[index];
  15908. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15909. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15910. texturesCacheEntry.references++;
  15911. return texturesCacheEntry;
  15912. }
  15913. }
  15914. }
  15915. return null;
  15916. };
  15917. BaseTexture.prototype.delayLoad = function () {
  15918. };
  15919. BaseTexture.prototype.releaseInternalTexture = function () {
  15920. if (!this._texture) {
  15921. return;
  15922. }
  15923. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15924. this._texture.references--;
  15925. // Final reference ?
  15926. if (this._texture.references === 0) {
  15927. var index = texturesCache.indexOf(this._texture);
  15928. texturesCache.splice(index, 1);
  15929. this._scene.getEngine()._releaseTexture(this._texture);
  15930. delete this._texture;
  15931. }
  15932. };
  15933. BaseTexture.prototype.clone = function () {
  15934. return null;
  15935. };
  15936. BaseTexture.prototype.dispose = function () {
  15937. // Remove from scene
  15938. var index = this._scene.textures.indexOf(this);
  15939. if (index >= 0) {
  15940. this._scene.textures.splice(index, 1);
  15941. }
  15942. if (this._texture === undefined) {
  15943. return;
  15944. }
  15945. this.releaseInternalTexture();
  15946. // Callback
  15947. if (this.onDispose) {
  15948. this.onDispose();
  15949. }
  15950. };
  15951. return BaseTexture;
  15952. })();
  15953. BABYLON.BaseTexture = BaseTexture;
  15954. })(BABYLON || (BABYLON = {}));
  15955. //# sourceMappingURL=babylon.baseTexture.js.map
  15956. var __extends = this.__extends || function (d, b) {
  15957. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15958. function __() { this.constructor = d; }
  15959. __.prototype = b.prototype;
  15960. d.prototype = new __();
  15961. };
  15962. var BABYLON;
  15963. (function (BABYLON) {
  15964. var Texture = (function (_super) {
  15965. __extends(Texture, _super);
  15966. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  15967. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15968. if (onLoad === void 0) { onLoad = null; }
  15969. if (onError === void 0) { onError = null; }
  15970. if (buffer === void 0) { buffer = null; }
  15971. if (deleteBuffer === void 0) { deleteBuffer = false; }
  15972. _super.call(this, scene);
  15973. this.uOffset = 0;
  15974. this.vOffset = 0;
  15975. this.uScale = 1.0;
  15976. this.vScale = 1.0;
  15977. this.uAng = 0;
  15978. this.vAng = 0;
  15979. this.wAng = 0;
  15980. this.name = url;
  15981. this.url = url;
  15982. this._noMipmap = noMipmap;
  15983. this._invertY = invertY;
  15984. this._samplingMode = samplingMode;
  15985. this._buffer = buffer;
  15986. this._deleteBuffer = deleteBuffer;
  15987. if (!url) {
  15988. return;
  15989. }
  15990. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  15991. if (!this._texture) {
  15992. if (!scene.useDelayedTextureLoading) {
  15993. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  15994. if (deleteBuffer) {
  15995. delete this._buffer;
  15996. }
  15997. }
  15998. else {
  15999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16000. }
  16001. }
  16002. else {
  16003. BABYLON.Tools.SetImmediate(function () {
  16004. if (onLoad) {
  16005. onLoad();
  16006. }
  16007. });
  16008. }
  16009. }
  16010. Texture.prototype.delayLoad = function () {
  16011. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16012. return;
  16013. }
  16014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16015. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16016. if (!this._texture) {
  16017. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16018. if (this._deleteBuffer) {
  16019. delete this._buffer;
  16020. }
  16021. }
  16022. };
  16023. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16024. if (!this._texture) {
  16025. return;
  16026. }
  16027. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16028. };
  16029. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16030. x -= this.uOffset + 0.5;
  16031. y -= this.vOffset + 0.5;
  16032. z -= 0.5;
  16033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16034. t.x *= this.uScale;
  16035. t.y *= this.vScale;
  16036. t.x += 0.5;
  16037. t.y += 0.5;
  16038. t.z += 0.5;
  16039. };
  16040. Texture.prototype.getTextureMatrix = function () {
  16041. 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) {
  16042. return this._cachedTextureMatrix;
  16043. }
  16044. this._cachedUOffset = this.uOffset;
  16045. this._cachedVOffset = this.vOffset;
  16046. this._cachedUScale = this.uScale;
  16047. this._cachedVScale = this.vScale;
  16048. this._cachedUAng = this.uAng;
  16049. this._cachedVAng = this.vAng;
  16050. this._cachedWAng = this.wAng;
  16051. if (!this._cachedTextureMatrix) {
  16052. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16053. this._rowGenerationMatrix = new BABYLON.Matrix();
  16054. this._t0 = BABYLON.Vector3.Zero();
  16055. this._t1 = BABYLON.Vector3.Zero();
  16056. this._t2 = BABYLON.Vector3.Zero();
  16057. }
  16058. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16059. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16060. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16061. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16062. this._t1.subtractInPlace(this._t0);
  16063. this._t2.subtractInPlace(this._t0);
  16064. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16065. this._cachedTextureMatrix.m[0] = this._t1.x;
  16066. this._cachedTextureMatrix.m[1] = this._t1.y;
  16067. this._cachedTextureMatrix.m[2] = this._t1.z;
  16068. this._cachedTextureMatrix.m[4] = this._t2.x;
  16069. this._cachedTextureMatrix.m[5] = this._t2.y;
  16070. this._cachedTextureMatrix.m[6] = this._t2.z;
  16071. this._cachedTextureMatrix.m[8] = this._t0.x;
  16072. this._cachedTextureMatrix.m[9] = this._t0.y;
  16073. this._cachedTextureMatrix.m[10] = this._t0.z;
  16074. return this._cachedTextureMatrix;
  16075. };
  16076. Texture.prototype.getReflectionTextureMatrix = function () {
  16077. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  16078. return this._cachedTextureMatrix;
  16079. }
  16080. if (!this._cachedTextureMatrix) {
  16081. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16082. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16083. }
  16084. this._cachedCoordinatesMode = this.coordinatesMode;
  16085. switch (this.coordinatesMode) {
  16086. case Texture.SPHERICAL_MODE:
  16087. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16088. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16089. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16090. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16091. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16092. break;
  16093. case Texture.PLANAR_MODE:
  16094. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16095. this._cachedTextureMatrix[0] = this.uScale;
  16096. this._cachedTextureMatrix[5] = this.vScale;
  16097. this._cachedTextureMatrix[12] = this.uOffset;
  16098. this._cachedTextureMatrix[13] = this.vOffset;
  16099. break;
  16100. case Texture.PROJECTION_MODE:
  16101. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16102. this._projectionModeMatrix.m[0] = 0.5;
  16103. this._projectionModeMatrix.m[5] = -0.5;
  16104. this._projectionModeMatrix.m[10] = 0.0;
  16105. this._projectionModeMatrix.m[12] = 0.5;
  16106. this._projectionModeMatrix.m[13] = 0.5;
  16107. this._projectionModeMatrix.m[14] = 1.0;
  16108. this._projectionModeMatrix.m[15] = 1.0;
  16109. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16110. break;
  16111. default:
  16112. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16113. break;
  16114. }
  16115. return this._cachedTextureMatrix;
  16116. };
  16117. Texture.prototype.clone = function () {
  16118. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16119. // Base texture
  16120. newTexture.hasAlpha = this.hasAlpha;
  16121. newTexture.level = this.level;
  16122. newTexture.wrapU = this.wrapU;
  16123. newTexture.wrapV = this.wrapV;
  16124. newTexture.coordinatesIndex = this.coordinatesIndex;
  16125. newTexture.coordinatesMode = this.coordinatesMode;
  16126. // Texture
  16127. newTexture.uOffset = this.uOffset;
  16128. newTexture.vOffset = this.vOffset;
  16129. newTexture.uScale = this.uScale;
  16130. newTexture.vScale = this.vScale;
  16131. newTexture.uAng = this.uAng;
  16132. newTexture.vAng = this.vAng;
  16133. newTexture.wAng = this.wAng;
  16134. return newTexture;
  16135. };
  16136. // Statics
  16137. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16138. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16139. if (onLoad === void 0) { onLoad = null; }
  16140. if (onError === void 0) { onError = null; }
  16141. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16142. };
  16143. // Constants
  16144. Texture.NEAREST_SAMPLINGMODE = 1;
  16145. Texture.BILINEAR_SAMPLINGMODE = 2;
  16146. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16147. Texture.EXPLICIT_MODE = 0;
  16148. Texture.SPHERICAL_MODE = 1;
  16149. Texture.PLANAR_MODE = 2;
  16150. Texture.CUBIC_MODE = 3;
  16151. Texture.PROJECTION_MODE = 4;
  16152. Texture.SKYBOX_MODE = 5;
  16153. Texture.CLAMP_ADDRESSMODE = 0;
  16154. Texture.WRAP_ADDRESSMODE = 1;
  16155. Texture.MIRROR_ADDRESSMODE = 2;
  16156. return Texture;
  16157. })(BABYLON.BaseTexture);
  16158. BABYLON.Texture = Texture;
  16159. })(BABYLON || (BABYLON = {}));
  16160. //# sourceMappingURL=babylon.texture.js.map
  16161. var __extends = this.__extends || function (d, b) {
  16162. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16163. function __() { this.constructor = d; }
  16164. __.prototype = b.prototype;
  16165. d.prototype = new __();
  16166. };
  16167. var BABYLON;
  16168. (function (BABYLON) {
  16169. var CubeTexture = (function (_super) {
  16170. __extends(CubeTexture, _super);
  16171. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16172. _super.call(this, scene);
  16173. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16174. this.name = rootUrl;
  16175. this.url = rootUrl;
  16176. this._noMipmap = noMipmap;
  16177. this.hasAlpha = false;
  16178. this._texture = this._getFromCache(rootUrl, noMipmap);
  16179. if (!extensions) {
  16180. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16181. }
  16182. this._extensions = extensions;
  16183. if (!this._texture) {
  16184. if (!scene.useDelayedTextureLoading) {
  16185. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16186. }
  16187. else {
  16188. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16189. }
  16190. }
  16191. this.isCube = true;
  16192. this._textureMatrix = BABYLON.Matrix.Identity();
  16193. }
  16194. CubeTexture.prototype.clone = function () {
  16195. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16196. // Base texture
  16197. newTexture.level = this.level;
  16198. newTexture.wrapU = this.wrapU;
  16199. newTexture.wrapV = this.wrapV;
  16200. newTexture.coordinatesIndex = this.coordinatesIndex;
  16201. newTexture.coordinatesMode = this.coordinatesMode;
  16202. return newTexture;
  16203. };
  16204. // Methods
  16205. CubeTexture.prototype.delayLoad = function () {
  16206. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16207. return;
  16208. }
  16209. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16210. this._texture = this._getFromCache(this.url, this._noMipmap);
  16211. if (!this._texture) {
  16212. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16213. }
  16214. };
  16215. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16216. return this._textureMatrix;
  16217. };
  16218. return CubeTexture;
  16219. })(BABYLON.BaseTexture);
  16220. BABYLON.CubeTexture = CubeTexture;
  16221. })(BABYLON || (BABYLON = {}));
  16222. //# sourceMappingURL=babylon.cubeTexture.js.map
  16223. var __extends = this.__extends || function (d, b) {
  16224. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16225. function __() { this.constructor = d; }
  16226. __.prototype = b.prototype;
  16227. d.prototype = new __();
  16228. };
  16229. var BABYLON;
  16230. (function (BABYLON) {
  16231. var RenderTargetTexture = (function (_super) {
  16232. __extends(RenderTargetTexture, _super);
  16233. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16234. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16235. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16236. _super.call(this, null, scene, !generateMipMaps);
  16237. this.renderList = new Array();
  16238. this.renderParticles = true;
  16239. this.renderSprites = false;
  16240. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16241. this._currentRefreshId = -1;
  16242. this._refreshRate = 1;
  16243. this.name = name;
  16244. this.isRenderTarget = true;
  16245. this._size = size;
  16246. this._generateMipMaps = generateMipMaps;
  16247. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16248. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16249. // Rendering groups
  16250. this._renderingManager = new BABYLON.RenderingManager(scene);
  16251. }
  16252. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16253. this._currentRefreshId = -1;
  16254. };
  16255. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16256. get: function () {
  16257. return this._refreshRate;
  16258. },
  16259. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16260. set: function (value) {
  16261. this._refreshRate = value;
  16262. this.resetRefreshCounter();
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. RenderTargetTexture.prototype._shouldRender = function () {
  16268. if (this._currentRefreshId === -1) {
  16269. this._currentRefreshId = 1;
  16270. return true;
  16271. }
  16272. if (this.refreshRate === this._currentRefreshId) {
  16273. this._currentRefreshId = 1;
  16274. return true;
  16275. }
  16276. this._currentRefreshId++;
  16277. return false;
  16278. };
  16279. RenderTargetTexture.prototype.isReady = function () {
  16280. if (!this.getScene().renderTargetsEnabled) {
  16281. return false;
  16282. }
  16283. return _super.prototype.isReady.call(this);
  16284. };
  16285. RenderTargetTexture.prototype.getRenderSize = function () {
  16286. return this._size;
  16287. };
  16288. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16289. get: function () {
  16290. return true;
  16291. },
  16292. enumerable: true,
  16293. configurable: true
  16294. });
  16295. RenderTargetTexture.prototype.scale = function (ratio) {
  16296. var newSize = this._size * ratio;
  16297. this.resize(newSize, this._generateMipMaps);
  16298. };
  16299. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16300. this.releaseInternalTexture();
  16301. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16302. };
  16303. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16304. var scene = this.getScene();
  16305. var engine = scene.getEngine();
  16306. if (this._waitingRenderList) {
  16307. this.renderList = [];
  16308. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16309. var id = this._waitingRenderList[index];
  16310. this.renderList.push(scene.getMeshByID(id));
  16311. }
  16312. delete this._waitingRenderList;
  16313. }
  16314. if (this.renderList && this.renderList.length === 0) {
  16315. return;
  16316. }
  16317. // Bind
  16318. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16319. engine.bindFramebuffer(this._texture);
  16320. }
  16321. this._renderingManager.reset();
  16322. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16323. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16324. var mesh = currentRenderList[meshIndex];
  16325. if (mesh) {
  16326. if (!mesh.isReady()) {
  16327. // Reset _currentRefreshId
  16328. this.resetRefreshCounter();
  16329. continue;
  16330. }
  16331. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16332. mesh._activate(scene.getRenderId());
  16333. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16334. var subMesh = mesh.subMeshes[subIndex];
  16335. scene._activeIndices += subMesh.indexCount;
  16336. this._renderingManager.dispatch(subMesh);
  16337. }
  16338. }
  16339. }
  16340. }
  16341. if (this.onBeforeRender) {
  16342. this.onBeforeRender();
  16343. }
  16344. // Clear
  16345. if (this.onClear) {
  16346. this.onClear(engine);
  16347. }
  16348. else {
  16349. engine.clear(scene.clearColor, true, true);
  16350. }
  16351. if (!this._doNotChangeAspectRatio) {
  16352. scene.updateTransformMatrix(true);
  16353. }
  16354. // Render
  16355. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16356. if (useCameraPostProcess) {
  16357. scene.postProcessManager._finalizeFrame(false, this._texture);
  16358. }
  16359. if (!this._doNotChangeAspectRatio) {
  16360. scene.updateTransformMatrix(true);
  16361. }
  16362. if (this.onAfterRender) {
  16363. this.onAfterRender();
  16364. }
  16365. // Dump ?
  16366. if (dumpForDebug) {
  16367. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16368. }
  16369. // Unbind
  16370. engine.unBindFramebuffer(this._texture);
  16371. if (this.onAfterUnbind) {
  16372. this.onAfterUnbind();
  16373. }
  16374. };
  16375. RenderTargetTexture.prototype.clone = function () {
  16376. var textureSize = this.getSize();
  16377. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16378. // Base texture
  16379. newTexture.hasAlpha = this.hasAlpha;
  16380. newTexture.level = this.level;
  16381. // RenderTarget Texture
  16382. newTexture.coordinatesMode = this.coordinatesMode;
  16383. newTexture.renderList = this.renderList.slice(0);
  16384. return newTexture;
  16385. };
  16386. return RenderTargetTexture;
  16387. })(BABYLON.Texture);
  16388. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16391. var __extends = this.__extends || function (d, b) {
  16392. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16393. function __() { this.constructor = d; }
  16394. __.prototype = b.prototype;
  16395. d.prototype = new __();
  16396. };
  16397. var BABYLON;
  16398. (function (BABYLON) {
  16399. var ProceduralTexture = (function (_super) {
  16400. __extends(ProceduralTexture, _super);
  16401. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16402. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16403. _super.call(this, null, scene, !generateMipMaps);
  16404. this._currentRefreshId = -1;
  16405. this._refreshRate = 1;
  16406. this._vertexDeclaration = [2];
  16407. this._vertexStrideSize = 2 * 4;
  16408. this._uniforms = new Array();
  16409. this._samplers = new Array();
  16410. this._textures = new Array();
  16411. this._floats = new Array();
  16412. this._floatsArrays = {};
  16413. this._colors3 = new Array();
  16414. this._colors4 = new Array();
  16415. this._vectors2 = new Array();
  16416. this._vectors3 = new Array();
  16417. this._matrices = new Array();
  16418. this._fallbackTextureUsed = false;
  16419. scene._proceduralTextures.push(this);
  16420. this.name = name;
  16421. this.isRenderTarget = true;
  16422. this._size = size;
  16423. this._generateMipMaps = generateMipMaps;
  16424. this.setFragment(fragment);
  16425. this._fallbackTexture = fallbackTexture;
  16426. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16427. // VBO
  16428. var vertices = [];
  16429. vertices.push(1, 1);
  16430. vertices.push(-1, 1);
  16431. vertices.push(-1, -1);
  16432. vertices.push(1, -1);
  16433. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16434. // Indices
  16435. var indices = [];
  16436. indices.push(0);
  16437. indices.push(1);
  16438. indices.push(2);
  16439. indices.push(0);
  16440. indices.push(2);
  16441. indices.push(3);
  16442. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16443. }
  16444. ProceduralTexture.prototype.reset = function () {
  16445. if (this._effect === undefined) {
  16446. return;
  16447. }
  16448. var engine = this.getScene().getEngine();
  16449. engine._releaseEffect(this._effect);
  16450. };
  16451. ProceduralTexture.prototype.isReady = function () {
  16452. var _this = this;
  16453. var engine = this.getScene().getEngine();
  16454. var shaders;
  16455. if (!this._fragment) {
  16456. return false;
  16457. }
  16458. if (this._fallbackTextureUsed) {
  16459. return true;
  16460. }
  16461. if (this._fragment.fragmentElement !== undefined) {
  16462. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16463. }
  16464. else {
  16465. shaders = { vertex: "procedural", fragment: this._fragment };
  16466. }
  16467. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16468. _this.releaseInternalTexture();
  16469. if (_this._fallbackTexture) {
  16470. _this._texture = _this._fallbackTexture._texture;
  16471. _this._texture.references++;
  16472. }
  16473. _this._fallbackTextureUsed = true;
  16474. });
  16475. return this._effect.isReady();
  16476. };
  16477. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16478. this._currentRefreshId = -1;
  16479. };
  16480. ProceduralTexture.prototype.setFragment = function (fragment) {
  16481. this._fragment = fragment;
  16482. };
  16483. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16484. get: function () {
  16485. return this._refreshRate;
  16486. },
  16487. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16488. set: function (value) {
  16489. this._refreshRate = value;
  16490. this.resetRefreshCounter();
  16491. },
  16492. enumerable: true,
  16493. configurable: true
  16494. });
  16495. ProceduralTexture.prototype._shouldRender = function () {
  16496. if (!this.isReady() || !this._texture) {
  16497. return false;
  16498. }
  16499. if (this._fallbackTextureUsed) {
  16500. return false;
  16501. }
  16502. if (this._currentRefreshId === -1) {
  16503. this._currentRefreshId = 1;
  16504. return true;
  16505. }
  16506. if (this.refreshRate === this._currentRefreshId) {
  16507. this._currentRefreshId = 1;
  16508. return true;
  16509. }
  16510. this._currentRefreshId++;
  16511. return false;
  16512. };
  16513. ProceduralTexture.prototype.getRenderSize = function () {
  16514. return this._size;
  16515. };
  16516. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16517. if (this._fallbackTextureUsed) {
  16518. return;
  16519. }
  16520. this.releaseInternalTexture();
  16521. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16522. };
  16523. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16524. if (this._uniforms.indexOf(uniformName) === -1) {
  16525. this._uniforms.push(uniformName);
  16526. }
  16527. };
  16528. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16529. if (this._samplers.indexOf(name) === -1) {
  16530. this._samplers.push(name);
  16531. }
  16532. this._textures[name] = texture;
  16533. return this;
  16534. };
  16535. ProceduralTexture.prototype.setFloat = function (name, value) {
  16536. this._checkUniform(name);
  16537. this._floats[name] = value;
  16538. return this;
  16539. };
  16540. ProceduralTexture.prototype.setFloats = function (name, value) {
  16541. this._checkUniform(name);
  16542. this._floatsArrays[name] = value;
  16543. return this;
  16544. };
  16545. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16546. this._checkUniform(name);
  16547. this._colors3[name] = value;
  16548. return this;
  16549. };
  16550. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16551. this._checkUniform(name);
  16552. this._colors4[name] = value;
  16553. return this;
  16554. };
  16555. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16556. this._checkUniform(name);
  16557. this._vectors2[name] = value;
  16558. return this;
  16559. };
  16560. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16561. this._checkUniform(name);
  16562. this._vectors3[name] = value;
  16563. return this;
  16564. };
  16565. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16566. this._checkUniform(name);
  16567. this._matrices[name] = value;
  16568. return this;
  16569. };
  16570. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16571. var scene = this.getScene();
  16572. var engine = scene.getEngine();
  16573. engine.bindFramebuffer(this._texture);
  16574. // Clear
  16575. engine.clear(scene.clearColor, true, true);
  16576. // Render
  16577. engine.enableEffect(this._effect);
  16578. engine.setState(false);
  16579. for (var name in this._textures) {
  16580. this._effect.setTexture(name, this._textures[name]);
  16581. }
  16582. for (name in this._floats) {
  16583. this._effect.setFloat(name, this._floats[name]);
  16584. }
  16585. for (name in this._floatsArrays) {
  16586. this._effect.setArray(name, this._floatsArrays[name]);
  16587. }
  16588. for (name in this._colors3) {
  16589. this._effect.setColor3(name, this._colors3[name]);
  16590. }
  16591. for (name in this._colors4) {
  16592. var color = this._colors4[name];
  16593. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16594. }
  16595. for (name in this._vectors2) {
  16596. this._effect.setVector2(name, this._vectors2[name]);
  16597. }
  16598. for (name in this._vectors3) {
  16599. this._effect.setVector3(name, this._vectors3[name]);
  16600. }
  16601. for (name in this._matrices) {
  16602. this._effect.setMatrix(name, this._matrices[name]);
  16603. }
  16604. // VBOs
  16605. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16606. // Draw order
  16607. engine.draw(true, 0, 6);
  16608. // Unbind
  16609. engine.unBindFramebuffer(this._texture);
  16610. };
  16611. ProceduralTexture.prototype.clone = function () {
  16612. var textureSize = this.getSize();
  16613. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16614. // Base texture
  16615. newTexture.hasAlpha = this.hasAlpha;
  16616. newTexture.level = this.level;
  16617. // RenderTarget Texture
  16618. newTexture.coordinatesMode = this.coordinatesMode;
  16619. return newTexture;
  16620. };
  16621. ProceduralTexture.prototype.dispose = function () {
  16622. var index = this.getScene()._proceduralTextures.indexOf(this);
  16623. if (index >= 0) {
  16624. this.getScene()._proceduralTextures.splice(index, 1);
  16625. }
  16626. _super.prototype.dispose.call(this);
  16627. };
  16628. return ProceduralTexture;
  16629. })(BABYLON.Texture);
  16630. BABYLON.ProceduralTexture = ProceduralTexture;
  16631. })(BABYLON || (BABYLON = {}));
  16632. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16633. var __extends = this.__extends || function (d, b) {
  16634. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16635. function __() { this.constructor = d; }
  16636. __.prototype = b.prototype;
  16637. d.prototype = new __();
  16638. };
  16639. var BABYLON;
  16640. (function (BABYLON) {
  16641. var MirrorTexture = (function (_super) {
  16642. __extends(MirrorTexture, _super);
  16643. function MirrorTexture(name, size, scene, generateMipMaps) {
  16644. var _this = this;
  16645. _super.call(this, name, size, scene, generateMipMaps, true);
  16646. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16647. this._transformMatrix = BABYLON.Matrix.Zero();
  16648. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16649. this.onBeforeRender = function () {
  16650. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16651. _this._savedViewMatrix = scene.getViewMatrix();
  16652. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16653. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16654. scene.clipPlane = _this.mirrorPlane;
  16655. scene.getEngine().cullBackFaces = false;
  16656. };
  16657. this.onAfterRender = function () {
  16658. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16659. scene.getEngine().cullBackFaces = true;
  16660. delete scene.clipPlane;
  16661. };
  16662. }
  16663. MirrorTexture.prototype.clone = function () {
  16664. var textureSize = this.getSize();
  16665. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16666. // Base texture
  16667. newTexture.hasAlpha = this.hasAlpha;
  16668. newTexture.level = this.level;
  16669. // Mirror Texture
  16670. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16671. newTexture.renderList = this.renderList.slice(0);
  16672. return newTexture;
  16673. };
  16674. return MirrorTexture;
  16675. })(BABYLON.RenderTargetTexture);
  16676. BABYLON.MirrorTexture = MirrorTexture;
  16677. })(BABYLON || (BABYLON = {}));
  16678. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16679. var __extends = this.__extends || function (d, b) {
  16680. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16681. function __() { this.constructor = d; }
  16682. __.prototype = b.prototype;
  16683. d.prototype = new __();
  16684. };
  16685. var BABYLON;
  16686. (function (BABYLON) {
  16687. var DynamicTexture = (function (_super) {
  16688. __extends(DynamicTexture, _super);
  16689. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16690. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16691. _super.call(this, null, scene, !generateMipMaps);
  16692. this.name = name;
  16693. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16694. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16695. this._generateMipMaps = generateMipMaps;
  16696. if (options.getContext) {
  16697. this._canvas = options;
  16698. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16699. }
  16700. else {
  16701. this._canvas = document.createElement("canvas");
  16702. if (options.width) {
  16703. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16704. }
  16705. else {
  16706. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16707. }
  16708. }
  16709. var textureSize = this.getSize();
  16710. this._canvas.width = textureSize.width;
  16711. this._canvas.height = textureSize.height;
  16712. this._context = this._canvas.getContext("2d");
  16713. }
  16714. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16715. get: function () {
  16716. return true;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. DynamicTexture.prototype.scale = function (ratio) {
  16722. var textureSize = this.getSize();
  16723. textureSize.width *= ratio;
  16724. textureSize.height *= ratio;
  16725. this._canvas.width = textureSize.width;
  16726. this._canvas.height = textureSize.height;
  16727. this.releaseInternalTexture();
  16728. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16729. };
  16730. DynamicTexture.prototype.getContext = function () {
  16731. return this._context;
  16732. };
  16733. DynamicTexture.prototype.clear = function () {
  16734. var size = this.getSize();
  16735. this._context.fillRect(0, 0, size.width, size.height);
  16736. };
  16737. DynamicTexture.prototype.update = function (invertY) {
  16738. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16739. };
  16740. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16741. if (update === void 0) { update = true; }
  16742. var size = this.getSize();
  16743. if (clearColor) {
  16744. this._context.fillStyle = clearColor;
  16745. this._context.fillRect(0, 0, size.width, size.height);
  16746. }
  16747. this._context.font = font;
  16748. if (x === null) {
  16749. var textSize = this._context.measureText(text);
  16750. x = (size.width - textSize.width) / 2;
  16751. }
  16752. this._context.fillStyle = color;
  16753. this._context.fillText(text, x, y);
  16754. if (update) {
  16755. this.update(invertY);
  16756. }
  16757. };
  16758. DynamicTexture.prototype.clone = function () {
  16759. var textureSize = this.getSize();
  16760. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16761. // Base texture
  16762. newTexture.hasAlpha = this.hasAlpha;
  16763. newTexture.level = this.level;
  16764. // Dynamic Texture
  16765. newTexture.wrapU = this.wrapU;
  16766. newTexture.wrapV = this.wrapV;
  16767. return newTexture;
  16768. };
  16769. return DynamicTexture;
  16770. })(BABYLON.Texture);
  16771. BABYLON.DynamicTexture = DynamicTexture;
  16772. })(BABYLON || (BABYLON = {}));
  16773. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16774. var __extends = this.__extends || function (d, b) {
  16775. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16776. function __() { this.constructor = d; }
  16777. __.prototype = b.prototype;
  16778. d.prototype = new __();
  16779. };
  16780. var BABYLON;
  16781. (function (BABYLON) {
  16782. var VideoTexture = (function (_super) {
  16783. __extends(VideoTexture, _super);
  16784. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16785. var _this = this;
  16786. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16787. if (invertY === void 0) { invertY = false; }
  16788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16789. _super.call(this, null, scene, !generateMipMaps, invertY);
  16790. this._autoLaunch = true;
  16791. this.name = name;
  16792. this.video = document.createElement("video");
  16793. this.video.autoplay = false;
  16794. this.video.loop = true;
  16795. this.video.addEventListener("canplaythrough", function () {
  16796. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16797. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16798. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16799. }
  16800. else {
  16801. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16802. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16803. generateMipMaps = false;
  16804. }
  16805. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16806. _this._texture.isReady = true;
  16807. });
  16808. urls.forEach(function (url) {
  16809. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16810. var source = document.createElement("source");
  16811. source.src = url;
  16812. _this.video.appendChild(source);
  16813. });
  16814. this._lastUpdate = BABYLON.Tools.Now;
  16815. }
  16816. VideoTexture.prototype.update = function () {
  16817. if (this._autoLaunch) {
  16818. this._autoLaunch = false;
  16819. this.video.play();
  16820. }
  16821. var now = BABYLON.Tools.Now;
  16822. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16823. return false;
  16824. }
  16825. this._lastUpdate = now;
  16826. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16827. return true;
  16828. };
  16829. return VideoTexture;
  16830. })(BABYLON.Texture);
  16831. BABYLON.VideoTexture = VideoTexture;
  16832. })(BABYLON || (BABYLON = {}));
  16833. //# sourceMappingURL=babylon.videoTexture.js.map
  16834. var __extends = this.__extends || function (d, b) {
  16835. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16836. function __() { this.constructor = d; }
  16837. __.prototype = b.prototype;
  16838. d.prototype = new __();
  16839. };
  16840. var BABYLON;
  16841. (function (BABYLON) {
  16842. var CustomProceduralTexture = (function (_super) {
  16843. __extends(CustomProceduralTexture, _super);
  16844. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16845. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16846. this._animate = true;
  16847. this._time = 0;
  16848. this._texturePath = texturePath;
  16849. //Try to load json
  16850. this.loadJson(texturePath);
  16851. this.refreshRate = 1;
  16852. }
  16853. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16854. var _this = this;
  16855. var that = this;
  16856. function noConfigFile() {
  16857. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16858. try {
  16859. that.setFragment(that._texturePath);
  16860. }
  16861. catch (ex) {
  16862. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16863. }
  16864. }
  16865. var configFileUrl = jsonUrl + "/config.json";
  16866. var xhr = new XMLHttpRequest();
  16867. xhr.open("GET", configFileUrl, true);
  16868. xhr.addEventListener("load", function () {
  16869. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16870. try {
  16871. _this._config = JSON.parse(xhr.response);
  16872. _this.updateShaderUniforms();
  16873. _this.updateTextures();
  16874. _this.setFragment(_this._texturePath + "/custom");
  16875. _this._animate = _this._config.animate;
  16876. _this.refreshRate = _this._config.refreshrate;
  16877. }
  16878. catch (ex) {
  16879. noConfigFile();
  16880. }
  16881. }
  16882. else {
  16883. noConfigFile();
  16884. }
  16885. }, false);
  16886. xhr.addEventListener("error", function () {
  16887. noConfigFile();
  16888. }, false);
  16889. try {
  16890. xhr.send();
  16891. }
  16892. catch (ex) {
  16893. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16894. }
  16895. };
  16896. CustomProceduralTexture.prototype.isReady = function () {
  16897. if (!_super.prototype.isReady.call(this)) {
  16898. return false;
  16899. }
  16900. for (var name in this._textures) {
  16901. var texture = this._textures[name];
  16902. if (!texture.isReady()) {
  16903. return false;
  16904. }
  16905. }
  16906. return true;
  16907. };
  16908. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16909. if (this._animate) {
  16910. this._time += this.getScene().getAnimationRatio() * 0.03;
  16911. this.updateShaderUniforms();
  16912. }
  16913. _super.prototype.render.call(this, useCameraPostProcess);
  16914. };
  16915. CustomProceduralTexture.prototype.updateTextures = function () {
  16916. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16917. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16918. }
  16919. };
  16920. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16921. if (this._config) {
  16922. for (var j = 0; j < this._config.uniforms.length; j++) {
  16923. var uniform = this._config.uniforms[j];
  16924. switch (uniform.type) {
  16925. case "float":
  16926. this.setFloat(uniform.name, uniform.value);
  16927. break;
  16928. case "color3":
  16929. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16930. break;
  16931. case "color4":
  16932. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  16933. break;
  16934. case "vector2":
  16935. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  16936. break;
  16937. case "vector3":
  16938. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  16939. break;
  16940. }
  16941. }
  16942. }
  16943. this.setFloat("time", this._time);
  16944. };
  16945. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  16946. get: function () {
  16947. return this._animate;
  16948. },
  16949. set: function (value) {
  16950. this._animate = value;
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. return CustomProceduralTexture;
  16956. })(BABYLON.ProceduralTexture);
  16957. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  16958. })(BABYLON || (BABYLON = {}));
  16959. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  16960. var __extends = this.__extends || function (d, b) {
  16961. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16962. function __() { this.constructor = d; }
  16963. __.prototype = b.prototype;
  16964. d.prototype = new __();
  16965. };
  16966. var BABYLON;
  16967. (function (BABYLON) {
  16968. var WoodProceduralTexture = (function (_super) {
  16969. __extends(WoodProceduralTexture, _super);
  16970. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16971. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  16972. this._ampScale = 100.0;
  16973. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  16974. this.updateShaderUniforms();
  16975. this.refreshRate = 0;
  16976. }
  16977. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  16978. this.setFloat("ampScale", this._ampScale);
  16979. this.setColor3("woodColor", this._woodColor);
  16980. };
  16981. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  16982. get: function () {
  16983. return this._ampScale;
  16984. },
  16985. set: function (value) {
  16986. this._ampScale = value;
  16987. this.updateShaderUniforms();
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  16993. get: function () {
  16994. return this._woodColor;
  16995. },
  16996. set: function (value) {
  16997. this._woodColor = value;
  16998. this.updateShaderUniforms();
  16999. },
  17000. enumerable: true,
  17001. configurable: true
  17002. });
  17003. return WoodProceduralTexture;
  17004. })(BABYLON.ProceduralTexture);
  17005. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17006. var FireProceduralTexture = (function (_super) {
  17007. __extends(FireProceduralTexture, _super);
  17008. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17009. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17010. this._time = 0.0;
  17011. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17012. this._autoGenerateTime = true;
  17013. this._alphaThreshold = 0.5;
  17014. this._fireColors = FireProceduralTexture.RedFireColors;
  17015. this.updateShaderUniforms();
  17016. this.refreshRate = 1;
  17017. }
  17018. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17019. this.setFloat("time", this._time);
  17020. this.setVector2("speed", this._speed);
  17021. this.setColor3("c1", this._fireColors[0]);
  17022. this.setColor3("c2", this._fireColors[1]);
  17023. this.setColor3("c3", this._fireColors[2]);
  17024. this.setColor3("c4", this._fireColors[3]);
  17025. this.setColor3("c5", this._fireColors[4]);
  17026. this.setColor3("c6", this._fireColors[5]);
  17027. this.setFloat("alphaThreshold", this._alphaThreshold);
  17028. };
  17029. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17030. if (this._autoGenerateTime) {
  17031. this._time += this.getScene().getAnimationRatio() * 0.03;
  17032. this.updateShaderUniforms();
  17033. }
  17034. _super.prototype.render.call(this, useCameraPostProcess);
  17035. };
  17036. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17037. get: function () {
  17038. return [
  17039. new BABYLON.Color3(0.5, 0.0, 1.0),
  17040. new BABYLON.Color3(0.9, 0.0, 1.0),
  17041. new BABYLON.Color3(0.2, 0.0, 1.0),
  17042. new BABYLON.Color3(1.0, 0.9, 1.0),
  17043. new BABYLON.Color3(0.1, 0.1, 1.0),
  17044. new BABYLON.Color3(0.9, 0.9, 1.0)
  17045. ];
  17046. },
  17047. enumerable: true,
  17048. configurable: true
  17049. });
  17050. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17051. get: function () {
  17052. return [
  17053. new BABYLON.Color3(0.5, 1.0, 0.0),
  17054. new BABYLON.Color3(0.5, 1.0, 0.0),
  17055. new BABYLON.Color3(0.3, 0.4, 0.0),
  17056. new BABYLON.Color3(0.5, 1.0, 0.0),
  17057. new BABYLON.Color3(0.2, 0.0, 0.0),
  17058. new BABYLON.Color3(0.5, 1.0, 0.0)
  17059. ];
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17065. get: function () {
  17066. return [
  17067. new BABYLON.Color3(0.5, 0.0, 0.1),
  17068. new BABYLON.Color3(0.9, 0.0, 0.0),
  17069. new BABYLON.Color3(0.2, 0.0, 0.0),
  17070. new BABYLON.Color3(1.0, 0.9, 0.0),
  17071. new BABYLON.Color3(0.1, 0.1, 0.1),
  17072. new BABYLON.Color3(0.9, 0.9, 0.9)
  17073. ];
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17079. get: function () {
  17080. return [
  17081. new BABYLON.Color3(0.1, 0.0, 0.5),
  17082. new BABYLON.Color3(0.0, 0.0, 0.5),
  17083. new BABYLON.Color3(0.1, 0.0, 0.2),
  17084. new BABYLON.Color3(0.0, 0.0, 1.0),
  17085. new BABYLON.Color3(0.1, 0.2, 0.3),
  17086. new BABYLON.Color3(0.0, 0.2, 0.9)
  17087. ];
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17093. get: function () {
  17094. return this._fireColors;
  17095. },
  17096. set: function (value) {
  17097. this._fireColors = value;
  17098. this.updateShaderUniforms();
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17104. get: function () {
  17105. return this._time;
  17106. },
  17107. set: function (value) {
  17108. this._time = value;
  17109. this.updateShaderUniforms();
  17110. },
  17111. enumerable: true,
  17112. configurable: true
  17113. });
  17114. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17115. get: function () {
  17116. return this._speed;
  17117. },
  17118. set: function (value) {
  17119. this._speed = value;
  17120. this.updateShaderUniforms();
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17126. get: function () {
  17127. return this._alphaThreshold;
  17128. },
  17129. set: function (value) {
  17130. this._alphaThreshold = value;
  17131. this.updateShaderUniforms();
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. return FireProceduralTexture;
  17137. })(BABYLON.ProceduralTexture);
  17138. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17139. var CloudProceduralTexture = (function (_super) {
  17140. __extends(CloudProceduralTexture, _super);
  17141. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17142. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17143. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17144. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17145. this.updateShaderUniforms();
  17146. this.refreshRate = 0;
  17147. }
  17148. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17149. this.setColor3("skyColor", this._skyColor);
  17150. this.setColor3("cloudColor", this._cloudColor);
  17151. };
  17152. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17153. get: function () {
  17154. return this._skyColor;
  17155. },
  17156. set: function (value) {
  17157. this._skyColor = value;
  17158. this.updateShaderUniforms();
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17164. get: function () {
  17165. return this._cloudColor;
  17166. },
  17167. set: function (value) {
  17168. this._cloudColor = value;
  17169. this.updateShaderUniforms();
  17170. },
  17171. enumerable: true,
  17172. configurable: true
  17173. });
  17174. return CloudProceduralTexture;
  17175. })(BABYLON.ProceduralTexture);
  17176. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17177. var GrassProceduralTexture = (function (_super) {
  17178. __extends(GrassProceduralTexture, _super);
  17179. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17180. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17181. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17182. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17183. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17184. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17185. this._grassColors = [
  17186. new BABYLON.Color3(0.29, 0.38, 0.02),
  17187. new BABYLON.Color3(0.36, 0.49, 0.09),
  17188. new BABYLON.Color3(0.51, 0.6, 0.28)
  17189. ];
  17190. this.updateShaderUniforms();
  17191. this.refreshRate = 0;
  17192. }
  17193. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17194. this.setColor3("herb1Color", this._grassColors[0]);
  17195. this.setColor3("herb2Color", this._grassColors[1]);
  17196. this.setColor3("herb3Color", this._grassColors[2]);
  17197. this.setColor3("groundColor", this._groundColor);
  17198. };
  17199. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17200. get: function () {
  17201. return this._grassColors;
  17202. },
  17203. set: function (value) {
  17204. this._grassColors = value;
  17205. this.updateShaderUniforms();
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17211. get: function () {
  17212. return this._groundColor;
  17213. },
  17214. set: function (value) {
  17215. this.groundColor = value;
  17216. this.updateShaderUniforms();
  17217. },
  17218. enumerable: true,
  17219. configurable: true
  17220. });
  17221. return GrassProceduralTexture;
  17222. })(BABYLON.ProceduralTexture);
  17223. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17224. var RoadProceduralTexture = (function (_super) {
  17225. __extends(RoadProceduralTexture, _super);
  17226. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17227. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17228. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17229. this.updateShaderUniforms();
  17230. this.refreshRate = 0;
  17231. }
  17232. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17233. this.setColor3("roadColor", this._roadColor);
  17234. };
  17235. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17236. get: function () {
  17237. return this._roadColor;
  17238. },
  17239. set: function (value) {
  17240. this._roadColor = value;
  17241. this.updateShaderUniforms();
  17242. },
  17243. enumerable: true,
  17244. configurable: true
  17245. });
  17246. return RoadProceduralTexture;
  17247. })(BABYLON.ProceduralTexture);
  17248. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17249. var BrickProceduralTexture = (function (_super) {
  17250. __extends(BrickProceduralTexture, _super);
  17251. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17252. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17253. this._numberOfBricksHeight = 15;
  17254. this._numberOfBricksWidth = 5;
  17255. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17256. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17257. this.updateShaderUniforms();
  17258. this.refreshRate = 0;
  17259. }
  17260. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17261. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17262. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17263. this.setColor3("brickColor", this._brickColor);
  17264. this.setColor3("jointColor", this._jointColor);
  17265. };
  17266. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17267. get: function () {
  17268. return this._numberOfBricksHeight;
  17269. },
  17270. set: function (value) {
  17271. this._numberOfBricksHeight = value;
  17272. this.updateShaderUniforms();
  17273. },
  17274. enumerable: true,
  17275. configurable: true
  17276. });
  17277. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17278. get: function () {
  17279. return this._numberOfBricksWidth;
  17280. },
  17281. set: function (value) {
  17282. this._numberOfBricksHeight = value;
  17283. this.updateShaderUniforms();
  17284. },
  17285. enumerable: true,
  17286. configurable: true
  17287. });
  17288. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17289. get: function () {
  17290. return this._jointColor;
  17291. },
  17292. set: function (value) {
  17293. this._jointColor = value;
  17294. this.updateShaderUniforms();
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17300. get: function () {
  17301. return this._brickColor;
  17302. },
  17303. set: function (value) {
  17304. this._brickColor = value;
  17305. this.updateShaderUniforms();
  17306. },
  17307. enumerable: true,
  17308. configurable: true
  17309. });
  17310. return BrickProceduralTexture;
  17311. })(BABYLON.ProceduralTexture);
  17312. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17313. var MarbleProceduralTexture = (function (_super) {
  17314. __extends(MarbleProceduralTexture, _super);
  17315. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17316. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17317. this._numberOfTilesHeight = 3;
  17318. this._numberOfTilesWidth = 3;
  17319. this._amplitude = 9.0;
  17320. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17321. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17322. this.updateShaderUniforms();
  17323. this.refreshRate = 0;
  17324. }
  17325. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17326. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17327. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17328. this.setFloat("amplitude", this._amplitude);
  17329. this.setColor3("marbleColor", this._marbleColor);
  17330. this.setColor3("jointColor", this._jointColor);
  17331. };
  17332. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17333. get: function () {
  17334. return this._numberOfTilesHeight;
  17335. },
  17336. set: function (value) {
  17337. this._numberOfTilesHeight = value;
  17338. this.updateShaderUniforms();
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17344. get: function () {
  17345. return this._numberOfTilesWidth;
  17346. },
  17347. set: function (value) {
  17348. this._numberOfTilesWidth = value;
  17349. this.updateShaderUniforms();
  17350. },
  17351. enumerable: true,
  17352. configurable: true
  17353. });
  17354. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17355. get: function () {
  17356. return this._jointColor;
  17357. },
  17358. set: function (value) {
  17359. this._jointColor = value;
  17360. this.updateShaderUniforms();
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17366. get: function () {
  17367. return this._marbleColor;
  17368. },
  17369. set: function (value) {
  17370. this._marbleColor = value;
  17371. this.updateShaderUniforms();
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. return MarbleProceduralTexture;
  17377. })(BABYLON.ProceduralTexture);
  17378. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17379. })(BABYLON || (BABYLON = {}));
  17380. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17381. var BABYLON;
  17382. (function (BABYLON) {
  17383. var EffectFallbacks = (function () {
  17384. function EffectFallbacks() {
  17385. this._defines = {};
  17386. this._currentRank = 32;
  17387. this._maxRank = -1;
  17388. }
  17389. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17390. if (!this._defines[rank]) {
  17391. if (rank < this._currentRank) {
  17392. this._currentRank = rank;
  17393. }
  17394. if (rank > this._maxRank) {
  17395. this._maxRank = rank;
  17396. }
  17397. this._defines[rank] = new Array();
  17398. }
  17399. this._defines[rank].push(define);
  17400. };
  17401. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17402. get: function () {
  17403. return this._currentRank <= this._maxRank;
  17404. },
  17405. enumerable: true,
  17406. configurable: true
  17407. });
  17408. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17409. var currentFallbacks = this._defines[this._currentRank];
  17410. for (var index = 0; index < currentFallbacks.length; index++) {
  17411. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17412. }
  17413. this._currentRank++;
  17414. return currentDefines;
  17415. };
  17416. return EffectFallbacks;
  17417. })();
  17418. BABYLON.EffectFallbacks = EffectFallbacks;
  17419. var Effect = (function () {
  17420. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17421. var _this = this;
  17422. this._isReady = false;
  17423. this._compilationError = "";
  17424. this._valueCache = [];
  17425. this._engine = engine;
  17426. this.name = baseName;
  17427. this.defines = defines;
  17428. this._uniformsNames = uniformsNames.concat(samplers);
  17429. this._samplers = samplers;
  17430. this._attributesNames = attributesNames;
  17431. this.onError = onError;
  17432. this.onCompiled = onCompiled;
  17433. var vertexSource;
  17434. var fragmentSource;
  17435. if (baseName.vertexElement) {
  17436. vertexSource = document.getElementById(baseName.vertexElement);
  17437. if (!vertexSource) {
  17438. vertexSource = baseName.vertexElement;
  17439. }
  17440. }
  17441. else {
  17442. vertexSource = baseName.vertex || baseName;
  17443. }
  17444. if (baseName.fragmentElement) {
  17445. fragmentSource = document.getElementById(baseName.fragmentElement);
  17446. if (!fragmentSource) {
  17447. fragmentSource = baseName.fragmentElement;
  17448. }
  17449. }
  17450. else {
  17451. fragmentSource = baseName.fragment || baseName;
  17452. }
  17453. this._loadVertexShader(vertexSource, function (vertexCode) {
  17454. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17455. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17456. });
  17457. });
  17458. }
  17459. // Properties
  17460. Effect.prototype.isReady = function () {
  17461. return this._isReady;
  17462. };
  17463. Effect.prototype.getProgram = function () {
  17464. return this._program;
  17465. };
  17466. Effect.prototype.getAttributesNames = function () {
  17467. return this._attributesNames;
  17468. };
  17469. Effect.prototype.getAttributeLocation = function (index) {
  17470. return this._attributes[index];
  17471. };
  17472. Effect.prototype.getAttributeLocationByName = function (name) {
  17473. var index = this._attributesNames.indexOf(name);
  17474. return this._attributes[index];
  17475. };
  17476. Effect.prototype.getAttributesCount = function () {
  17477. return this._attributes.length;
  17478. };
  17479. Effect.prototype.getUniformIndex = function (uniformName) {
  17480. return this._uniformsNames.indexOf(uniformName);
  17481. };
  17482. Effect.prototype.getUniform = function (uniformName) {
  17483. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17484. };
  17485. Effect.prototype.getSamplers = function () {
  17486. return this._samplers;
  17487. };
  17488. Effect.prototype.getCompilationError = function () {
  17489. return this._compilationError;
  17490. };
  17491. // Methods
  17492. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17493. // DOM element ?
  17494. if (vertex instanceof HTMLElement) {
  17495. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17496. callback(vertexCode);
  17497. return;
  17498. }
  17499. // Is in local store ?
  17500. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17501. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17502. return;
  17503. }
  17504. var vertexShaderUrl;
  17505. if (vertex[0] === ".") {
  17506. vertexShaderUrl = vertex;
  17507. }
  17508. else {
  17509. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17510. }
  17511. // Vertex shader
  17512. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17513. };
  17514. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17515. // DOM element ?
  17516. if (fragment instanceof HTMLElement) {
  17517. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17518. callback(fragmentCode);
  17519. return;
  17520. }
  17521. // Is in local store ?
  17522. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17523. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17524. return;
  17525. }
  17526. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17527. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17528. return;
  17529. }
  17530. var fragmentShaderUrl;
  17531. if (fragment[0] === ".") {
  17532. fragmentShaderUrl = fragment;
  17533. }
  17534. else {
  17535. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17536. }
  17537. // Fragment shader
  17538. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17539. };
  17540. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17541. try {
  17542. var engine = this._engine;
  17543. if (!engine.getCaps().highPrecisionShaderSupported) {
  17544. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17545. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17546. }
  17547. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17548. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17549. this._attributes = engine.getAttributes(this._program, attributesNames);
  17550. for (var index = 0; index < this._samplers.length; index++) {
  17551. var sampler = this.getUniform(this._samplers[index]);
  17552. if (sampler == null) {
  17553. this._samplers.splice(index, 1);
  17554. index--;
  17555. }
  17556. }
  17557. engine.bindSamplers(this);
  17558. this._isReady = true;
  17559. if (this.onCompiled) {
  17560. this.onCompiled(this);
  17561. }
  17562. }
  17563. catch (e) {
  17564. // Is it a problem with precision?
  17565. if (e.message.indexOf("highp") !== -1) {
  17566. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17567. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17568. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17569. return;
  17570. }
  17571. // Let's go through fallbacks then
  17572. if (fallbacks && fallbacks.isMoreFallbacks) {
  17573. defines = fallbacks.reduce(defines);
  17574. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17575. }
  17576. else {
  17577. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17578. BABYLON.Tools.Error("Defines: " + defines);
  17579. BABYLON.Tools.Error("Error: " + e.message);
  17580. this._compilationError = e.message;
  17581. if (this.onError) {
  17582. this.onError(this, this._compilationError);
  17583. }
  17584. }
  17585. }
  17586. };
  17587. Effect.prototype._bindTexture = function (channel, texture) {
  17588. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17589. };
  17590. Effect.prototype.setTexture = function (channel, texture) {
  17591. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17592. };
  17593. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17594. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17595. };
  17596. //public _cacheMatrix(uniformName, matrix) {
  17597. // if (!this._valueCache[uniformName]) {
  17598. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17599. // }
  17600. // for (var index = 0; index < 16; index++) {
  17601. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17602. // }
  17603. //};
  17604. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17605. if (!this._valueCache[uniformName]) {
  17606. this._valueCache[uniformName] = [x, y];
  17607. return;
  17608. }
  17609. this._valueCache[uniformName][0] = x;
  17610. this._valueCache[uniformName][1] = y;
  17611. };
  17612. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17613. if (!this._valueCache[uniformName]) {
  17614. this._valueCache[uniformName] = [x, y, z];
  17615. return;
  17616. }
  17617. this._valueCache[uniformName][0] = x;
  17618. this._valueCache[uniformName][1] = y;
  17619. this._valueCache[uniformName][2] = z;
  17620. };
  17621. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17622. if (!this._valueCache[uniformName]) {
  17623. this._valueCache[uniformName] = [x, y, z, w];
  17624. return;
  17625. }
  17626. this._valueCache[uniformName][0] = x;
  17627. this._valueCache[uniformName][1] = y;
  17628. this._valueCache[uniformName][2] = z;
  17629. this._valueCache[uniformName][3] = w;
  17630. };
  17631. Effect.prototype.setArray = function (uniformName, array) {
  17632. this._engine.setArray(this.getUniform(uniformName), array);
  17633. return this;
  17634. };
  17635. Effect.prototype.setArray2 = function (uniformName, array) {
  17636. this._engine.setArray2(this.getUniform(uniformName), array);
  17637. return this;
  17638. };
  17639. Effect.prototype.setArray3 = function (uniformName, array) {
  17640. this._engine.setArray3(this.getUniform(uniformName), array);
  17641. return this;
  17642. };
  17643. Effect.prototype.setArray4 = function (uniformName, array) {
  17644. this._engine.setArray4(this.getUniform(uniformName), array);
  17645. return this;
  17646. };
  17647. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17648. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17649. return this;
  17650. };
  17651. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17652. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17653. // return;
  17654. //this._cacheMatrix(uniformName, matrix);
  17655. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17656. return this;
  17657. };
  17658. Effect.prototype.setFloat = function (uniformName, value) {
  17659. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17660. return this;
  17661. this._valueCache[uniformName] = value;
  17662. this._engine.setFloat(this.getUniform(uniformName), value);
  17663. return this;
  17664. };
  17665. Effect.prototype.setBool = function (uniformName, bool) {
  17666. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17667. return this;
  17668. this._valueCache[uniformName] = bool;
  17669. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17670. return this;
  17671. };
  17672. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17673. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17674. return this;
  17675. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17676. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17677. return this;
  17678. };
  17679. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17680. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17681. return this;
  17682. this._cacheFloat2(uniformName, x, y);
  17683. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17684. return this;
  17685. };
  17686. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17687. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17688. return this;
  17689. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17690. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17691. return this;
  17692. };
  17693. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17694. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17695. return this;
  17696. this._cacheFloat3(uniformName, x, y, z);
  17697. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17698. return this;
  17699. };
  17700. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17701. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17702. return this;
  17703. this._cacheFloat4(uniformName, x, y, z, w);
  17704. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17705. return this;
  17706. };
  17707. Effect.prototype.setColor3 = function (uniformName, color3) {
  17708. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17709. return this;
  17710. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17711. this._engine.setColor3(this.getUniform(uniformName), color3);
  17712. return this;
  17713. };
  17714. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17715. 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)
  17716. return this;
  17717. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17718. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17719. return this;
  17720. };
  17721. // Statics
  17722. Effect.ShadersStore = {};
  17723. return Effect;
  17724. })();
  17725. BABYLON.Effect = Effect;
  17726. })(BABYLON || (BABYLON = {}));
  17727. //# sourceMappingURL=babylon.effect.js.map
  17728. var BABYLON;
  17729. (function (BABYLON) {
  17730. var Material = (function () {
  17731. function Material(name, scene, doNotAdd) {
  17732. this.name = name;
  17733. this.checkReadyOnEveryCall = true;
  17734. this.checkReadyOnlyOnce = false;
  17735. this.state = "";
  17736. this.alpha = 1.0;
  17737. this.backFaceCulling = true;
  17738. this._wasPreviouslyReady = false;
  17739. this._fillMode = Material.TriangleFillMode;
  17740. this.pointSize = 1.0;
  17741. this.zOffset = 0;
  17742. this.id = name;
  17743. this._scene = scene;
  17744. if (!doNotAdd) {
  17745. scene.materials.push(this);
  17746. }
  17747. }
  17748. Object.defineProperty(Material, "TriangleFillMode", {
  17749. get: function () {
  17750. return Material._TriangleFillMode;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. Object.defineProperty(Material, "WireFrameFillMode", {
  17756. get: function () {
  17757. return Material._WireFrameFillMode;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(Material, "PointFillMode", {
  17763. get: function () {
  17764. return Material._PointFillMode;
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(Material.prototype, "wireframe", {
  17770. get: function () {
  17771. return this._fillMode === Material.WireFrameFillMode;
  17772. },
  17773. set: function (value) {
  17774. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(Material.prototype, "pointsCloud", {
  17780. get: function () {
  17781. return this._fillMode === Material.PointFillMode;
  17782. },
  17783. set: function (value) {
  17784. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(Material.prototype, "fillMode", {
  17790. get: function () {
  17791. return this._fillMode;
  17792. },
  17793. set: function (value) {
  17794. this._fillMode = value;
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Material.prototype.isReady = function (mesh, useInstances) {
  17800. return true;
  17801. };
  17802. Material.prototype.getEffect = function () {
  17803. return this._effect;
  17804. };
  17805. Material.prototype.getScene = function () {
  17806. return this._scene;
  17807. };
  17808. Material.prototype.needAlphaBlending = function () {
  17809. return (this.alpha < 1.0);
  17810. };
  17811. Material.prototype.needAlphaTesting = function () {
  17812. return false;
  17813. };
  17814. Material.prototype.getAlphaTestTexture = function () {
  17815. return null;
  17816. };
  17817. Material.prototype.trackCreation = function (onCompiled, onError) {
  17818. };
  17819. Material.prototype._preBind = function () {
  17820. var engine = this._scene.getEngine();
  17821. engine.enableEffect(this._effect);
  17822. engine.setState(this.backFaceCulling, this.zOffset);
  17823. };
  17824. Material.prototype.bind = function (world, mesh) {
  17825. this._scene._cachedMaterial = this;
  17826. if (this.onBind) {
  17827. this.onBind(this, mesh);
  17828. }
  17829. };
  17830. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17831. };
  17832. Material.prototype.unbind = function () {
  17833. };
  17834. Material.prototype.dispose = function (forceDisposeEffect) {
  17835. // Remove from scene
  17836. var index = this._scene.materials.indexOf(this);
  17837. this._scene.materials.splice(index, 1);
  17838. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17839. if (forceDisposeEffect && this._effect) {
  17840. this._scene.getEngine()._releaseEffect(this._effect);
  17841. this._effect = null;
  17842. }
  17843. // Callback
  17844. if (this.onDispose) {
  17845. this.onDispose();
  17846. }
  17847. };
  17848. Material._TriangleFillMode = 0;
  17849. Material._WireFrameFillMode = 1;
  17850. Material._PointFillMode = 2;
  17851. return Material;
  17852. })();
  17853. BABYLON.Material = Material;
  17854. })(BABYLON || (BABYLON = {}));
  17855. //# sourceMappingURL=babylon.material.js.map
  17856. var __extends = this.__extends || function (d, b) {
  17857. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17858. function __() { this.constructor = d; }
  17859. __.prototype = b.prototype;
  17860. d.prototype = new __();
  17861. };
  17862. var BABYLON;
  17863. (function (BABYLON) {
  17864. var maxSimultaneousLights = 4;
  17865. var FresnelParameters = (function () {
  17866. function FresnelParameters() {
  17867. this.isEnabled = true;
  17868. this.leftColor = BABYLON.Color3.White();
  17869. this.rightColor = BABYLON.Color3.Black();
  17870. this.bias = 0;
  17871. this.power = 1;
  17872. }
  17873. return FresnelParameters;
  17874. })();
  17875. BABYLON.FresnelParameters = FresnelParameters;
  17876. var StandardMaterial = (function (_super) {
  17877. __extends(StandardMaterial, _super);
  17878. function StandardMaterial(name, scene) {
  17879. var _this = this;
  17880. _super.call(this, name, scene);
  17881. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17882. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17883. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17884. this.specularPower = 64;
  17885. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17886. this.useAlphaFromDiffuseTexture = false;
  17887. this.useSpecularOverAlpha = true;
  17888. this.fogEnabled = true;
  17889. this._cachedDefines = null;
  17890. this._renderTargets = new BABYLON.SmartArray(16);
  17891. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17892. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17893. this._scaledDiffuse = new BABYLON.Color3();
  17894. this._scaledSpecular = new BABYLON.Color3();
  17895. this.getRenderTargetTextures = function () {
  17896. _this._renderTargets.reset();
  17897. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17898. _this._renderTargets.push(_this.reflectionTexture);
  17899. }
  17900. return _this._renderTargets;
  17901. };
  17902. }
  17903. StandardMaterial.prototype.needAlphaBlending = function () {
  17904. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17905. };
  17906. StandardMaterial.prototype.needAlphaTesting = function () {
  17907. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17908. };
  17909. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17910. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17911. };
  17912. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17913. return this.diffuseTexture;
  17914. };
  17915. // Methods
  17916. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17917. if (this.checkReadyOnlyOnce) {
  17918. if (this._wasPreviouslyReady) {
  17919. return true;
  17920. }
  17921. }
  17922. var scene = this.getScene();
  17923. if (!this.checkReadyOnEveryCall) {
  17924. if (this._renderId === scene.getRenderId()) {
  17925. return true;
  17926. }
  17927. }
  17928. var engine = scene.getEngine();
  17929. var defines = [];
  17930. var fallbacks = new BABYLON.EffectFallbacks();
  17931. var needNormals = false;
  17932. var needUVs = false;
  17933. // Textures
  17934. if (scene.texturesEnabled) {
  17935. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17936. if (!this.diffuseTexture.isReady()) {
  17937. return false;
  17938. }
  17939. else {
  17940. needUVs = true;
  17941. defines.push("#define DIFFUSE");
  17942. }
  17943. }
  17944. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17945. if (!this.ambientTexture.isReady()) {
  17946. return false;
  17947. }
  17948. else {
  17949. needUVs = true;
  17950. defines.push("#define AMBIENT");
  17951. }
  17952. }
  17953. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17954. if (!this.opacityTexture.isReady()) {
  17955. return false;
  17956. }
  17957. else {
  17958. needUVs = true;
  17959. defines.push("#define OPACITY");
  17960. if (this.opacityTexture.getAlphaFromRGB) {
  17961. defines.push("#define OPACITYRGB");
  17962. }
  17963. }
  17964. }
  17965. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17966. if (!this.reflectionTexture.isReady()) {
  17967. return false;
  17968. }
  17969. else {
  17970. needNormals = true;
  17971. needUVs = true;
  17972. defines.push("#define REFLECTION");
  17973. fallbacks.addFallback(0, "REFLECTION");
  17974. }
  17975. }
  17976. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17977. if (!this.emissiveTexture.isReady()) {
  17978. return false;
  17979. }
  17980. else {
  17981. needUVs = true;
  17982. defines.push("#define EMISSIVE");
  17983. }
  17984. }
  17985. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17986. if (!this.specularTexture.isReady()) {
  17987. return false;
  17988. }
  17989. else {
  17990. needUVs = true;
  17991. defines.push("#define SPECULAR");
  17992. fallbacks.addFallback(0, "SPECULAR");
  17993. }
  17994. }
  17995. }
  17996. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  17997. if (!this.bumpTexture.isReady()) {
  17998. return false;
  17999. }
  18000. else {
  18001. needUVs = true;
  18002. defines.push("#define BUMP");
  18003. fallbacks.addFallback(0, "BUMP");
  18004. }
  18005. }
  18006. // Effect
  18007. if (this.useSpecularOverAlpha) {
  18008. defines.push("#define SPECULAROVERALPHA");
  18009. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18010. }
  18011. if (scene.clipPlane) {
  18012. defines.push("#define CLIPPLANE");
  18013. }
  18014. if (engine.getAlphaTesting()) {
  18015. defines.push("#define ALPHATEST");
  18016. }
  18017. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18018. defines.push("#define ALPHAFROMDIFFUSE");
  18019. }
  18020. // Point size
  18021. if (this.pointsCloud || scene.forcePointsCloud) {
  18022. defines.push("#define POINTSIZE");
  18023. }
  18024. // Fog
  18025. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18026. defines.push("#define FOG");
  18027. fallbacks.addFallback(1, "FOG");
  18028. }
  18029. var shadowsActivated = false;
  18030. var lightIndex = 0;
  18031. if (scene.lightsEnabled) {
  18032. for (var index = 0; index < scene.lights.length; index++) {
  18033. var light = scene.lights[index];
  18034. if (!light.isEnabled()) {
  18035. continue;
  18036. }
  18037. // Excluded check
  18038. if (light._excludedMeshesIds.length > 0) {
  18039. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18040. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18041. if (excludedMesh) {
  18042. light.excludedMeshes.push(excludedMesh);
  18043. }
  18044. }
  18045. light._excludedMeshesIds = [];
  18046. }
  18047. // Included check
  18048. if (light._includedOnlyMeshesIds.length > 0) {
  18049. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18050. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18051. if (includedOnlyMesh) {
  18052. light.includedOnlyMeshes.push(includedOnlyMesh);
  18053. }
  18054. }
  18055. light._includedOnlyMeshesIds = [];
  18056. }
  18057. if (!light.canAffectMesh(mesh)) {
  18058. continue;
  18059. }
  18060. needNormals = true;
  18061. defines.push("#define LIGHT" + lightIndex);
  18062. if (lightIndex > 0) {
  18063. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18064. }
  18065. var type;
  18066. if (light instanceof BABYLON.SpotLight) {
  18067. type = "#define SPOTLIGHT" + lightIndex;
  18068. }
  18069. else if (light instanceof BABYLON.HemisphericLight) {
  18070. type = "#define HEMILIGHT" + lightIndex;
  18071. }
  18072. else {
  18073. type = "#define POINTDIRLIGHT" + lightIndex;
  18074. }
  18075. defines.push(type);
  18076. if (lightIndex > 0) {
  18077. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18078. }
  18079. // Shadows
  18080. if (scene.shadowsEnabled) {
  18081. var shadowGenerator = light.getShadowGenerator();
  18082. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18083. defines.push("#define SHADOW" + lightIndex);
  18084. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18085. if (!shadowsActivated) {
  18086. defines.push("#define SHADOWS");
  18087. shadowsActivated = true;
  18088. }
  18089. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18090. defines.push("#define SHADOWVSM" + lightIndex);
  18091. if (lightIndex > 0) {
  18092. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18093. }
  18094. }
  18095. if (shadowGenerator.usePoissonSampling) {
  18096. defines.push("#define SHADOWPCF" + lightIndex);
  18097. if (lightIndex > 0) {
  18098. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18099. }
  18100. }
  18101. }
  18102. }
  18103. lightIndex++;
  18104. if (lightIndex === maxSimultaneousLights)
  18105. break;
  18106. }
  18107. }
  18108. if (StandardMaterial.FresnelEnabled) {
  18109. // Fresnel
  18110. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18111. var fresnelRank = 1;
  18112. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18113. defines.push("#define DIFFUSEFRESNEL");
  18114. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18115. fresnelRank++;
  18116. }
  18117. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18118. defines.push("#define OPACITYFRESNEL");
  18119. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18120. fresnelRank++;
  18121. }
  18122. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18123. defines.push("#define REFLECTIONFRESNEL");
  18124. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18125. fresnelRank++;
  18126. }
  18127. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18128. defines.push("#define EMISSIVEFRESNEL");
  18129. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18130. fresnelRank++;
  18131. }
  18132. needNormals = true;
  18133. defines.push("#define FRESNEL");
  18134. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18135. }
  18136. }
  18137. // Attribs
  18138. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18139. if (mesh) {
  18140. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18141. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18142. defines.push("#define NORMAL");
  18143. }
  18144. if (needUVs) {
  18145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18146. attribs.push(BABYLON.VertexBuffer.UVKind);
  18147. defines.push("#define UV1");
  18148. }
  18149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18151. defines.push("#define UV2");
  18152. }
  18153. }
  18154. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18155. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18156. defines.push("#define VERTEXCOLOR");
  18157. if (mesh.hasVertexAlpha) {
  18158. defines.push("#define VERTEXALPHA");
  18159. }
  18160. }
  18161. if (mesh.useBones) {
  18162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18164. defines.push("#define BONES");
  18165. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18166. defines.push("#define BONES4");
  18167. fallbacks.addFallback(0, "BONES4");
  18168. }
  18169. // Instances
  18170. if (useInstances) {
  18171. defines.push("#define INSTANCES");
  18172. attribs.push("world0");
  18173. attribs.push("world1");
  18174. attribs.push("world2");
  18175. attribs.push("world3");
  18176. }
  18177. }
  18178. // Get correct effect
  18179. var join = defines.join("\n");
  18180. if (this._cachedDefines !== join) {
  18181. this._cachedDefines = join;
  18182. scene.resetCachedMaterial();
  18183. // Legacy browser patch
  18184. var shaderName = "default";
  18185. if (!scene.getEngine().getCaps().standardDerivatives) {
  18186. shaderName = "legacydefault";
  18187. }
  18188. 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);
  18189. }
  18190. if (!this._effect.isReady()) {
  18191. return false;
  18192. }
  18193. this._renderId = scene.getRenderId();
  18194. this._wasPreviouslyReady = true;
  18195. return true;
  18196. };
  18197. StandardMaterial.prototype.unbind = function () {
  18198. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18199. this._effect.setTexture("reflection2DSampler", null);
  18200. }
  18201. };
  18202. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18203. this._effect.setMatrix("world", world);
  18204. };
  18205. StandardMaterial.prototype.bind = function (world, mesh) {
  18206. var scene = this.getScene();
  18207. // Matrices
  18208. this.bindOnlyWorldMatrix(world);
  18209. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18210. // Bones
  18211. if (mesh && mesh.useBones) {
  18212. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18213. }
  18214. if (scene.getCachedMaterial() !== this) {
  18215. if (StandardMaterial.FresnelEnabled) {
  18216. // Fresnel
  18217. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18218. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18219. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18220. }
  18221. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18222. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18223. }
  18224. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18225. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18226. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18227. }
  18228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18229. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18230. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18231. }
  18232. }
  18233. // Textures
  18234. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18235. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18236. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18237. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18238. }
  18239. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18240. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18241. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18242. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18243. }
  18244. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18245. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18246. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18247. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18248. }
  18249. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18250. if (this.reflectionTexture.isCube) {
  18251. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18252. }
  18253. else {
  18254. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18255. }
  18256. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18257. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18258. }
  18259. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18260. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18261. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18262. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18263. }
  18264. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18265. this._effect.setTexture("specularSampler", this.specularTexture);
  18266. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18267. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18268. }
  18269. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18270. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18271. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18272. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18273. }
  18274. // Clip plane
  18275. if (scene.clipPlane) {
  18276. var clipPlane = scene.clipPlane;
  18277. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18278. }
  18279. // Point size
  18280. if (this.pointsCloud) {
  18281. this._effect.setFloat("pointSize", this.pointSize);
  18282. }
  18283. // Colors
  18284. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18285. // Scaling down color according to emissive
  18286. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18287. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18288. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18289. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18290. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18291. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18292. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18293. }
  18294. // Scaling down color according to emissive
  18295. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18296. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18297. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18298. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18299. if (scene.lightsEnabled) {
  18300. var lightIndex = 0;
  18301. for (var index = 0; index < scene.lights.length; index++) {
  18302. var light = scene.lights[index];
  18303. if (!light.isEnabled()) {
  18304. continue;
  18305. }
  18306. if (!light.canAffectMesh(mesh)) {
  18307. continue;
  18308. }
  18309. if (light instanceof BABYLON.PointLight) {
  18310. // Point Light
  18311. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18312. }
  18313. else if (light instanceof BABYLON.DirectionalLight) {
  18314. // Directional Light
  18315. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18316. }
  18317. else if (light instanceof BABYLON.SpotLight) {
  18318. // Spot Light
  18319. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18320. }
  18321. else if (light instanceof BABYLON.HemisphericLight) {
  18322. // Hemispheric Light
  18323. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18324. }
  18325. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18326. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18327. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18328. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18329. // Shadows
  18330. if (scene.shadowsEnabled) {
  18331. var shadowGenerator = light.getShadowGenerator();
  18332. if (mesh.receiveShadows && shadowGenerator) {
  18333. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18334. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18335. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18336. }
  18337. }
  18338. lightIndex++;
  18339. if (lightIndex === maxSimultaneousLights)
  18340. break;
  18341. }
  18342. }
  18343. // View
  18344. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18345. this._effect.setMatrix("view", scene.getViewMatrix());
  18346. }
  18347. // Fog
  18348. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18349. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18350. this._effect.setColor3("vFogColor", scene.fogColor);
  18351. }
  18352. _super.prototype.bind.call(this, world, mesh);
  18353. };
  18354. StandardMaterial.prototype.getAnimatables = function () {
  18355. var results = [];
  18356. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18357. results.push(this.diffuseTexture);
  18358. }
  18359. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18360. results.push(this.ambientTexture);
  18361. }
  18362. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18363. results.push(this.opacityTexture);
  18364. }
  18365. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18366. results.push(this.reflectionTexture);
  18367. }
  18368. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18369. results.push(this.emissiveTexture);
  18370. }
  18371. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18372. results.push(this.specularTexture);
  18373. }
  18374. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18375. results.push(this.bumpTexture);
  18376. }
  18377. return results;
  18378. };
  18379. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18380. if (this.diffuseTexture) {
  18381. this.diffuseTexture.dispose();
  18382. }
  18383. if (this.ambientTexture) {
  18384. this.ambientTexture.dispose();
  18385. }
  18386. if (this.opacityTexture) {
  18387. this.opacityTexture.dispose();
  18388. }
  18389. if (this.reflectionTexture) {
  18390. this.reflectionTexture.dispose();
  18391. }
  18392. if (this.emissiveTexture) {
  18393. this.emissiveTexture.dispose();
  18394. }
  18395. if (this.specularTexture) {
  18396. this.specularTexture.dispose();
  18397. }
  18398. if (this.bumpTexture) {
  18399. this.bumpTexture.dispose();
  18400. }
  18401. _super.prototype.dispose.call(this, forceDisposeEffect);
  18402. };
  18403. StandardMaterial.prototype.clone = function (name) {
  18404. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18405. // Base material
  18406. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18407. newStandardMaterial.alpha = this.alpha;
  18408. newStandardMaterial.fillMode = this.fillMode;
  18409. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18410. // Standard material
  18411. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18412. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18413. }
  18414. if (this.ambientTexture && this.ambientTexture.clone) {
  18415. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18416. }
  18417. if (this.opacityTexture && this.opacityTexture.clone) {
  18418. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18419. }
  18420. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18421. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18422. }
  18423. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18424. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18425. }
  18426. if (this.specularTexture && this.specularTexture.clone) {
  18427. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18428. }
  18429. if (this.bumpTexture && this.bumpTexture.clone) {
  18430. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18431. }
  18432. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18433. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18434. newStandardMaterial.specularColor = this.specularColor.clone();
  18435. newStandardMaterial.specularPower = this.specularPower;
  18436. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18437. return newStandardMaterial;
  18438. };
  18439. // Statics
  18440. // Flags used to enable or disable a type of texture for all Standard Materials
  18441. StandardMaterial.DiffuseTextureEnabled = true;
  18442. StandardMaterial.AmbientTextureEnabled = true;
  18443. StandardMaterial.OpacityTextureEnabled = true;
  18444. StandardMaterial.ReflectionTextureEnabled = true;
  18445. StandardMaterial.EmissiveTextureEnabled = true;
  18446. StandardMaterial.SpecularTextureEnabled = true;
  18447. StandardMaterial.BumpTextureEnabled = true;
  18448. StandardMaterial.FresnelEnabled = true;
  18449. return StandardMaterial;
  18450. })(BABYLON.Material);
  18451. BABYLON.StandardMaterial = StandardMaterial;
  18452. })(BABYLON || (BABYLON = {}));
  18453. //# sourceMappingURL=babylon.standardMaterial.js.map
  18454. var __extends = this.__extends || function (d, b) {
  18455. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18456. function __() { this.constructor = d; }
  18457. __.prototype = b.prototype;
  18458. d.prototype = new __();
  18459. };
  18460. var BABYLON;
  18461. (function (BABYLON) {
  18462. var MultiMaterial = (function (_super) {
  18463. __extends(MultiMaterial, _super);
  18464. function MultiMaterial(name, scene) {
  18465. _super.call(this, name, scene, true);
  18466. this.subMaterials = new Array();
  18467. scene.multiMaterials.push(this);
  18468. }
  18469. // Properties
  18470. MultiMaterial.prototype.getSubMaterial = function (index) {
  18471. if (index < 0 || index >= this.subMaterials.length) {
  18472. return this.getScene().defaultMaterial;
  18473. }
  18474. return this.subMaterials[index];
  18475. };
  18476. // Methods
  18477. MultiMaterial.prototype.isReady = function (mesh) {
  18478. for (var index = 0; index < this.subMaterials.length; index++) {
  18479. var subMaterial = this.subMaterials[index];
  18480. if (subMaterial) {
  18481. if (!this.subMaterials[index].isReady(mesh)) {
  18482. return false;
  18483. }
  18484. }
  18485. }
  18486. return true;
  18487. };
  18488. MultiMaterial.prototype.clone = function (name) {
  18489. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18490. for (var index = 0; index < this.subMaterials.length; index++) {
  18491. var subMaterial = this.subMaterials[index];
  18492. newMultiMaterial.subMaterials.push(subMaterial);
  18493. }
  18494. return newMultiMaterial;
  18495. };
  18496. return MultiMaterial;
  18497. })(BABYLON.Material);
  18498. BABYLON.MultiMaterial = MultiMaterial;
  18499. })(BABYLON || (BABYLON = {}));
  18500. //# sourceMappingURL=babylon.multiMaterial.js.map
  18501. var BABYLON;
  18502. (function (BABYLON) {
  18503. var SceneLoader = (function () {
  18504. function SceneLoader() {
  18505. }
  18506. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18507. get: function () {
  18508. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18509. },
  18510. set: function (value) {
  18511. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18517. get: function () {
  18518. return SceneLoader._ShowLoadingScreen;
  18519. },
  18520. set: function (value) {
  18521. SceneLoader._ShowLoadingScreen = value;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18527. var dotPosition = sceneFilename.lastIndexOf(".");
  18528. var queryStringPosition = sceneFilename.indexOf("?");
  18529. if (queryStringPosition === -1) {
  18530. queryStringPosition = sceneFilename.length;
  18531. }
  18532. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18533. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18534. var plugin = this._registeredPlugins[index];
  18535. if (plugin.extensions.indexOf(extension) !== -1) {
  18536. return plugin;
  18537. }
  18538. }
  18539. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18540. };
  18541. // Public functions
  18542. SceneLoader.RegisterPlugin = function (plugin) {
  18543. plugin.extensions = plugin.extensions.toLowerCase();
  18544. SceneLoader._registeredPlugins.push(plugin);
  18545. };
  18546. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18547. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18548. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18549. return;
  18550. }
  18551. var manifestChecked = function (success) {
  18552. scene.database = database;
  18553. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18554. var importMeshFromData = function (data) {
  18555. var meshes = [];
  18556. var particleSystems = [];
  18557. var skeletons = [];
  18558. try {
  18559. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18560. if (onerror) {
  18561. onerror(scene, 'unable to load the scene');
  18562. }
  18563. return;
  18564. }
  18565. }
  18566. catch (e) {
  18567. if (onerror) {
  18568. onerror(scene, e);
  18569. }
  18570. return;
  18571. }
  18572. if (onsuccess) {
  18573. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18574. onsuccess(meshes, particleSystems, skeletons);
  18575. }
  18576. };
  18577. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18578. // Direct load
  18579. importMeshFromData(sceneFilename.substr(5));
  18580. return;
  18581. }
  18582. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18583. importMeshFromData(data);
  18584. }, progressCallBack, database);
  18585. };
  18586. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18587. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18588. };
  18589. /**
  18590. * Load a scene
  18591. * @param rootUrl a string that defines the root url for scene and resources
  18592. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18593. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18594. */
  18595. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18596. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18597. };
  18598. /**
  18599. * Append a scene
  18600. * @param rootUrl a string that defines the root url for scene and resources
  18601. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18602. * @param scene is the instance of BABYLON.Scene to append to
  18603. */
  18604. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18605. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18606. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18607. return;
  18608. }
  18609. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18610. var database;
  18611. if (SceneLoader.ShowLoadingScreen) {
  18612. scene.getEngine().displayLoadingUI();
  18613. }
  18614. var loadSceneFromData = function (data) {
  18615. scene.database = database;
  18616. if (!plugin.load(scene, data, rootUrl)) {
  18617. if (onerror) {
  18618. onerror(scene);
  18619. }
  18620. scene.getEngine().hideLoadingUI();
  18621. return;
  18622. }
  18623. if (onsuccess) {
  18624. onsuccess(scene);
  18625. }
  18626. if (SceneLoader.ShowLoadingScreen) {
  18627. scene.executeWhenReady(function () {
  18628. scene.getEngine().hideLoadingUI();
  18629. });
  18630. }
  18631. };
  18632. var manifestChecked = function (success) {
  18633. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18634. };
  18635. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18636. // Direct load
  18637. loadSceneFromData(sceneFilename.substr(5));
  18638. return;
  18639. }
  18640. if (rootUrl.indexOf("file:") === -1) {
  18641. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18642. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18643. }
  18644. else {
  18645. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18646. }
  18647. };
  18648. // Flags
  18649. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18650. SceneLoader._ShowLoadingScreen = true;
  18651. // Members
  18652. SceneLoader._registeredPlugins = new Array();
  18653. return SceneLoader;
  18654. })();
  18655. BABYLON.SceneLoader = SceneLoader;
  18656. ;
  18657. })(BABYLON || (BABYLON = {}));
  18658. //# sourceMappingURL=babylon.sceneLoader.js.map
  18659. var BABYLON;
  18660. (function (BABYLON) {
  18661. var Internals;
  18662. (function (Internals) {
  18663. var checkColors4 = function (colors, count) {
  18664. // Check if color3 was used
  18665. if (colors.length === count * 3) {
  18666. var colors4 = [];
  18667. for (var index = 0; index < colors.length; index += 3) {
  18668. var newIndex = (index / 3) * 4;
  18669. colors4[newIndex] = colors[index];
  18670. colors4[newIndex + 1] = colors[index + 1];
  18671. colors4[newIndex + 2] = colors[index + 2];
  18672. colors4[newIndex + 3] = 1.0;
  18673. }
  18674. return colors4;
  18675. }
  18676. return colors;
  18677. };
  18678. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18679. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18680. texture.name = parsedTexture.name;
  18681. texture.hasAlpha = parsedTexture.hasAlpha;
  18682. texture.level = parsedTexture.level;
  18683. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18684. return texture;
  18685. };
  18686. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18687. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18688. return null;
  18689. }
  18690. if (parsedTexture.isCube) {
  18691. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18692. }
  18693. var texture;
  18694. if (parsedTexture.mirrorPlane) {
  18695. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18696. texture._waitingRenderList = parsedTexture.renderList;
  18697. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18698. }
  18699. else if (parsedTexture.isRenderTarget) {
  18700. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18701. texture._waitingRenderList = parsedTexture.renderList;
  18702. }
  18703. else {
  18704. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18705. }
  18706. texture.name = parsedTexture.name;
  18707. texture.hasAlpha = parsedTexture.hasAlpha;
  18708. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18709. texture.level = parsedTexture.level;
  18710. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18711. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18712. texture.uOffset = parsedTexture.uOffset;
  18713. texture.vOffset = parsedTexture.vOffset;
  18714. texture.uScale = parsedTexture.uScale;
  18715. texture.vScale = parsedTexture.vScale;
  18716. texture.uAng = parsedTexture.uAng;
  18717. texture.vAng = parsedTexture.vAng;
  18718. texture.wAng = parsedTexture.wAng;
  18719. texture.wrapU = parsedTexture.wrapU;
  18720. texture.wrapV = parsedTexture.wrapV;
  18721. // Animations
  18722. if (parsedTexture.animations) {
  18723. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18724. var parsedAnimation = parsedTexture.animations[animationIndex];
  18725. texture.animations.push(parseAnimation(parsedAnimation));
  18726. }
  18727. }
  18728. return texture;
  18729. };
  18730. var parseSkeleton = function (parsedSkeleton, scene) {
  18731. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18732. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18733. var parsedBone = parsedSkeleton.bones[index];
  18734. var parentBone = null;
  18735. if (parsedBone.parentBoneIndex > -1) {
  18736. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18737. }
  18738. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18739. if (parsedBone.animation) {
  18740. bone.animations.push(parseAnimation(parsedBone.animation));
  18741. }
  18742. }
  18743. return skeleton;
  18744. };
  18745. var parseFresnelParameters = function (parsedFresnelParameters) {
  18746. var fresnelParameters = new BABYLON.FresnelParameters();
  18747. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18748. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18749. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18750. fresnelParameters.bias = parsedFresnelParameters.bias;
  18751. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18752. return fresnelParameters;
  18753. };
  18754. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18755. var material;
  18756. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18757. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18758. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18759. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18760. material.specularPower = parsedMaterial.specularPower;
  18761. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18762. material.alpha = parsedMaterial.alpha;
  18763. material.id = parsedMaterial.id;
  18764. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18765. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18766. material.wireframe = parsedMaterial.wireframe;
  18767. if (parsedMaterial.diffuseTexture) {
  18768. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18769. }
  18770. if (parsedMaterial.diffuseFresnelParameters) {
  18771. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18772. }
  18773. if (parsedMaterial.ambientTexture) {
  18774. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18775. }
  18776. if (parsedMaterial.opacityTexture) {
  18777. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18778. }
  18779. if (parsedMaterial.opacityFresnelParameters) {
  18780. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18781. }
  18782. if (parsedMaterial.reflectionTexture) {
  18783. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18784. }
  18785. if (parsedMaterial.reflectionFresnelParameters) {
  18786. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18787. }
  18788. if (parsedMaterial.emissiveTexture) {
  18789. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18790. }
  18791. if (parsedMaterial.emissiveFresnelParameters) {
  18792. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18793. }
  18794. if (parsedMaterial.specularTexture) {
  18795. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18796. }
  18797. if (parsedMaterial.bumpTexture) {
  18798. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18799. }
  18800. return material;
  18801. };
  18802. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18803. for (var index = 0; index < parsedData.materials.length; index++) {
  18804. var parsedMaterial = parsedData.materials[index];
  18805. if (parsedMaterial.id === id) {
  18806. return parseMaterial(parsedMaterial, scene, rootUrl);
  18807. }
  18808. }
  18809. return null;
  18810. };
  18811. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18812. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18813. multiMaterial.id = parsedMultiMaterial.id;
  18814. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18815. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18816. var subMatId = parsedMultiMaterial.materials[matIndex];
  18817. if (subMatId) {
  18818. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18819. }
  18820. else {
  18821. multiMaterial.subMaterials.push(null);
  18822. }
  18823. }
  18824. return multiMaterial;
  18825. };
  18826. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18827. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18828. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18829. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18830. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18831. var parsedFlare = parsedLensFlareSystem.flares[index];
  18832. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18833. }
  18834. return lensFlareSystem;
  18835. };
  18836. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18837. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18838. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18839. if (parsedParticleSystem.textureName) {
  18840. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18841. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18842. }
  18843. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18844. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18845. particleSystem.minSize = parsedParticleSystem.minSize;
  18846. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18847. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18848. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18849. particleSystem.emitter = emitter;
  18850. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18851. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18852. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18853. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18854. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18855. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18856. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18857. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18858. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18859. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18860. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18861. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18862. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18863. particleSystem.start();
  18864. return particleSystem;
  18865. };
  18866. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18867. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18868. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18869. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18870. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18871. shadowGenerator.getShadowMap().renderList.push(mesh);
  18872. }
  18873. if (parsedShadowGenerator.usePoissonSampling) {
  18874. shadowGenerator.usePoissonSampling = true;
  18875. }
  18876. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18877. shadowGenerator.useVarianceShadowMap = true;
  18878. }
  18879. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18880. shadowGenerator.useBlurVarianceShadowMap = true;
  18881. if (parsedShadowGenerator.blurScale) {
  18882. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18883. }
  18884. if (parsedShadowGenerator.blurBoxOffset) {
  18885. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18886. }
  18887. }
  18888. if (parsedShadowGenerator.bias !== undefined) {
  18889. shadowGenerator.bias = parsedShadowGenerator.bias;
  18890. }
  18891. return shadowGenerator;
  18892. };
  18893. var parseAnimation = function (parsedAnimation) {
  18894. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18895. var dataType = parsedAnimation.dataType;
  18896. var keys = [];
  18897. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18898. var key = parsedAnimation.keys[index];
  18899. var data;
  18900. switch (dataType) {
  18901. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18902. data = key.values[0];
  18903. break;
  18904. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18905. data = BABYLON.Quaternion.FromArray(key.values);
  18906. break;
  18907. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18908. data = BABYLON.Matrix.FromArray(key.values);
  18909. break;
  18910. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18911. default:
  18912. data = BABYLON.Vector3.FromArray(key.values);
  18913. break;
  18914. }
  18915. keys.push({
  18916. frame: key.frame,
  18917. value: data
  18918. });
  18919. }
  18920. animation.setKeys(keys);
  18921. return animation;
  18922. };
  18923. var parseLight = function (parsedLight, scene) {
  18924. var light;
  18925. switch (parsedLight.type) {
  18926. case 0:
  18927. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18928. break;
  18929. case 1:
  18930. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18931. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18932. break;
  18933. case 2:
  18934. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18935. break;
  18936. case 3:
  18937. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18938. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18939. break;
  18940. }
  18941. light.id = parsedLight.id;
  18942. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18943. if (parsedLight.intensity !== undefined) {
  18944. light.intensity = parsedLight.intensity;
  18945. }
  18946. if (parsedLight.range) {
  18947. light.range = parsedLight.range;
  18948. }
  18949. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18950. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18951. if (parsedLight.excludedMeshesIds) {
  18952. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18953. }
  18954. // Parent
  18955. if (parsedLight.parentId) {
  18956. light._waitingParentId = parsedLight.parentId;
  18957. }
  18958. if (parsedLight.includedOnlyMeshesIds) {
  18959. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18960. }
  18961. // Animations
  18962. if (parsedLight.animations) {
  18963. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18964. var parsedAnimation = parsedLight.animations[animationIndex];
  18965. light.animations.push(parseAnimation(parsedAnimation));
  18966. }
  18967. }
  18968. if (parsedLight.autoAnimate) {
  18969. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18970. }
  18971. };
  18972. var parseCamera = function (parsedCamera, scene) {
  18973. var camera;
  18974. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18975. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18976. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18977. var alpha = parsedCamera.alpha;
  18978. var beta = parsedCamera.beta;
  18979. var radius = parsedCamera.radius;
  18980. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18981. var eye_space = parsedCamera.eye_space;
  18982. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18983. }
  18984. else {
  18985. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18986. }
  18987. }
  18988. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18989. eye_space = parsedCamera.eye_space;
  18990. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18991. }
  18992. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18993. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18994. }
  18995. else if (parsedCamera.type === "FollowCamera") {
  18996. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18997. camera.heightOffset = parsedCamera.heightOffset;
  18998. camera.radius = parsedCamera.radius;
  18999. camera.rotationOffset = parsedCamera.rotationOffset;
  19000. if (lockedTargetMesh)
  19001. camera.target = lockedTargetMesh;
  19002. }
  19003. else if (parsedCamera.type === "GamepadCamera") {
  19004. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19005. }
  19006. else if (parsedCamera.type === "TouchCamera") {
  19007. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19008. }
  19009. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19010. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19011. }
  19012. else if (parsedCamera.type === "WebVRFreeCamera") {
  19013. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19014. }
  19015. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19016. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19017. }
  19018. else {
  19019. // Free Camera is the default value
  19020. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19021. }
  19022. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19023. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19024. camera.lockedTarget = lockedTargetMesh;
  19025. }
  19026. camera.id = parsedCamera.id;
  19027. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19028. // Parent
  19029. if (parsedCamera.parentId) {
  19030. camera._waitingParentId = parsedCamera.parentId;
  19031. }
  19032. // Target
  19033. if (parsedCamera.target) {
  19034. if (camera.setTarget) {
  19035. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19036. }
  19037. else {
  19038. //For ArcRotate
  19039. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19040. }
  19041. }
  19042. else {
  19043. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19044. }
  19045. camera.fov = parsedCamera.fov;
  19046. camera.minZ = parsedCamera.minZ;
  19047. camera.maxZ = parsedCamera.maxZ;
  19048. camera.speed = parsedCamera.speed;
  19049. camera.inertia = parsedCamera.inertia;
  19050. camera.checkCollisions = parsedCamera.checkCollisions;
  19051. camera.applyGravity = parsedCamera.applyGravity;
  19052. if (parsedCamera.ellipsoid) {
  19053. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19054. }
  19055. // Animations
  19056. if (parsedCamera.animations) {
  19057. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19058. var parsedAnimation = parsedCamera.animations[animationIndex];
  19059. camera.animations.push(parseAnimation(parsedAnimation));
  19060. }
  19061. }
  19062. if (parsedCamera.autoAnimate) {
  19063. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19064. }
  19065. // Layer Mask
  19066. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19067. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19068. }
  19069. else {
  19070. camera.layerMask = 0xFFFFFFFF;
  19071. }
  19072. return camera;
  19073. };
  19074. var parseGeometry = function (parsedGeometry, scene) {
  19075. var id = parsedGeometry.id;
  19076. return scene.getGeometryByID(id);
  19077. };
  19078. var parseBox = function (parsedBox, scene) {
  19079. if (parseGeometry(parsedBox, scene)) {
  19080. return null; // null since geometry could be something else than a box...
  19081. }
  19082. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19083. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19084. scene.pushGeometry(box, true);
  19085. return box;
  19086. };
  19087. var parseSphere = function (parsedSphere, scene) {
  19088. if (parseGeometry(parsedSphere, scene)) {
  19089. return null; // null since geometry could be something else than a sphere...
  19090. }
  19091. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19092. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19093. scene.pushGeometry(sphere, true);
  19094. return sphere;
  19095. };
  19096. var parseCylinder = function (parsedCylinder, scene) {
  19097. if (parseGeometry(parsedCylinder, scene)) {
  19098. return null; // null since geometry could be something else than a cylinder...
  19099. }
  19100. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19101. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19102. scene.pushGeometry(cylinder, true);
  19103. return cylinder;
  19104. };
  19105. var parseTorus = function (parsedTorus, scene) {
  19106. if (parseGeometry(parsedTorus, scene)) {
  19107. return null; // null since geometry could be something else than a torus...
  19108. }
  19109. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19110. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19111. scene.pushGeometry(torus, true);
  19112. return torus;
  19113. };
  19114. var parseGround = function (parsedGround, scene) {
  19115. if (parseGeometry(parsedGround, scene)) {
  19116. return null; // null since geometry could be something else than a ground...
  19117. }
  19118. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19119. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19120. scene.pushGeometry(ground, true);
  19121. return ground;
  19122. };
  19123. var parsePlane = function (parsedPlane, scene) {
  19124. if (parseGeometry(parsedPlane, scene)) {
  19125. return null; // null since geometry could be something else than a plane...
  19126. }
  19127. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19128. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19129. scene.pushGeometry(plane, true);
  19130. return plane;
  19131. };
  19132. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19133. if (parseGeometry(parsedTorusKnot, scene)) {
  19134. return null; // null since geometry could be something else than a torusKnot...
  19135. }
  19136. 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);
  19137. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19138. scene.pushGeometry(torusKnot, true);
  19139. return torusKnot;
  19140. };
  19141. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19142. if (parseGeometry(parsedVertexData, scene)) {
  19143. return null; // null since geometry could be a primitive
  19144. }
  19145. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19146. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19147. if (parsedVertexData.delayLoadingFile) {
  19148. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19149. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19150. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19151. geometry._delayInfo = [];
  19152. if (parsedVertexData.hasUVs) {
  19153. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19154. }
  19155. if (parsedVertexData.hasUVs2) {
  19156. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19157. }
  19158. if (parsedVertexData.hasColors) {
  19159. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19160. }
  19161. if (parsedVertexData.hasMatricesIndices) {
  19162. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19163. }
  19164. if (parsedVertexData.hasMatricesWeights) {
  19165. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19166. }
  19167. geometry._delayLoadingFunction = importVertexData;
  19168. }
  19169. else {
  19170. importVertexData(parsedVertexData, geometry);
  19171. }
  19172. scene.pushGeometry(geometry, true);
  19173. return geometry;
  19174. };
  19175. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19176. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19177. mesh.id = parsedMesh.id;
  19178. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19179. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19180. if (parsedMesh.rotationQuaternion) {
  19181. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19182. }
  19183. else if (parsedMesh.rotation) {
  19184. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19185. }
  19186. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19187. if (parsedMesh.localMatrix) {
  19188. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19189. }
  19190. else if (parsedMesh.pivotMatrix) {
  19191. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19192. }
  19193. mesh.setEnabled(parsedMesh.isEnabled);
  19194. mesh.isVisible = parsedMesh.isVisible;
  19195. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19196. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19197. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19198. if (parsedMesh.applyFog !== undefined) {
  19199. mesh.applyFog = parsedMesh.applyFog;
  19200. }
  19201. if (parsedMesh.pickable !== undefined) {
  19202. mesh.isPickable = parsedMesh.pickable;
  19203. }
  19204. if (parsedMesh.alphaIndex !== undefined) {
  19205. mesh.alphaIndex = parsedMesh.alphaIndex;
  19206. }
  19207. mesh.receiveShadows = parsedMesh.receiveShadows;
  19208. mesh.billboardMode = parsedMesh.billboardMode;
  19209. if (parsedMesh.visibility !== undefined) {
  19210. mesh.visibility = parsedMesh.visibility;
  19211. }
  19212. mesh.checkCollisions = parsedMesh.checkCollisions;
  19213. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19214. // Parent
  19215. if (parsedMesh.parentId) {
  19216. mesh._waitingParentId = parsedMesh.parentId;
  19217. }
  19218. // Actions
  19219. if (parsedMesh.actions !== undefined) {
  19220. mesh._waitingActions = parsedMesh.actions;
  19221. }
  19222. // Geometry
  19223. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19224. if (parsedMesh.delayLoadingFile) {
  19225. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19226. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19227. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19228. if (parsedMesh._binaryInfo) {
  19229. mesh._binaryInfo = parsedMesh._binaryInfo;
  19230. }
  19231. mesh._delayInfo = [];
  19232. if (parsedMesh.hasUVs) {
  19233. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19234. }
  19235. if (parsedMesh.hasUVs2) {
  19236. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19237. }
  19238. if (parsedMesh.hasColors) {
  19239. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19240. }
  19241. if (parsedMesh.hasMatricesIndices) {
  19242. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19243. }
  19244. if (parsedMesh.hasMatricesWeights) {
  19245. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19246. }
  19247. mesh._delayLoadingFunction = importGeometry;
  19248. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19249. mesh._checkDelayState();
  19250. }
  19251. }
  19252. else {
  19253. importGeometry(parsedMesh, mesh);
  19254. }
  19255. // Material
  19256. if (parsedMesh.materialId) {
  19257. mesh.setMaterialByID(parsedMesh.materialId);
  19258. }
  19259. else {
  19260. mesh.material = null;
  19261. }
  19262. // Skeleton
  19263. if (parsedMesh.skeletonId > -1) {
  19264. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19265. }
  19266. // Physics
  19267. if (parsedMesh.physicsImpostor) {
  19268. if (!scene.isPhysicsEnabled()) {
  19269. scene.enablePhysics();
  19270. }
  19271. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19272. }
  19273. // Animations
  19274. if (parsedMesh.animations) {
  19275. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19276. var parsedAnimation = parsedMesh.animations[animationIndex];
  19277. mesh.animations.push(parseAnimation(parsedAnimation));
  19278. }
  19279. }
  19280. if (parsedMesh.autoAnimate) {
  19281. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19282. }
  19283. // Layer Mask
  19284. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19285. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19286. }
  19287. else {
  19288. mesh.layerMask = 0xFFFFFFFF;
  19289. }
  19290. // Instances
  19291. if (parsedMesh.instances) {
  19292. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19293. var parsedInstance = parsedMesh.instances[index];
  19294. var instance = mesh.createInstance(parsedInstance.name);
  19295. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19296. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19297. if (parsedInstance.rotationQuaternion) {
  19298. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19299. }
  19300. else if (parsedInstance.rotation) {
  19301. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19302. }
  19303. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19304. instance.checkCollisions = mesh.checkCollisions;
  19305. if (parsedMesh.animations) {
  19306. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19307. parsedAnimation = parsedMesh.animations[animationIndex];
  19308. instance.animations.push(parseAnimation(parsedAnimation));
  19309. }
  19310. }
  19311. }
  19312. }
  19313. return mesh;
  19314. };
  19315. var parseActions = function (parsedActions, object, scene) {
  19316. var actionManager = new BABYLON.ActionManager(scene);
  19317. if (object === null)
  19318. scene.actionManager = actionManager;
  19319. else
  19320. object.actionManager = actionManager;
  19321. // instanciate a new object
  19322. var instanciate = function (name, params) {
  19323. var newInstance = Object.create(BABYLON[name].prototype);
  19324. newInstance.constructor.apply(newInstance, params);
  19325. return newInstance;
  19326. };
  19327. var parseParameter = function (name, value, target, propertyPath) {
  19328. if (propertyPath === null) {
  19329. // String, boolean or float
  19330. var floatValue = parseFloat(value);
  19331. if (value === "true" || value === "false")
  19332. return value === "true";
  19333. else
  19334. return isNaN(floatValue) ? value : floatValue;
  19335. }
  19336. var effectiveTarget = propertyPath.split(".");
  19337. var values = value.split(",");
  19338. for (var i = 0; i < effectiveTarget.length; i++) {
  19339. target = target[effectiveTarget[i]];
  19340. }
  19341. // Return appropriate value with its type
  19342. if (typeof (target) === "boolean")
  19343. return values[0] === "true";
  19344. if (typeof (target) === "string")
  19345. return values[0];
  19346. // Parameters with multiple values such as Vector3 etc.
  19347. var split = new Array();
  19348. for (var i = 0; i < values.length; i++)
  19349. split.push(parseFloat(values[i]));
  19350. if (target instanceof BABYLON.Vector3)
  19351. return BABYLON.Vector3.FromArray(split);
  19352. if (target instanceof BABYLON.Vector4)
  19353. return BABYLON.Vector4.FromArray(split);
  19354. if (target instanceof BABYLON.Color3)
  19355. return BABYLON.Color3.FromArray(split);
  19356. if (target instanceof BABYLON.Color4)
  19357. return BABYLON.Color4.FromArray(split);
  19358. return parseFloat(values[0]);
  19359. };
  19360. // traverse graph per trigger
  19361. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19362. if (combineArray === void 0) { combineArray = null; }
  19363. if (parsedAction.detached)
  19364. return;
  19365. var parameters = new Array();
  19366. var target = null;
  19367. var propertyPath = null;
  19368. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19369. // Parameters
  19370. if (parsedAction.type === 2)
  19371. parameters.push(actionManager);
  19372. else
  19373. parameters.push(trigger);
  19374. if (combine) {
  19375. var actions = new Array();
  19376. for (var j = 0; j < parsedAction.combine.length; j++) {
  19377. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19378. }
  19379. parameters.push(actions);
  19380. }
  19381. else {
  19382. for (var i = 0; i < parsedAction.properties.length; i++) {
  19383. var value = parsedAction.properties[i].value;
  19384. var name = parsedAction.properties[i].name;
  19385. var targetType = parsedAction.properties[i].targetType;
  19386. if (name === "target")
  19387. if (targetType !== null && targetType === "SceneProperties")
  19388. value = target = scene;
  19389. else
  19390. value = target = scene.getNodeByName(value);
  19391. else if (name === "parent")
  19392. value = scene.getNodeByName(value);
  19393. else if (name === "sound")
  19394. value = scene.getSoundByName(value);
  19395. else if (name !== "propertyPath") {
  19396. if (parsedAction.type === 2 && name === "operator")
  19397. value = BABYLON.ValueCondition[value];
  19398. else
  19399. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19400. }
  19401. else {
  19402. propertyPath = value;
  19403. }
  19404. parameters.push(value);
  19405. }
  19406. }
  19407. if (combineArray === null) {
  19408. parameters.push(condition);
  19409. }
  19410. else {
  19411. parameters.push(null);
  19412. }
  19413. // If interpolate value action
  19414. if (parsedAction.name === "InterpolateValueAction") {
  19415. var param = parameters[parameters.length - 2];
  19416. parameters[parameters.length - 1] = param;
  19417. parameters[parameters.length - 2] = condition;
  19418. }
  19419. // Action or condition(s) and not CombineAction
  19420. var newAction = instanciate(parsedAction.name, parameters);
  19421. if (combineArray === null) {
  19422. if (newAction instanceof BABYLON.Condition) {
  19423. condition = newAction;
  19424. newAction = action;
  19425. }
  19426. else {
  19427. condition = null;
  19428. if (action)
  19429. action.then(newAction);
  19430. else
  19431. actionManager.registerAction(newAction);
  19432. }
  19433. }
  19434. else {
  19435. combineArray.push(newAction);
  19436. }
  19437. for (var i = 0; i < parsedAction.children.length; i++)
  19438. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19439. };
  19440. for (var i = 0; i < parsedActions.children.length; i++) {
  19441. var triggerParams;
  19442. var trigger = parsedActions.children[i];
  19443. if (trigger.properties.length > 0) {
  19444. var param = trigger.properties[0].value;
  19445. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19446. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19447. }
  19448. else
  19449. triggerParams = BABYLON.ActionManager[trigger.name];
  19450. for (var j = 0; j < trigger.children.length; j++) {
  19451. if (!trigger.detached)
  19452. traverse(trigger.children[j], triggerParams, null, null);
  19453. }
  19454. }
  19455. };
  19456. var parseSound = function (parsedSound, scene, rootUrl) {
  19457. var soundName = parsedSound.name;
  19458. var soundUrl = rootUrl + soundName;
  19459. var options = {
  19460. autoplay: parsedSound.autoplay,
  19461. loop: parsedSound.loop,
  19462. volume: parsedSound.volume,
  19463. spatialSound: parsedSound.spatialSound,
  19464. maxDistance: parsedSound.maxDistance,
  19465. rolloffFactor: parsedSound.rolloffFactor,
  19466. refDistance: parsedSound.refDistance,
  19467. distanceModel: parsedSound.distanceModel,
  19468. playbackRate: parsedSound.playbackRate
  19469. };
  19470. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19471. scene._removePendingData(newSound);
  19472. }, options);
  19473. scene._addPendingData(newSound);
  19474. if (parsedSound.position) {
  19475. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19476. newSound.setPosition(soundPosition);
  19477. }
  19478. if (parsedSound.isDirectional) {
  19479. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19480. if (parsedSound.localDirectionToMesh) {
  19481. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19482. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19483. }
  19484. }
  19485. if (parsedSound.connectedMeshId) {
  19486. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19487. if (connectedMesh) {
  19488. newSound.attachToMesh(connectedMesh);
  19489. }
  19490. }
  19491. };
  19492. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19493. names = (names instanceof Array) ? names : [names];
  19494. for (var i in names) {
  19495. if (mesh.name === names[i]) {
  19496. hierarchyIds.push(mesh.id);
  19497. return true;
  19498. }
  19499. }
  19500. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19501. hierarchyIds.push(mesh.id);
  19502. return true;
  19503. }
  19504. return false;
  19505. };
  19506. var importVertexData = function (parsedVertexData, geometry) {
  19507. var vertexData = new BABYLON.VertexData();
  19508. // positions
  19509. var positions = parsedVertexData.positions;
  19510. if (positions) {
  19511. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19512. }
  19513. // normals
  19514. var normals = parsedVertexData.normals;
  19515. if (normals) {
  19516. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19517. }
  19518. // uvs
  19519. var uvs = parsedVertexData.uvs;
  19520. if (uvs) {
  19521. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19522. }
  19523. // uv2s
  19524. var uv2s = parsedVertexData.uv2s;
  19525. if (uv2s) {
  19526. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19527. }
  19528. // colors
  19529. var colors = parsedVertexData.colors;
  19530. if (colors) {
  19531. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19532. }
  19533. // matricesIndices
  19534. var matricesIndices = parsedVertexData.matricesIndices;
  19535. if (matricesIndices) {
  19536. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19537. }
  19538. // matricesWeights
  19539. var matricesWeights = parsedVertexData.matricesWeights;
  19540. if (matricesWeights) {
  19541. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19542. }
  19543. // indices
  19544. var indices = parsedVertexData.indices;
  19545. if (indices) {
  19546. vertexData.indices = indices;
  19547. }
  19548. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19549. };
  19550. var importGeometry = function (parsedGeometry, mesh) {
  19551. var scene = mesh.getScene();
  19552. // Geometry
  19553. var geometryId = parsedGeometry.geometryId;
  19554. if (geometryId) {
  19555. var geometry = scene.getGeometryByID(geometryId);
  19556. if (geometry) {
  19557. geometry.applyToMesh(mesh);
  19558. }
  19559. }
  19560. else if (parsedGeometry instanceof ArrayBuffer) {
  19561. var binaryInfo = mesh._binaryInfo;
  19562. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19563. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19564. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19565. }
  19566. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19567. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19568. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19569. }
  19570. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19571. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19572. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19573. }
  19574. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19575. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19576. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19577. }
  19578. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19579. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19580. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19581. }
  19582. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19583. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19584. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19585. }
  19586. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19587. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19588. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19589. }
  19590. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19591. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19592. mesh.setIndices(indicesData);
  19593. }
  19594. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19595. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19596. mesh.subMeshes = [];
  19597. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19598. var materialIndex = subMeshesData[(i * 5) + 0];
  19599. var verticesStart = subMeshesData[(i * 5) + 1];
  19600. var verticesCount = subMeshesData[(i * 5) + 2];
  19601. var indexStart = subMeshesData[(i * 5) + 3];
  19602. var indexCount = subMeshesData[(i * 5) + 4];
  19603. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19604. }
  19605. }
  19606. }
  19607. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19608. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19609. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19610. if (parsedGeometry.uvs) {
  19611. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19612. }
  19613. if (parsedGeometry.uvs2) {
  19614. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19615. }
  19616. if (parsedGeometry.colors) {
  19617. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19618. }
  19619. if (parsedGeometry.matricesIndices) {
  19620. if (!parsedGeometry.matricesIndices._isExpanded) {
  19621. var floatIndices = [];
  19622. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19623. var matricesIndex = parsedGeometry.matricesIndices[i];
  19624. floatIndices.push(matricesIndex & 0x000000FF);
  19625. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19626. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19627. floatIndices.push(matricesIndex >> 24);
  19628. }
  19629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19630. }
  19631. else {
  19632. delete parsedGeometry.matricesIndices._isExpanded;
  19633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19634. }
  19635. }
  19636. if (parsedGeometry.matricesWeights) {
  19637. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19638. }
  19639. mesh.setIndices(parsedGeometry.indices);
  19640. // SubMeshes
  19641. if (parsedGeometry.subMeshes) {
  19642. mesh.subMeshes = [];
  19643. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19644. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19645. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19646. }
  19647. }
  19648. }
  19649. // Flat shading
  19650. if (mesh._shouldGenerateFlatShading) {
  19651. mesh.convertToFlatShadedMesh();
  19652. delete mesh._shouldGenerateFlatShading;
  19653. }
  19654. // Update
  19655. mesh.computeWorldMatrix(true);
  19656. // Octree
  19657. if (scene._selectionOctree) {
  19658. scene._selectionOctree.addMesh(mesh);
  19659. }
  19660. };
  19661. BABYLON.SceneLoader.RegisterPlugin({
  19662. extensions: ".babylon",
  19663. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19664. var parsedData = JSON.parse(data);
  19665. var loadedSkeletonsIds = [];
  19666. var loadedMaterialsIds = [];
  19667. var hierarchyIds = [];
  19668. for (var index = 0; index < parsedData.meshes.length; index++) {
  19669. var parsedMesh = parsedData.meshes[index];
  19670. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19671. if (meshesNames instanceof Array) {
  19672. // Remove found mesh name from list.
  19673. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19674. }
  19675. //Geometry?
  19676. if (parsedMesh.geometryId) {
  19677. //does the file contain geometries?
  19678. if (parsedData.geometries) {
  19679. //find the correct geometry and add it to the scene
  19680. var found = false;
  19681. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19682. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19683. return;
  19684. }
  19685. else {
  19686. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19687. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19688. switch (geometryType) {
  19689. case "boxes":
  19690. parseBox(parsedGeometryData, scene);
  19691. break;
  19692. case "spheres":
  19693. parseSphere(parsedGeometryData, scene);
  19694. break;
  19695. case "cylinders":
  19696. parseCylinder(parsedGeometryData, scene);
  19697. break;
  19698. case "toruses":
  19699. parseTorus(parsedGeometryData, scene);
  19700. break;
  19701. case "grounds":
  19702. parseGround(parsedGeometryData, scene);
  19703. break;
  19704. case "planes":
  19705. parsePlane(parsedGeometryData, scene);
  19706. break;
  19707. case "torusKnots":
  19708. parseTorusKnot(parsedGeometryData, scene);
  19709. break;
  19710. case "vertexData":
  19711. parseVertexData(parsedGeometryData, scene, rootUrl);
  19712. break;
  19713. }
  19714. found = true;
  19715. }
  19716. });
  19717. }
  19718. });
  19719. }
  19720. }
  19721. // Material ?
  19722. if (parsedMesh.materialId) {
  19723. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19724. if (!materialFound) {
  19725. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19726. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19727. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19728. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19729. var subMatId = parsedMultiMaterial.materials[matIndex];
  19730. loadedMaterialsIds.push(subMatId);
  19731. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19732. }
  19733. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19734. parseMultiMaterial(parsedMultiMaterial, scene);
  19735. materialFound = true;
  19736. break;
  19737. }
  19738. }
  19739. }
  19740. if (!materialFound) {
  19741. loadedMaterialsIds.push(parsedMesh.materialId);
  19742. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19743. }
  19744. }
  19745. // Skeleton ?
  19746. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19747. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19748. if (!skeletonAlreadyLoaded) {
  19749. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19750. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19751. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19752. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19753. loadedSkeletonsIds.push(parsedSkeleton.id);
  19754. }
  19755. }
  19756. }
  19757. }
  19758. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19759. meshes.push(mesh);
  19760. }
  19761. }
  19762. for (index = 0; index < scene.meshes.length; index++) {
  19763. var currentMesh = scene.meshes[index];
  19764. if (currentMesh._waitingParentId) {
  19765. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19766. currentMesh._waitingParentId = undefined;
  19767. }
  19768. }
  19769. // Particles
  19770. if (parsedData.particleSystems) {
  19771. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19772. var parsedParticleSystem = parsedData.particleSystems[index];
  19773. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19774. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19775. }
  19776. }
  19777. }
  19778. return true;
  19779. },
  19780. load: function (scene, data, rootUrl) {
  19781. var parsedData = JSON.parse(data);
  19782. // Scene
  19783. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19784. scene.autoClear = parsedData.autoClear;
  19785. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19786. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19787. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19788. // Fog
  19789. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19790. scene.fogMode = parsedData.fogMode;
  19791. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19792. scene.fogStart = parsedData.fogStart;
  19793. scene.fogEnd = parsedData.fogEnd;
  19794. scene.fogDensity = parsedData.fogDensity;
  19795. }
  19796. for (var index = 0; index < parsedData.lights.length; index++) {
  19797. var parsedLight = parsedData.lights[index];
  19798. parseLight(parsedLight, scene);
  19799. }
  19800. // Materials
  19801. if (parsedData.materials) {
  19802. for (index = 0; index < parsedData.materials.length; index++) {
  19803. var parsedMaterial = parsedData.materials[index];
  19804. parseMaterial(parsedMaterial, scene, rootUrl);
  19805. }
  19806. }
  19807. if (parsedData.multiMaterials) {
  19808. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19809. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19810. parseMultiMaterial(parsedMultiMaterial, scene);
  19811. }
  19812. }
  19813. // Skeletons
  19814. if (parsedData.skeletons) {
  19815. for (index = 0; index < parsedData.skeletons.length; index++) {
  19816. var parsedSkeleton = parsedData.skeletons[index];
  19817. parseSkeleton(parsedSkeleton, scene);
  19818. }
  19819. }
  19820. // Geometries
  19821. var geometries = parsedData.geometries;
  19822. if (geometries) {
  19823. // Boxes
  19824. var boxes = geometries.boxes;
  19825. if (boxes) {
  19826. for (index = 0; index < boxes.length; index++) {
  19827. var parsedBox = boxes[index];
  19828. parseBox(parsedBox, scene);
  19829. }
  19830. }
  19831. // Spheres
  19832. var spheres = geometries.spheres;
  19833. if (spheres) {
  19834. for (index = 0; index < spheres.length; index++) {
  19835. var parsedSphere = spheres[index];
  19836. parseSphere(parsedSphere, scene);
  19837. }
  19838. }
  19839. // Cylinders
  19840. var cylinders = geometries.cylinders;
  19841. if (cylinders) {
  19842. for (index = 0; index < cylinders.length; index++) {
  19843. var parsedCylinder = cylinders[index];
  19844. parseCylinder(parsedCylinder, scene);
  19845. }
  19846. }
  19847. // Toruses
  19848. var toruses = geometries.toruses;
  19849. if (toruses) {
  19850. for (index = 0; index < toruses.length; index++) {
  19851. var parsedTorus = toruses[index];
  19852. parseTorus(parsedTorus, scene);
  19853. }
  19854. }
  19855. // Grounds
  19856. var grounds = geometries.grounds;
  19857. if (grounds) {
  19858. for (index = 0; index < grounds.length; index++) {
  19859. var parsedGround = grounds[index];
  19860. parseGround(parsedGround, scene);
  19861. }
  19862. }
  19863. // Planes
  19864. var planes = geometries.planes;
  19865. if (planes) {
  19866. for (index = 0; index < planes.length; index++) {
  19867. var parsedPlane = planes[index];
  19868. parsePlane(parsedPlane, scene);
  19869. }
  19870. }
  19871. // TorusKnots
  19872. var torusKnots = geometries.torusKnots;
  19873. if (torusKnots) {
  19874. for (index = 0; index < torusKnots.length; index++) {
  19875. var parsedTorusKnot = torusKnots[index];
  19876. parseTorusKnot(parsedTorusKnot, scene);
  19877. }
  19878. }
  19879. // VertexData
  19880. var vertexData = geometries.vertexData;
  19881. if (vertexData) {
  19882. for (index = 0; index < vertexData.length; index++) {
  19883. var parsedVertexData = vertexData[index];
  19884. parseVertexData(parsedVertexData, scene, rootUrl);
  19885. }
  19886. }
  19887. }
  19888. for (index = 0; index < parsedData.meshes.length; index++) {
  19889. var parsedMesh = parsedData.meshes[index];
  19890. parseMesh(parsedMesh, scene, rootUrl);
  19891. }
  19892. for (index = 0; index < parsedData.cameras.length; index++) {
  19893. var parsedCamera = parsedData.cameras[index];
  19894. parseCamera(parsedCamera, scene);
  19895. }
  19896. if (parsedData.activeCameraID) {
  19897. scene.setActiveCameraByID(parsedData.activeCameraID);
  19898. }
  19899. for (index = 0; index < scene.cameras.length; index++) {
  19900. var camera = scene.cameras[index];
  19901. if (camera._waitingParentId) {
  19902. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19903. camera._waitingParentId = undefined;
  19904. }
  19905. }
  19906. for (index = 0; index < scene.lights.length; index++) {
  19907. var light = scene.lights[index];
  19908. if (light._waitingParentId) {
  19909. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19910. light._waitingParentId = undefined;
  19911. }
  19912. }
  19913. // Sounds
  19914. if (parsedData.sounds) {
  19915. for (index = 0; index < parsedData.sounds.length; index++) {
  19916. var parsedSound = parsedData.sounds[index];
  19917. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19918. parseSound(parsedSound, scene, rootUrl);
  19919. }
  19920. else {
  19921. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19922. }
  19923. }
  19924. }
  19925. for (index = 0; index < scene.meshes.length; index++) {
  19926. var mesh = scene.meshes[index];
  19927. if (mesh._waitingParentId) {
  19928. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19929. mesh._waitingParentId = undefined;
  19930. }
  19931. if (mesh._waitingActions) {
  19932. parseActions(mesh._waitingActions, mesh, scene);
  19933. mesh._waitingActions = undefined;
  19934. }
  19935. }
  19936. // Particles Systems
  19937. if (parsedData.particleSystems) {
  19938. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19939. var parsedParticleSystem = parsedData.particleSystems[index];
  19940. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19941. }
  19942. }
  19943. // Lens flares
  19944. if (parsedData.lensFlareSystems) {
  19945. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19946. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19947. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19948. }
  19949. }
  19950. // Shadows
  19951. if (parsedData.shadowGenerators) {
  19952. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19953. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19954. parseShadowGenerator(parsedShadowGenerator, scene);
  19955. }
  19956. }
  19957. // Actions (scene)
  19958. if (parsedData.actions) {
  19959. parseActions(parsedData.actions, null, scene);
  19960. }
  19961. // Finish
  19962. return true;
  19963. }
  19964. });
  19965. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19966. })(BABYLON || (BABYLON = {}));
  19967. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  19968. var BABYLON;
  19969. (function (BABYLON) {
  19970. var SpriteManager = (function () {
  19971. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  19972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19973. this.name = name;
  19974. this.cellSize = cellSize;
  19975. this.sprites = new Array();
  19976. this.renderingGroupId = 0;
  19977. this.fogEnabled = true;
  19978. this._vertexDeclaration = [4, 4, 4, 4];
  19979. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  19980. this._capacity = capacity;
  19981. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  19982. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19983. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19984. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  19985. this._scene = scene;
  19986. this._scene.spriteManagers.push(this);
  19987. // VBO
  19988. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19989. var indices = [];
  19990. var index = 0;
  19991. for (var count = 0; count < capacity; count++) {
  19992. indices.push(index);
  19993. indices.push(index + 1);
  19994. indices.push(index + 2);
  19995. indices.push(index);
  19996. indices.push(index + 2);
  19997. indices.push(index + 3);
  19998. index += 4;
  19999. }
  20000. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20001. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20002. // Effects
  20003. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20004. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20005. }
  20006. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20007. var arrayOffset = index * 16;
  20008. if (offsetX === 0)
  20009. offsetX = this._epsilon;
  20010. else if (offsetX === 1)
  20011. offsetX = 1 - this._epsilon;
  20012. if (offsetY === 0)
  20013. offsetY = this._epsilon;
  20014. else if (offsetY === 1)
  20015. offsetY = 1 - this._epsilon;
  20016. this._vertices[arrayOffset] = sprite.position.x;
  20017. this._vertices[arrayOffset + 1] = sprite.position.y;
  20018. this._vertices[arrayOffset + 2] = sprite.position.z;
  20019. this._vertices[arrayOffset + 3] = sprite.angle;
  20020. this._vertices[arrayOffset + 4] = sprite.width;
  20021. this._vertices[arrayOffset + 5] = sprite.height;
  20022. this._vertices[arrayOffset + 6] = offsetX;
  20023. this._vertices[arrayOffset + 7] = offsetY;
  20024. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20025. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20026. var offset = (sprite.cellIndex / rowSize) >> 0;
  20027. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20028. this._vertices[arrayOffset + 11] = offset;
  20029. // Color
  20030. this._vertices[arrayOffset + 12] = sprite.color.r;
  20031. this._vertices[arrayOffset + 13] = sprite.color.g;
  20032. this._vertices[arrayOffset + 14] = sprite.color.b;
  20033. this._vertices[arrayOffset + 15] = sprite.color.a;
  20034. };
  20035. SpriteManager.prototype.render = function () {
  20036. // Check
  20037. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20038. return;
  20039. var engine = this._scene.getEngine();
  20040. var baseSize = this._spriteTexture.getBaseSize();
  20041. // Sprites
  20042. var deltaTime = engine.getDeltaTime();
  20043. var max = Math.min(this._capacity, this.sprites.length);
  20044. var rowSize = baseSize.width / this.cellSize;
  20045. var offset = 0;
  20046. for (var index = 0; index < max; index++) {
  20047. var sprite = this.sprites[index];
  20048. if (!sprite) {
  20049. continue;
  20050. }
  20051. sprite._animate(deltaTime);
  20052. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20053. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20054. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20055. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20056. }
  20057. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20058. // Render
  20059. var effect = this._effectBase;
  20060. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20061. effect = this._effectFog;
  20062. }
  20063. engine.enableEffect(effect);
  20064. var viewMatrix = this._scene.getViewMatrix();
  20065. effect.setTexture("diffuseSampler", this._spriteTexture);
  20066. effect.setMatrix("view", viewMatrix);
  20067. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20068. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20069. // Fog
  20070. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20071. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20072. effect.setColor3("vFogColor", this._scene.fogColor);
  20073. }
  20074. // VBOs
  20075. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20076. // Draw order
  20077. engine.setDepthFunctionToLessOrEqual();
  20078. effect.setBool("alphaTest", true);
  20079. engine.setColorWrite(false);
  20080. engine.draw(true, 0, max * 6);
  20081. engine.setColorWrite(true);
  20082. effect.setBool("alphaTest", false);
  20083. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20084. engine.draw(true, 0, max * 6);
  20085. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20086. };
  20087. SpriteManager.prototype.dispose = function () {
  20088. if (this._vertexBuffer) {
  20089. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20090. this._vertexBuffer = null;
  20091. }
  20092. if (this._indexBuffer) {
  20093. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20094. this._indexBuffer = null;
  20095. }
  20096. if (this._spriteTexture) {
  20097. this._spriteTexture.dispose();
  20098. this._spriteTexture = null;
  20099. }
  20100. // Remove from scene
  20101. var index = this._scene.spriteManagers.indexOf(this);
  20102. this._scene.spriteManagers.splice(index, 1);
  20103. // Callback
  20104. if (this.onDispose) {
  20105. this.onDispose();
  20106. }
  20107. };
  20108. return SpriteManager;
  20109. })();
  20110. BABYLON.SpriteManager = SpriteManager;
  20111. })(BABYLON || (BABYLON = {}));
  20112. //# sourceMappingURL=babylon.spriteManager.js.map
  20113. var BABYLON;
  20114. (function (BABYLON) {
  20115. var Sprite = (function () {
  20116. function Sprite(name, manager) {
  20117. this.name = name;
  20118. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20119. this.width = 1.0;
  20120. this.height = 1.0;
  20121. this.angle = 0;
  20122. this.cellIndex = 0;
  20123. this.invertU = 0;
  20124. this.invertV = 0;
  20125. this.animations = new Array();
  20126. this._animationStarted = false;
  20127. this._loopAnimation = false;
  20128. this._fromIndex = 0;
  20129. this._toIndex = 0;
  20130. this._delay = 0;
  20131. this._direction = 1;
  20132. this._frameCount = 0;
  20133. this._time = 0;
  20134. this._manager = manager;
  20135. this._manager.sprites.push(this);
  20136. this.position = BABYLON.Vector3.Zero();
  20137. }
  20138. Object.defineProperty(Sprite.prototype, "size", {
  20139. get: function () {
  20140. return this.width;
  20141. },
  20142. set: function (value) {
  20143. this.width = value;
  20144. this.height = value;
  20145. },
  20146. enumerable: true,
  20147. configurable: true
  20148. });
  20149. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20150. this._fromIndex = from;
  20151. this._toIndex = to;
  20152. this._loopAnimation = loop;
  20153. this._delay = delay;
  20154. this._animationStarted = true;
  20155. this._direction = from < to ? 1 : -1;
  20156. this.cellIndex = from;
  20157. this._time = 0;
  20158. };
  20159. Sprite.prototype.stopAnimation = function () {
  20160. this._animationStarted = false;
  20161. };
  20162. Sprite.prototype._animate = function (deltaTime) {
  20163. if (!this._animationStarted)
  20164. return;
  20165. this._time += deltaTime;
  20166. if (this._time > this._delay) {
  20167. this._time = this._time % this._delay;
  20168. this.cellIndex += this._direction;
  20169. if (this.cellIndex == this._toIndex) {
  20170. if (this._loopAnimation) {
  20171. this.cellIndex = this._fromIndex;
  20172. }
  20173. else {
  20174. this._animationStarted = false;
  20175. if (this.disposeWhenFinishedAnimating) {
  20176. this.dispose();
  20177. }
  20178. }
  20179. }
  20180. }
  20181. };
  20182. Sprite.prototype.dispose = function () {
  20183. for (var i = 0; i < this._manager.sprites.length; i++) {
  20184. if (this._manager.sprites[i] == this) {
  20185. this._manager.sprites.splice(i, 1);
  20186. }
  20187. }
  20188. };
  20189. return Sprite;
  20190. })();
  20191. BABYLON.Sprite = Sprite;
  20192. })(BABYLON || (BABYLON = {}));
  20193. //# sourceMappingURL=babylon.sprite.js.map
  20194. var BABYLON;
  20195. (function (BABYLON) {
  20196. var Layer = (function () {
  20197. function Layer(name, imgUrl, scene, isBackground, color) {
  20198. this.name = name;
  20199. this._vertexDeclaration = [2];
  20200. this._vertexStrideSize = 2 * 4;
  20201. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20202. this.isBackground = isBackground === undefined ? true : isBackground;
  20203. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20204. this._scene = scene;
  20205. this._scene.layers.push(this);
  20206. // VBO
  20207. var vertices = [];
  20208. vertices.push(1, 1);
  20209. vertices.push(-1, 1);
  20210. vertices.push(-1, -1);
  20211. vertices.push(1, -1);
  20212. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20213. // Indices
  20214. var indices = [];
  20215. indices.push(0);
  20216. indices.push(1);
  20217. indices.push(2);
  20218. indices.push(0);
  20219. indices.push(2);
  20220. indices.push(3);
  20221. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20222. // Effects
  20223. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20224. }
  20225. Layer.prototype.render = function () {
  20226. // Check
  20227. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20228. return;
  20229. var engine = this._scene.getEngine();
  20230. // Render
  20231. engine.enableEffect(this._effect);
  20232. engine.setState(false);
  20233. // Texture
  20234. this._effect.setTexture("textureSampler", this.texture);
  20235. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20236. // Color
  20237. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20238. // VBOs
  20239. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20240. // Draw order
  20241. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20242. engine.draw(true, 0, 6);
  20243. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20244. };
  20245. Layer.prototype.dispose = function () {
  20246. if (this._vertexBuffer) {
  20247. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20248. this._vertexBuffer = null;
  20249. }
  20250. if (this._indexBuffer) {
  20251. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20252. this._indexBuffer = null;
  20253. }
  20254. if (this.texture) {
  20255. this.texture.dispose();
  20256. this.texture = null;
  20257. }
  20258. // Remove from scene
  20259. var index = this._scene.layers.indexOf(this);
  20260. this._scene.layers.splice(index, 1);
  20261. // Callback
  20262. if (this.onDispose) {
  20263. this.onDispose();
  20264. }
  20265. };
  20266. return Layer;
  20267. })();
  20268. BABYLON.Layer = Layer;
  20269. })(BABYLON || (BABYLON = {}));
  20270. //# sourceMappingURL=babylon.layer.js.map
  20271. var BABYLON;
  20272. (function (BABYLON) {
  20273. var Particle = (function () {
  20274. function Particle() {
  20275. this.position = BABYLON.Vector3.Zero();
  20276. this.direction = BABYLON.Vector3.Zero();
  20277. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20278. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20279. this.lifeTime = 1.0;
  20280. this.age = 0;
  20281. this.size = 0;
  20282. this.angle = 0;
  20283. this.angularSpeed = 0;
  20284. }
  20285. Particle.prototype.copyTo = function (other) {
  20286. other.position.copyFrom(this.position);
  20287. other.direction.copyFrom(this.direction);
  20288. other.color.copyFrom(this.color);
  20289. other.colorStep.copyFrom(this.colorStep);
  20290. other.lifeTime = this.lifeTime;
  20291. other.age = this.age;
  20292. other.size = this.size;
  20293. other.angle = this.angle;
  20294. other.angularSpeed = this.angularSpeed;
  20295. };
  20296. return Particle;
  20297. })();
  20298. BABYLON.Particle = Particle;
  20299. })(BABYLON || (BABYLON = {}));
  20300. //# sourceMappingURL=babylon.particle.js.map
  20301. var BABYLON;
  20302. (function (BABYLON) {
  20303. var randomNumber = function (min, max) {
  20304. if (min === max) {
  20305. return (min);
  20306. }
  20307. var random = Math.random();
  20308. return ((random * (max - min)) + min);
  20309. };
  20310. var ParticleSystem = (function () {
  20311. function ParticleSystem(name, capacity, scene, customEffect) {
  20312. var _this = this;
  20313. this.name = name;
  20314. this.renderingGroupId = 0;
  20315. this.emitter = null;
  20316. this.emitRate = 10;
  20317. this.manualEmitCount = -1;
  20318. this.updateSpeed = 0.01;
  20319. this.targetStopDuration = 0;
  20320. this.disposeOnStop = false;
  20321. this.minEmitPower = 1;
  20322. this.maxEmitPower = 1;
  20323. this.minLifeTime = 1;
  20324. this.maxLifeTime = 1;
  20325. this.minSize = 1;
  20326. this.maxSize = 1;
  20327. this.minAngularSpeed = 0;
  20328. this.maxAngularSpeed = 0;
  20329. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20330. this.forceDepthWrite = false;
  20331. this.gravity = BABYLON.Vector3.Zero();
  20332. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20333. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20334. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20335. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20336. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20337. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20338. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20339. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20340. this.particles = new Array();
  20341. this._vertexDeclaration = [3, 4, 4];
  20342. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20343. this._stockParticles = new Array();
  20344. this._newPartsExcess = 0;
  20345. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20346. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20347. this._scaledDirection = BABYLON.Vector3.Zero();
  20348. this._scaledGravity = BABYLON.Vector3.Zero();
  20349. this._currentRenderId = -1;
  20350. this._started = false;
  20351. this._stopped = false;
  20352. this._actualFrame = 0;
  20353. this.id = name;
  20354. this._capacity = capacity;
  20355. this._scene = scene;
  20356. this._customEffect = customEffect;
  20357. scene.particleSystems.push(this);
  20358. // VBO
  20359. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20360. var indices = [];
  20361. var index = 0;
  20362. for (var count = 0; count < capacity; count++) {
  20363. indices.push(index);
  20364. indices.push(index + 1);
  20365. indices.push(index + 2);
  20366. indices.push(index);
  20367. indices.push(index + 2);
  20368. indices.push(index + 3);
  20369. index += 4;
  20370. }
  20371. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20372. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20373. // Default behaviors
  20374. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20375. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20376. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20377. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20378. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20379. };
  20380. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20381. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20382. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20383. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20384. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20385. };
  20386. this.updateFunction = function (particles) {
  20387. for (var index = 0; index < particles.length; index++) {
  20388. var particle = particles[index];
  20389. particle.age += _this._scaledUpdateSpeed;
  20390. if (particle.age >= particle.lifeTime) {
  20391. _this.recycleParticle(particle);
  20392. index--;
  20393. continue;
  20394. }
  20395. else {
  20396. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20397. particle.color.addInPlace(_this._scaledColorStep);
  20398. if (particle.color.a < 0)
  20399. particle.color.a = 0;
  20400. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20401. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20402. particle.position.addInPlace(_this._scaledDirection);
  20403. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20404. particle.direction.addInPlace(_this._scaledGravity);
  20405. }
  20406. }
  20407. };
  20408. }
  20409. ParticleSystem.prototype.recycleParticle = function (particle) {
  20410. var lastParticle = this.particles.pop();
  20411. if (lastParticle !== particle) {
  20412. lastParticle.copyTo(particle);
  20413. this._stockParticles.push(lastParticle);
  20414. }
  20415. };
  20416. ParticleSystem.prototype.getCapacity = function () {
  20417. return this._capacity;
  20418. };
  20419. ParticleSystem.prototype.isAlive = function () {
  20420. return this._alive;
  20421. };
  20422. ParticleSystem.prototype.isStarted = function () {
  20423. return this._started;
  20424. };
  20425. ParticleSystem.prototype.start = function () {
  20426. this._started = true;
  20427. this._stopped = false;
  20428. this._actualFrame = 0;
  20429. };
  20430. ParticleSystem.prototype.stop = function () {
  20431. this._stopped = true;
  20432. };
  20433. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20434. var offset = index * 11;
  20435. this._vertices[offset] = particle.position.x;
  20436. this._vertices[offset + 1] = particle.position.y;
  20437. this._vertices[offset + 2] = particle.position.z;
  20438. this._vertices[offset + 3] = particle.color.r;
  20439. this._vertices[offset + 4] = particle.color.g;
  20440. this._vertices[offset + 5] = particle.color.b;
  20441. this._vertices[offset + 6] = particle.color.a;
  20442. this._vertices[offset + 7] = particle.angle;
  20443. this._vertices[offset + 8] = particle.size;
  20444. this._vertices[offset + 9] = offsetX;
  20445. this._vertices[offset + 10] = offsetY;
  20446. };
  20447. ParticleSystem.prototype._update = function (newParticles) {
  20448. // Update current
  20449. this._alive = this.particles.length > 0;
  20450. this.updateFunction(this.particles);
  20451. // Add new ones
  20452. var worldMatrix;
  20453. if (this.emitter.position) {
  20454. worldMatrix = this.emitter.getWorldMatrix();
  20455. }
  20456. else {
  20457. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20458. }
  20459. for (var index = 0; index < newParticles; index++) {
  20460. if (this.particles.length === this._capacity) {
  20461. break;
  20462. }
  20463. if (this._stockParticles.length !== 0) {
  20464. var particle = this._stockParticles.pop();
  20465. particle.age = 0;
  20466. }
  20467. else {
  20468. particle = new BABYLON.Particle();
  20469. }
  20470. this.particles.push(particle);
  20471. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20472. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20473. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20474. particle.size = randomNumber(this.minSize, this.maxSize);
  20475. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20476. this.startPositionFunction(worldMatrix, particle.position);
  20477. var step = randomNumber(0, 1.0);
  20478. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20479. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20480. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20481. }
  20482. };
  20483. ParticleSystem.prototype._getEffect = function () {
  20484. if (this._customEffect) {
  20485. return this._customEffect;
  20486. }
  20487. ;
  20488. var defines = [];
  20489. if (this._scene.clipPlane) {
  20490. defines.push("#define CLIPPLANE");
  20491. }
  20492. // Effect
  20493. var join = defines.join("\n");
  20494. if (this._cachedDefines !== join) {
  20495. this._cachedDefines = join;
  20496. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20497. }
  20498. return this._effect;
  20499. };
  20500. ParticleSystem.prototype.animate = function () {
  20501. if (!this._started)
  20502. return;
  20503. var effect = this._getEffect();
  20504. // Check
  20505. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20506. return;
  20507. if (this._currentRenderId === this._scene.getRenderId()) {
  20508. return;
  20509. }
  20510. this._currentRenderId = this._scene.getRenderId();
  20511. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20512. // determine the number of particles we need to create
  20513. var emitCout;
  20514. if (this.manualEmitCount > -1) {
  20515. emitCout = this.manualEmitCount;
  20516. this.manualEmitCount = 0;
  20517. }
  20518. else {
  20519. emitCout = this.emitRate;
  20520. }
  20521. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20522. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20523. if (this._newPartsExcess > 1.0) {
  20524. newParticles += this._newPartsExcess >> 0;
  20525. this._newPartsExcess -= this._newPartsExcess >> 0;
  20526. }
  20527. this._alive = false;
  20528. if (!this._stopped) {
  20529. this._actualFrame += this._scaledUpdateSpeed;
  20530. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20531. this.stop();
  20532. }
  20533. else {
  20534. newParticles = 0;
  20535. }
  20536. this._update(newParticles);
  20537. // Stopped?
  20538. if (this._stopped) {
  20539. if (!this._alive) {
  20540. this._started = false;
  20541. if (this.disposeOnStop) {
  20542. this._scene._toBeDisposed.push(this);
  20543. }
  20544. }
  20545. }
  20546. // Update VBO
  20547. var offset = 0;
  20548. for (var index = 0; index < this.particles.length; index++) {
  20549. var particle = this.particles[index];
  20550. this._appendParticleVertex(offset++, particle, 0, 0);
  20551. this._appendParticleVertex(offset++, particle, 1, 0);
  20552. this._appendParticleVertex(offset++, particle, 1, 1);
  20553. this._appendParticleVertex(offset++, particle, 0, 1);
  20554. }
  20555. var engine = this._scene.getEngine();
  20556. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20557. };
  20558. ParticleSystem.prototype.render = function () {
  20559. var effect = this._getEffect();
  20560. // Check
  20561. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20562. return 0;
  20563. var engine = this._scene.getEngine();
  20564. // Render
  20565. engine.enableEffect(effect);
  20566. engine.setState(false);
  20567. var viewMatrix = this._scene.getViewMatrix();
  20568. effect.setTexture("diffuseSampler", this.particleTexture);
  20569. effect.setMatrix("view", viewMatrix);
  20570. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20571. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20572. if (this._scene.clipPlane) {
  20573. var clipPlane = this._scene.clipPlane;
  20574. var invView = viewMatrix.clone();
  20575. invView.invert();
  20576. effect.setMatrix("invView", invView);
  20577. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20578. }
  20579. // VBOs
  20580. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20581. // Draw order
  20582. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20583. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20584. }
  20585. else {
  20586. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20587. }
  20588. if (this.forceDepthWrite) {
  20589. engine.setDepthWrite(true);
  20590. }
  20591. engine.draw(true, 0, this.particles.length * 6);
  20592. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20593. return this.particles.length;
  20594. };
  20595. ParticleSystem.prototype.dispose = function () {
  20596. if (this._vertexBuffer) {
  20597. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20598. this._vertexBuffer = null;
  20599. }
  20600. if (this._indexBuffer) {
  20601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20602. this._indexBuffer = null;
  20603. }
  20604. if (this.particleTexture) {
  20605. this.particleTexture.dispose();
  20606. this.particleTexture = null;
  20607. }
  20608. // Remove from scene
  20609. var index = this._scene.particleSystems.indexOf(this);
  20610. this._scene.particleSystems.splice(index, 1);
  20611. // Callback
  20612. if (this.onDispose) {
  20613. this.onDispose();
  20614. }
  20615. };
  20616. // Clone
  20617. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20618. var result = new ParticleSystem(name, this._capacity, this._scene);
  20619. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20620. if (newEmitter === undefined) {
  20621. newEmitter = this.emitter;
  20622. }
  20623. result.emitter = newEmitter;
  20624. if (this.particleTexture) {
  20625. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20626. }
  20627. result.start();
  20628. return result;
  20629. };
  20630. // Statics
  20631. ParticleSystem.BLENDMODE_ONEONE = 0;
  20632. ParticleSystem.BLENDMODE_STANDARD = 1;
  20633. return ParticleSystem;
  20634. })();
  20635. BABYLON.ParticleSystem = ParticleSystem;
  20636. })(BABYLON || (BABYLON = {}));
  20637. //# sourceMappingURL=babylon.particleSystem.js.map
  20638. var BABYLON;
  20639. (function (BABYLON) {
  20640. var Animation = (function () {
  20641. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20642. this.name = name;
  20643. this.targetProperty = targetProperty;
  20644. this.framePerSecond = framePerSecond;
  20645. this.dataType = dataType;
  20646. this.loopMode = loopMode;
  20647. this._offsetsCache = {};
  20648. this._highLimitsCache = {};
  20649. this._stopped = false;
  20650. this.targetPropertyPath = targetProperty.split(".");
  20651. this.dataType = dataType;
  20652. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20653. }
  20654. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20655. var dataType = undefined;
  20656. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20657. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20658. }
  20659. else if (from instanceof BABYLON.Quaternion) {
  20660. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20661. }
  20662. else if (from instanceof BABYLON.Vector3) {
  20663. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20664. }
  20665. else if (from instanceof BABYLON.Vector2) {
  20666. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20667. }
  20668. else if (from instanceof BABYLON.Color3) {
  20669. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20670. }
  20671. if (dataType == undefined) {
  20672. return null;
  20673. }
  20674. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20675. var keys = [];
  20676. keys.push({ frame: 0, value: from });
  20677. keys.push({ frame: totalFrame, value: to });
  20678. animation.setKeys(keys);
  20679. mesh.animations.push(animation);
  20680. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20681. };
  20682. // Methods
  20683. Animation.prototype.isStopped = function () {
  20684. return this._stopped;
  20685. };
  20686. Animation.prototype.getKeys = function () {
  20687. return this._keys;
  20688. };
  20689. Animation.prototype.getEasingFunction = function () {
  20690. return this._easingFunction;
  20691. };
  20692. Animation.prototype.setEasingFunction = function (easingFunction) {
  20693. this._easingFunction = easingFunction;
  20694. };
  20695. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20696. return startValue + (endValue - startValue) * gradient;
  20697. };
  20698. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20699. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20700. };
  20701. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20702. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20703. };
  20704. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20705. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20706. };
  20707. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20708. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20709. };
  20710. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20711. var startScale = new BABYLON.Vector3(0, 0, 0);
  20712. var startRotation = new BABYLON.Quaternion();
  20713. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20714. startValue.decompose(startScale, startRotation, startTranslation);
  20715. var endScale = new BABYLON.Vector3(0, 0, 0);
  20716. var endRotation = new BABYLON.Quaternion();
  20717. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20718. endValue.decompose(endScale, endRotation, endTranslation);
  20719. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20720. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20721. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20722. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20723. return result;
  20724. };
  20725. Animation.prototype.clone = function () {
  20726. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20727. clone.setKeys(this._keys);
  20728. return clone;
  20729. };
  20730. Animation.prototype.setKeys = function (values) {
  20731. this._keys = values.slice(0);
  20732. this._offsetsCache = {};
  20733. this._highLimitsCache = {};
  20734. };
  20735. Animation.prototype._getKeyValue = function (value) {
  20736. if (typeof value === "function") {
  20737. return value();
  20738. }
  20739. return value;
  20740. };
  20741. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20742. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20743. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20744. }
  20745. this.currentFrame = currentFrame;
  20746. // Try to get a hash to find the right key
  20747. 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));
  20748. if (this._keys[startKey].frame >= currentFrame) {
  20749. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20750. startKey--;
  20751. }
  20752. }
  20753. for (var key = startKey; key < this._keys.length; key++) {
  20754. if (this._keys[key + 1].frame >= currentFrame) {
  20755. var startValue = this._getKeyValue(this._keys[key].value);
  20756. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20757. // gradient : percent of currentFrame between the frame inf and the frame sup
  20758. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20759. // check for easingFunction and correction of gradient
  20760. if (this._easingFunction != null) {
  20761. gradient = this._easingFunction.ease(gradient);
  20762. }
  20763. switch (this.dataType) {
  20764. case Animation.ANIMATIONTYPE_FLOAT:
  20765. switch (loopMode) {
  20766. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20767. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20768. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20769. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20770. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20771. }
  20772. break;
  20773. case Animation.ANIMATIONTYPE_QUATERNION:
  20774. var quaternion = null;
  20775. switch (loopMode) {
  20776. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20777. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20778. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20779. break;
  20780. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20781. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20782. break;
  20783. }
  20784. return quaternion;
  20785. case Animation.ANIMATIONTYPE_VECTOR3:
  20786. switch (loopMode) {
  20787. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20788. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20789. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20790. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20791. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20792. }
  20793. case Animation.ANIMATIONTYPE_VECTOR2:
  20794. switch (loopMode) {
  20795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20797. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20799. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20800. }
  20801. case Animation.ANIMATIONTYPE_COLOR3:
  20802. switch (loopMode) {
  20803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20805. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20807. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20808. }
  20809. case Animation.ANIMATIONTYPE_MATRIX:
  20810. switch (loopMode) {
  20811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20813. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20814. return startValue;
  20815. }
  20816. default:
  20817. break;
  20818. }
  20819. break;
  20820. }
  20821. }
  20822. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20823. };
  20824. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20825. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20826. this._stopped = true;
  20827. return false;
  20828. }
  20829. var returnValue = true;
  20830. // Adding a start key at frame 0 if missing
  20831. if (this._keys[0].frame !== 0) {
  20832. var newKey = { frame: 0, value: this._keys[0].value };
  20833. this._keys.splice(0, 0, newKey);
  20834. }
  20835. // Check limits
  20836. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20837. from = this._keys[0].frame;
  20838. }
  20839. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20840. to = this._keys[this._keys.length - 1].frame;
  20841. }
  20842. // Compute ratio
  20843. var range = to - from;
  20844. var offsetValue;
  20845. // ratio represents the frame delta between from and to
  20846. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20847. var highLimitValue = 0;
  20848. if (ratio > range && !loop) {
  20849. returnValue = false;
  20850. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20851. }
  20852. else {
  20853. // Get max value if required
  20854. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20855. var keyOffset = to.toString() + from.toString();
  20856. if (!this._offsetsCache[keyOffset]) {
  20857. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20858. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20859. switch (this.dataType) {
  20860. case Animation.ANIMATIONTYPE_FLOAT:
  20861. this._offsetsCache[keyOffset] = toValue - fromValue;
  20862. break;
  20863. case Animation.ANIMATIONTYPE_QUATERNION:
  20864. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20865. break;
  20866. case Animation.ANIMATIONTYPE_VECTOR3:
  20867. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20868. case Animation.ANIMATIONTYPE_VECTOR2:
  20869. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20870. case Animation.ANIMATIONTYPE_COLOR3:
  20871. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20872. default:
  20873. break;
  20874. }
  20875. this._highLimitsCache[keyOffset] = toValue;
  20876. }
  20877. highLimitValue = this._highLimitsCache[keyOffset];
  20878. offsetValue = this._offsetsCache[keyOffset];
  20879. }
  20880. }
  20881. if (offsetValue === undefined) {
  20882. switch (this.dataType) {
  20883. case Animation.ANIMATIONTYPE_FLOAT:
  20884. offsetValue = 0;
  20885. break;
  20886. case Animation.ANIMATIONTYPE_QUATERNION:
  20887. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20888. break;
  20889. case Animation.ANIMATIONTYPE_VECTOR3:
  20890. offsetValue = BABYLON.Vector3.Zero();
  20891. break;
  20892. case Animation.ANIMATIONTYPE_VECTOR2:
  20893. offsetValue = BABYLON.Vector2.Zero();
  20894. break;
  20895. case Animation.ANIMATIONTYPE_COLOR3:
  20896. offsetValue = BABYLON.Color3.Black();
  20897. }
  20898. }
  20899. // Compute value
  20900. var repeatCount = (ratio / range) >> 0;
  20901. var currentFrame = returnValue ? from + ratio % range : to;
  20902. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  20903. // Set value
  20904. if (this.targetPropertyPath.length > 1) {
  20905. var property = this._target[this.targetPropertyPath[0]];
  20906. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  20907. property = property[this.targetPropertyPath[index]];
  20908. }
  20909. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  20910. }
  20911. else {
  20912. this._target[this.targetPropertyPath[0]] = currentValue;
  20913. }
  20914. if (this._target.markAsDirty) {
  20915. this._target.markAsDirty(this.targetProperty);
  20916. }
  20917. if (!returnValue) {
  20918. this._stopped = true;
  20919. }
  20920. return returnValue;
  20921. };
  20922. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  20923. get: function () {
  20924. return Animation._ANIMATIONTYPE_FLOAT;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  20930. get: function () {
  20931. return Animation._ANIMATIONTYPE_VECTOR3;
  20932. },
  20933. enumerable: true,
  20934. configurable: true
  20935. });
  20936. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  20937. get: function () {
  20938. return Animation._ANIMATIONTYPE_VECTOR2;
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  20944. get: function () {
  20945. return Animation._ANIMATIONTYPE_QUATERNION;
  20946. },
  20947. enumerable: true,
  20948. configurable: true
  20949. });
  20950. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  20951. get: function () {
  20952. return Animation._ANIMATIONTYPE_MATRIX;
  20953. },
  20954. enumerable: true,
  20955. configurable: true
  20956. });
  20957. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  20958. get: function () {
  20959. return Animation._ANIMATIONTYPE_COLOR3;
  20960. },
  20961. enumerable: true,
  20962. configurable: true
  20963. });
  20964. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  20965. get: function () {
  20966. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  20967. },
  20968. enumerable: true,
  20969. configurable: true
  20970. });
  20971. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  20972. get: function () {
  20973. return Animation._ANIMATIONLOOPMODE_CYCLE;
  20974. },
  20975. enumerable: true,
  20976. configurable: true
  20977. });
  20978. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  20979. get: function () {
  20980. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  20981. },
  20982. enumerable: true,
  20983. configurable: true
  20984. });
  20985. // Statics
  20986. Animation._ANIMATIONTYPE_FLOAT = 0;
  20987. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  20988. Animation._ANIMATIONTYPE_QUATERNION = 2;
  20989. Animation._ANIMATIONTYPE_MATRIX = 3;
  20990. Animation._ANIMATIONTYPE_COLOR3 = 4;
  20991. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  20992. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  20993. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  20994. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  20995. return Animation;
  20996. })();
  20997. BABYLON.Animation = Animation;
  20998. })(BABYLON || (BABYLON = {}));
  20999. //# sourceMappingURL=babylon.animation.js.map
  21000. var BABYLON;
  21001. (function (BABYLON) {
  21002. var Animatable = (function () {
  21003. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21004. if (fromFrame === void 0) { fromFrame = 0; }
  21005. if (toFrame === void 0) { toFrame = 100; }
  21006. if (loopAnimation === void 0) { loopAnimation = false; }
  21007. if (speedRatio === void 0) { speedRatio = 1.0; }
  21008. this.target = target;
  21009. this.fromFrame = fromFrame;
  21010. this.toFrame = toFrame;
  21011. this.loopAnimation = loopAnimation;
  21012. this.speedRatio = speedRatio;
  21013. this.onAnimationEnd = onAnimationEnd;
  21014. this._animations = new Array();
  21015. this._paused = false;
  21016. this.animationStarted = false;
  21017. if (animations) {
  21018. this.appendAnimations(target, animations);
  21019. }
  21020. this._scene = scene;
  21021. scene._activeAnimatables.push(this);
  21022. }
  21023. // Methods
  21024. Animatable.prototype.appendAnimations = function (target, animations) {
  21025. for (var index = 0; index < animations.length; index++) {
  21026. var animation = animations[index];
  21027. animation._target = target;
  21028. this._animations.push(animation);
  21029. }
  21030. };
  21031. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21032. var animations = this._animations;
  21033. for (var index = 0; index < animations.length; index++) {
  21034. if (animations[index].targetProperty === property) {
  21035. return animations[index];
  21036. }
  21037. }
  21038. return null;
  21039. };
  21040. Animatable.prototype.pause = function () {
  21041. if (this._paused) {
  21042. return;
  21043. }
  21044. this._paused = true;
  21045. };
  21046. Animatable.prototype.restart = function () {
  21047. this._paused = false;
  21048. };
  21049. Animatable.prototype.stop = function () {
  21050. var index = this._scene._activeAnimatables.indexOf(this);
  21051. if (index > -1) {
  21052. this._scene._activeAnimatables.splice(index, 1);
  21053. }
  21054. if (this.onAnimationEnd) {
  21055. this.onAnimationEnd();
  21056. }
  21057. };
  21058. Animatable.prototype._animate = function (delay) {
  21059. if (this._paused) {
  21060. if (!this._pausedDelay) {
  21061. this._pausedDelay = delay;
  21062. }
  21063. return true;
  21064. }
  21065. if (!this._localDelayOffset) {
  21066. this._localDelayOffset = delay;
  21067. }
  21068. else if (this._pausedDelay) {
  21069. this._localDelayOffset += delay - this._pausedDelay;
  21070. this._pausedDelay = null;
  21071. }
  21072. // Animating
  21073. var running = false;
  21074. var animations = this._animations;
  21075. for (var index = 0; index < animations.length; index++) {
  21076. var animation = animations[index];
  21077. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21078. running = running || isRunning;
  21079. }
  21080. if (!running) {
  21081. // Remove from active animatables
  21082. index = this._scene._activeAnimatables.indexOf(this);
  21083. this._scene._activeAnimatables.splice(index, 1);
  21084. }
  21085. if (!running && this.onAnimationEnd) {
  21086. this.onAnimationEnd();
  21087. }
  21088. return running;
  21089. };
  21090. return Animatable;
  21091. })();
  21092. BABYLON.Animatable = Animatable;
  21093. })(BABYLON || (BABYLON = {}));
  21094. //# sourceMappingURL=babylon.animatable.js.map
  21095. var __extends = this.__extends || function (d, b) {
  21096. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21097. function __() { this.constructor = d; }
  21098. __.prototype = b.prototype;
  21099. d.prototype = new __();
  21100. };
  21101. var BABYLON;
  21102. (function (BABYLON) {
  21103. var EasingFunction = (function () {
  21104. function EasingFunction() {
  21105. // Properties
  21106. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21107. }
  21108. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21109. get: function () {
  21110. return EasingFunction._EASINGMODE_EASEIN;
  21111. },
  21112. enumerable: true,
  21113. configurable: true
  21114. });
  21115. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21116. get: function () {
  21117. return EasingFunction._EASINGMODE_EASEOUT;
  21118. },
  21119. enumerable: true,
  21120. configurable: true
  21121. });
  21122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21123. get: function () {
  21124. return EasingFunction._EASINGMODE_EASEINOUT;
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21130. var n = Math.min(Math.max(easingMode, 0), 2);
  21131. this._easingMode = n;
  21132. };
  21133. EasingFunction.prototype.getEasingMode = function () {
  21134. return this._easingMode;
  21135. };
  21136. EasingFunction.prototype.easeInCore = function (gradient) {
  21137. throw new Error('You must implement this method');
  21138. };
  21139. EasingFunction.prototype.ease = function (gradient) {
  21140. switch (this._easingMode) {
  21141. case EasingFunction.EASINGMODE_EASEIN:
  21142. return this.easeInCore(gradient);
  21143. case EasingFunction.EASINGMODE_EASEOUT:
  21144. return (1 - this.easeInCore(1 - gradient));
  21145. }
  21146. if (gradient >= 0.5) {
  21147. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21148. }
  21149. return (this.easeInCore(gradient * 2) * 0.5);
  21150. };
  21151. //Statics
  21152. EasingFunction._EASINGMODE_EASEIN = 0;
  21153. EasingFunction._EASINGMODE_EASEOUT = 1;
  21154. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21155. return EasingFunction;
  21156. })();
  21157. BABYLON.EasingFunction = EasingFunction;
  21158. var CircleEase = (function (_super) {
  21159. __extends(CircleEase, _super);
  21160. function CircleEase() {
  21161. _super.apply(this, arguments);
  21162. }
  21163. CircleEase.prototype.easeInCore = function (gradient) {
  21164. gradient = Math.max(0, Math.min(1, gradient));
  21165. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21166. };
  21167. return CircleEase;
  21168. })(EasingFunction);
  21169. BABYLON.CircleEase = CircleEase;
  21170. var BackEase = (function (_super) {
  21171. __extends(BackEase, _super);
  21172. function BackEase(amplitude) {
  21173. if (amplitude === void 0) { amplitude = 1; }
  21174. _super.call(this);
  21175. this.amplitude = amplitude;
  21176. }
  21177. BackEase.prototype.easeInCore = function (gradient) {
  21178. var num = Math.max(0, this.amplitude);
  21179. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21180. };
  21181. return BackEase;
  21182. })(EasingFunction);
  21183. BABYLON.BackEase = BackEase;
  21184. var BounceEase = (function (_super) {
  21185. __extends(BounceEase, _super);
  21186. function BounceEase(bounces, bounciness) {
  21187. if (bounces === void 0) { bounces = 3; }
  21188. if (bounciness === void 0) { bounciness = 2; }
  21189. _super.call(this);
  21190. this.bounces = bounces;
  21191. this.bounciness = bounciness;
  21192. }
  21193. BounceEase.prototype.easeInCore = function (gradient) {
  21194. var y = Math.max(0.0, this.bounces);
  21195. var bounciness = this.bounciness;
  21196. if (bounciness <= 1.0) {
  21197. bounciness = 1.001;
  21198. }
  21199. var num9 = Math.pow(bounciness, y);
  21200. var num5 = 1.0 - bounciness;
  21201. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21202. var num15 = gradient * num4;
  21203. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21204. var num3 = Math.floor(num65);
  21205. var num13 = num3 + 1.0;
  21206. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21207. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21208. var num7 = (num8 + num12) * 0.5;
  21209. var num6 = gradient - num7;
  21210. var num2 = num7 - num8;
  21211. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21212. };
  21213. return BounceEase;
  21214. })(EasingFunction);
  21215. BABYLON.BounceEase = BounceEase;
  21216. var CubicEase = (function (_super) {
  21217. __extends(CubicEase, _super);
  21218. function CubicEase() {
  21219. _super.apply(this, arguments);
  21220. }
  21221. CubicEase.prototype.easeInCore = function (gradient) {
  21222. return (gradient * gradient * gradient);
  21223. };
  21224. return CubicEase;
  21225. })(EasingFunction);
  21226. BABYLON.CubicEase = CubicEase;
  21227. var ElasticEase = (function (_super) {
  21228. __extends(ElasticEase, _super);
  21229. function ElasticEase(oscillations, springiness) {
  21230. if (oscillations === void 0) { oscillations = 3; }
  21231. if (springiness === void 0) { springiness = 3; }
  21232. _super.call(this);
  21233. this.oscillations = oscillations;
  21234. this.springiness = springiness;
  21235. }
  21236. ElasticEase.prototype.easeInCore = function (gradient) {
  21237. var num2;
  21238. var num3 = Math.max(0.0, this.oscillations);
  21239. var num = Math.max(0.0, this.springiness);
  21240. if (num == 0) {
  21241. num2 = gradient;
  21242. }
  21243. else {
  21244. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21245. }
  21246. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21247. };
  21248. return ElasticEase;
  21249. })(EasingFunction);
  21250. BABYLON.ElasticEase = ElasticEase;
  21251. var ExponentialEase = (function (_super) {
  21252. __extends(ExponentialEase, _super);
  21253. function ExponentialEase(exponent) {
  21254. if (exponent === void 0) { exponent = 2; }
  21255. _super.call(this);
  21256. this.exponent = exponent;
  21257. }
  21258. ExponentialEase.prototype.easeInCore = function (gradient) {
  21259. if (this.exponent <= 0) {
  21260. return gradient;
  21261. }
  21262. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21263. };
  21264. return ExponentialEase;
  21265. })(EasingFunction);
  21266. BABYLON.ExponentialEase = ExponentialEase;
  21267. var PowerEase = (function (_super) {
  21268. __extends(PowerEase, _super);
  21269. function PowerEase(power) {
  21270. if (power === void 0) { power = 2; }
  21271. _super.call(this);
  21272. this.power = power;
  21273. }
  21274. PowerEase.prototype.easeInCore = function (gradient) {
  21275. var y = Math.max(0.0, this.power);
  21276. return Math.pow(gradient, y);
  21277. };
  21278. return PowerEase;
  21279. })(EasingFunction);
  21280. BABYLON.PowerEase = PowerEase;
  21281. var QuadraticEase = (function (_super) {
  21282. __extends(QuadraticEase, _super);
  21283. function QuadraticEase() {
  21284. _super.apply(this, arguments);
  21285. }
  21286. QuadraticEase.prototype.easeInCore = function (gradient) {
  21287. return (gradient * gradient);
  21288. };
  21289. return QuadraticEase;
  21290. })(EasingFunction);
  21291. BABYLON.QuadraticEase = QuadraticEase;
  21292. var QuarticEase = (function (_super) {
  21293. __extends(QuarticEase, _super);
  21294. function QuarticEase() {
  21295. _super.apply(this, arguments);
  21296. }
  21297. QuarticEase.prototype.easeInCore = function (gradient) {
  21298. return (gradient * gradient * gradient * gradient);
  21299. };
  21300. return QuarticEase;
  21301. })(EasingFunction);
  21302. BABYLON.QuarticEase = QuarticEase;
  21303. var QuinticEase = (function (_super) {
  21304. __extends(QuinticEase, _super);
  21305. function QuinticEase() {
  21306. _super.apply(this, arguments);
  21307. }
  21308. QuinticEase.prototype.easeInCore = function (gradient) {
  21309. return (gradient * gradient * gradient * gradient * gradient);
  21310. };
  21311. return QuinticEase;
  21312. })(EasingFunction);
  21313. BABYLON.QuinticEase = QuinticEase;
  21314. var SineEase = (function (_super) {
  21315. __extends(SineEase, _super);
  21316. function SineEase() {
  21317. _super.apply(this, arguments);
  21318. }
  21319. SineEase.prototype.easeInCore = function (gradient) {
  21320. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21321. };
  21322. return SineEase;
  21323. })(EasingFunction);
  21324. BABYLON.SineEase = SineEase;
  21325. var BezierCurveEase = (function (_super) {
  21326. __extends(BezierCurveEase, _super);
  21327. function BezierCurveEase(x1, y1, x2, y2) {
  21328. if (x1 === void 0) { x1 = 0; }
  21329. if (y1 === void 0) { y1 = 0; }
  21330. if (x2 === void 0) { x2 = 1; }
  21331. if (y2 === void 0) { y2 = 1; }
  21332. _super.call(this);
  21333. this.x1 = x1;
  21334. this.y1 = y1;
  21335. this.x2 = x2;
  21336. this.y2 = y2;
  21337. }
  21338. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21339. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21340. };
  21341. return BezierCurveEase;
  21342. })(EasingFunction);
  21343. BABYLON.BezierCurveEase = BezierCurveEase;
  21344. })(BABYLON || (BABYLON = {}));
  21345. //# sourceMappingURL=babylon.easing.js.map
  21346. var BABYLON;
  21347. (function (BABYLON) {
  21348. var Octree = (function () {
  21349. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21350. if (maxDepth === void 0) { maxDepth = 2; }
  21351. this.maxDepth = maxDepth;
  21352. this.dynamicContent = new Array();
  21353. this._maxBlockCapacity = maxBlockCapacity || 64;
  21354. this._selectionContent = new BABYLON.SmartArray(1024);
  21355. this._creationFunc = creationFunc;
  21356. }
  21357. // Methods
  21358. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21359. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21360. };
  21361. Octree.prototype.addMesh = function (entry) {
  21362. for (var index = 0; index < this.blocks.length; index++) {
  21363. var block = this.blocks[index];
  21364. block.addEntry(entry);
  21365. }
  21366. };
  21367. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21368. this._selectionContent.reset();
  21369. for (var index = 0; index < this.blocks.length; index++) {
  21370. var block = this.blocks[index];
  21371. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21372. }
  21373. if (allowDuplicate) {
  21374. this._selectionContent.concat(this.dynamicContent);
  21375. }
  21376. else {
  21377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21378. }
  21379. return this._selectionContent;
  21380. };
  21381. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21382. this._selectionContent.reset();
  21383. for (var index = 0; index < this.blocks.length; index++) {
  21384. var block = this.blocks[index];
  21385. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21386. }
  21387. if (allowDuplicate) {
  21388. this._selectionContent.concat(this.dynamicContent);
  21389. }
  21390. else {
  21391. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21392. }
  21393. return this._selectionContent;
  21394. };
  21395. Octree.prototype.intersectsRay = function (ray) {
  21396. this._selectionContent.reset();
  21397. for (var index = 0; index < this.blocks.length; index++) {
  21398. var block = this.blocks[index];
  21399. block.intersectsRay(ray, this._selectionContent);
  21400. }
  21401. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21402. return this._selectionContent;
  21403. };
  21404. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21405. target.blocks = new Array();
  21406. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21407. for (var x = 0; x < 2; x++) {
  21408. for (var y = 0; y < 2; y++) {
  21409. for (var z = 0; z < 2; z++) {
  21410. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21411. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21412. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21413. block.addEntries(entries);
  21414. target.blocks.push(block);
  21415. }
  21416. }
  21417. }
  21418. };
  21419. Octree.CreationFuncForMeshes = function (entry, block) {
  21420. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21421. block.entries.push(entry);
  21422. }
  21423. };
  21424. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21425. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21426. block.entries.push(entry);
  21427. }
  21428. };
  21429. return Octree;
  21430. })();
  21431. BABYLON.Octree = Octree;
  21432. })(BABYLON || (BABYLON = {}));
  21433. //# sourceMappingURL=babylon.octree.js.map
  21434. var BABYLON;
  21435. (function (BABYLON) {
  21436. var OctreeBlock = (function () {
  21437. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21438. this.entries = new Array();
  21439. this._boundingVectors = new Array();
  21440. this._capacity = capacity;
  21441. this._depth = depth;
  21442. this._maxDepth = maxDepth;
  21443. this._creationFunc = creationFunc;
  21444. this._minPoint = minPoint;
  21445. this._maxPoint = maxPoint;
  21446. this._boundingVectors.push(minPoint.clone());
  21447. this._boundingVectors.push(maxPoint.clone());
  21448. this._boundingVectors.push(minPoint.clone());
  21449. this._boundingVectors[2].x = maxPoint.x;
  21450. this._boundingVectors.push(minPoint.clone());
  21451. this._boundingVectors[3].y = maxPoint.y;
  21452. this._boundingVectors.push(minPoint.clone());
  21453. this._boundingVectors[4].z = maxPoint.z;
  21454. this._boundingVectors.push(maxPoint.clone());
  21455. this._boundingVectors[5].z = minPoint.z;
  21456. this._boundingVectors.push(maxPoint.clone());
  21457. this._boundingVectors[6].x = minPoint.x;
  21458. this._boundingVectors.push(maxPoint.clone());
  21459. this._boundingVectors[7].y = minPoint.y;
  21460. }
  21461. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21462. // Property
  21463. get: function () {
  21464. return this._capacity;
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21470. get: function () {
  21471. return this._minPoint;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21477. get: function () {
  21478. return this._maxPoint;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. // Methods
  21484. OctreeBlock.prototype.addEntry = function (entry) {
  21485. if (this.blocks) {
  21486. for (var index = 0; index < this.blocks.length; index++) {
  21487. var block = this.blocks[index];
  21488. block.addEntry(entry);
  21489. }
  21490. return;
  21491. }
  21492. this._creationFunc(entry, this);
  21493. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21494. this.createInnerBlocks();
  21495. }
  21496. };
  21497. OctreeBlock.prototype.addEntries = function (entries) {
  21498. for (var index = 0; index < entries.length; index++) {
  21499. var mesh = entries[index];
  21500. this.addEntry(mesh);
  21501. }
  21502. };
  21503. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21504. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21505. if (this.blocks) {
  21506. for (var index = 0; index < this.blocks.length; index++) {
  21507. var block = this.blocks[index];
  21508. block.select(frustumPlanes, selection, allowDuplicate);
  21509. }
  21510. return;
  21511. }
  21512. if (allowDuplicate) {
  21513. selection.concat(this.entries);
  21514. }
  21515. else {
  21516. selection.concatWithNoDuplicate(this.entries);
  21517. }
  21518. }
  21519. };
  21520. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21521. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21522. if (this.blocks) {
  21523. for (var index = 0; index < this.blocks.length; index++) {
  21524. var block = this.blocks[index];
  21525. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21526. }
  21527. return;
  21528. }
  21529. if (allowDuplicate) {
  21530. selection.concat(this.entries);
  21531. }
  21532. else {
  21533. selection.concatWithNoDuplicate(this.entries);
  21534. }
  21535. }
  21536. };
  21537. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21538. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21539. if (this.blocks) {
  21540. for (var index = 0; index < this.blocks.length; index++) {
  21541. var block = this.blocks[index];
  21542. block.intersectsRay(ray, selection);
  21543. }
  21544. return;
  21545. }
  21546. selection.concatWithNoDuplicate(this.entries);
  21547. }
  21548. };
  21549. OctreeBlock.prototype.createInnerBlocks = function () {
  21550. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21551. };
  21552. return OctreeBlock;
  21553. })();
  21554. BABYLON.OctreeBlock = OctreeBlock;
  21555. })(BABYLON || (BABYLON = {}));
  21556. //# sourceMappingURL=babylon.octreeBlock.js.map
  21557. var BABYLON;
  21558. (function (BABYLON) {
  21559. var Bone = (function () {
  21560. function Bone(name, skeleton, parentBone, matrix) {
  21561. this.name = name;
  21562. this.children = new Array();
  21563. this.animations = new Array();
  21564. this._worldTransform = new BABYLON.Matrix();
  21565. this._absoluteTransform = new BABYLON.Matrix();
  21566. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21567. this._skeleton = skeleton;
  21568. this._matrix = matrix;
  21569. this._baseMatrix = matrix;
  21570. skeleton.bones.push(this);
  21571. if (parentBone) {
  21572. this._parent = parentBone;
  21573. parentBone.children.push(this);
  21574. }
  21575. else {
  21576. this._parent = null;
  21577. }
  21578. this._updateDifferenceMatrix();
  21579. }
  21580. // Members
  21581. Bone.prototype.getParent = function () {
  21582. return this._parent;
  21583. };
  21584. Bone.prototype.getLocalMatrix = function () {
  21585. return this._matrix;
  21586. };
  21587. Bone.prototype.getBaseMatrix = function () {
  21588. return this._baseMatrix;
  21589. };
  21590. Bone.prototype.getWorldMatrix = function () {
  21591. return this._worldTransform;
  21592. };
  21593. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21594. return this._invertedAbsoluteTransform;
  21595. };
  21596. Bone.prototype.getAbsoluteMatrix = function () {
  21597. var matrix = this._matrix.clone();
  21598. var parent = this._parent;
  21599. while (parent) {
  21600. matrix = matrix.multiply(parent.getLocalMatrix());
  21601. parent = parent.getParent();
  21602. }
  21603. return matrix;
  21604. };
  21605. // Methods
  21606. Bone.prototype.updateMatrix = function (matrix) {
  21607. this._matrix = matrix;
  21608. this._skeleton._markAsDirty();
  21609. this._updateDifferenceMatrix();
  21610. };
  21611. Bone.prototype._updateDifferenceMatrix = function () {
  21612. if (this._parent) {
  21613. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21614. }
  21615. else {
  21616. this._absoluteTransform.copyFrom(this._matrix);
  21617. }
  21618. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21619. for (var index = 0; index < this.children.length; index++) {
  21620. this.children[index]._updateDifferenceMatrix();
  21621. }
  21622. };
  21623. Bone.prototype.markAsDirty = function () {
  21624. this._skeleton._markAsDirty();
  21625. };
  21626. return Bone;
  21627. })();
  21628. BABYLON.Bone = Bone;
  21629. })(BABYLON || (BABYLON = {}));
  21630. //# sourceMappingURL=babylon.bone.js.map
  21631. var BABYLON;
  21632. (function (BABYLON) {
  21633. var Skeleton = (function () {
  21634. function Skeleton(name, id, scene) {
  21635. this.name = name;
  21636. this.id = id;
  21637. this.bones = new Array();
  21638. this._isDirty = true;
  21639. this._identity = BABYLON.Matrix.Identity();
  21640. this.bones = [];
  21641. this._scene = scene;
  21642. scene.skeletons.push(this);
  21643. this.prepare();
  21644. //make sure it will recalculate the matrix next time prepare is called.
  21645. this._isDirty = true;
  21646. }
  21647. // Members
  21648. Skeleton.prototype.getTransformMatrices = function () {
  21649. return this._transformMatrices;
  21650. };
  21651. // Methods
  21652. Skeleton.prototype._markAsDirty = function () {
  21653. this._isDirty = true;
  21654. };
  21655. Skeleton.prototype.prepare = function () {
  21656. if (!this._isDirty) {
  21657. return;
  21658. }
  21659. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21660. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21661. }
  21662. for (var index = 0; index < this.bones.length; index++) {
  21663. var bone = this.bones[index];
  21664. var parentBone = bone.getParent();
  21665. if (parentBone) {
  21666. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21667. }
  21668. else {
  21669. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21670. }
  21671. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21672. }
  21673. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21674. this._isDirty = false;
  21675. this._scene._activeBones += this.bones.length;
  21676. };
  21677. Skeleton.prototype.getAnimatables = function () {
  21678. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21679. this._animatables = [];
  21680. for (var index = 0; index < this.bones.length; index++) {
  21681. this._animatables.push(this.bones[index]);
  21682. }
  21683. }
  21684. return this._animatables;
  21685. };
  21686. Skeleton.prototype.clone = function (name, id) {
  21687. var result = new Skeleton(name, id || name, this._scene);
  21688. for (var index = 0; index < this.bones.length; index++) {
  21689. var source = this.bones[index];
  21690. var parentBone = null;
  21691. if (source.getParent()) {
  21692. var parentIndex = this.bones.indexOf(source.getParent());
  21693. parentBone = result.bones[parentIndex];
  21694. }
  21695. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21696. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21697. }
  21698. return result;
  21699. };
  21700. return Skeleton;
  21701. })();
  21702. BABYLON.Skeleton = Skeleton;
  21703. })(BABYLON || (BABYLON = {}));
  21704. //# sourceMappingURL=babylon.skeleton.js.map
  21705. var BABYLON;
  21706. (function (BABYLON) {
  21707. var PostProcess = (function () {
  21708. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21710. this.name = name;
  21711. this.width = -1;
  21712. this.height = -1;
  21713. this._reusable = false;
  21714. this._textures = new BABYLON.SmartArray(2);
  21715. this._currentRenderTextureInd = 0;
  21716. if (camera != null) {
  21717. this._camera = camera;
  21718. this._scene = camera.getScene();
  21719. camera.attachPostProcess(this);
  21720. this._engine = this._scene.getEngine();
  21721. }
  21722. else {
  21723. this._engine = engine;
  21724. }
  21725. this._renderRatio = ratio;
  21726. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21727. this._reusable = reusable || false;
  21728. samplers = samplers || [];
  21729. samplers.push("textureSampler");
  21730. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21731. }
  21732. PostProcess.prototype.isReusable = function () {
  21733. return this._reusable;
  21734. };
  21735. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21736. camera = camera || this._camera;
  21737. var scene = camera.getScene();
  21738. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21739. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21740. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21741. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21742. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21743. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21744. if (this._textures.length > 0) {
  21745. for (var i = 0; i < this._textures.length; i++) {
  21746. this._engine._releaseTexture(this._textures.data[i]);
  21747. }
  21748. this._textures.reset();
  21749. }
  21750. this.width = desiredWidth;
  21751. this.height = desiredHeight;
  21752. 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 }));
  21753. if (this._reusable) {
  21754. 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 }));
  21755. }
  21756. if (this.onSizeChanged) {
  21757. this.onSizeChanged();
  21758. }
  21759. }
  21760. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21761. if (this.onActivate) {
  21762. this.onActivate(camera);
  21763. }
  21764. // Clear
  21765. if (this.clearColor) {
  21766. this._engine.clear(this.clearColor, true, true);
  21767. }
  21768. else {
  21769. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21770. }
  21771. if (this._reusable) {
  21772. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21773. }
  21774. };
  21775. PostProcess.prototype.apply = function () {
  21776. // Check
  21777. if (!this._effect.isReady())
  21778. return null;
  21779. // States
  21780. this._engine.enableEffect(this._effect);
  21781. this._engine.setState(false);
  21782. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21783. this._engine.setDepthBuffer(false);
  21784. this._engine.setDepthWrite(false);
  21785. // Texture
  21786. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21787. // Parameters
  21788. if (this.onApply) {
  21789. this.onApply(this._effect);
  21790. }
  21791. return this._effect;
  21792. };
  21793. PostProcess.prototype.dispose = function (camera) {
  21794. camera = camera || this._camera;
  21795. if (this._textures.length > 0) {
  21796. for (var i = 0; i < this._textures.length; i++) {
  21797. this._engine._releaseTexture(this._textures.data[i]);
  21798. }
  21799. this._textures.reset();
  21800. }
  21801. if (!camera) {
  21802. return;
  21803. }
  21804. camera.detachPostProcess(this);
  21805. var index = camera._postProcesses.indexOf(this);
  21806. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21807. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21808. }
  21809. };
  21810. return PostProcess;
  21811. })();
  21812. BABYLON.PostProcess = PostProcess;
  21813. })(BABYLON || (BABYLON = {}));
  21814. //# sourceMappingURL=babylon.postProcess.js.map
  21815. var BABYLON;
  21816. (function (BABYLON) {
  21817. var PostProcessManager = (function () {
  21818. function PostProcessManager(scene) {
  21819. this._vertexDeclaration = [2];
  21820. this._vertexStrideSize = 2 * 4;
  21821. this._scene = scene;
  21822. }
  21823. PostProcessManager.prototype._prepareBuffers = function () {
  21824. if (this._vertexBuffer) {
  21825. return;
  21826. }
  21827. // VBO
  21828. var vertices = [];
  21829. vertices.push(1, 1);
  21830. vertices.push(-1, 1);
  21831. vertices.push(-1, -1);
  21832. vertices.push(1, -1);
  21833. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21834. // Indices
  21835. var indices = [];
  21836. indices.push(0);
  21837. indices.push(1);
  21838. indices.push(2);
  21839. indices.push(0);
  21840. indices.push(2);
  21841. indices.push(3);
  21842. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21843. };
  21844. // Methods
  21845. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21846. var postProcesses = this._scene.activeCamera._postProcesses;
  21847. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21848. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21849. return false;
  21850. }
  21851. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21852. return true;
  21853. };
  21854. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21855. var engine = this._scene.getEngine();
  21856. for (var index = 0; index < postProcesses.length; index++) {
  21857. if (index < postProcesses.length - 1) {
  21858. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21859. }
  21860. else {
  21861. if (targetTexture) {
  21862. engine.bindFramebuffer(targetTexture);
  21863. }
  21864. else {
  21865. engine.restoreDefaultFramebuffer();
  21866. }
  21867. }
  21868. var pp = postProcesses[index];
  21869. var effect = pp.apply();
  21870. if (effect) {
  21871. if (pp.onBeforeRender) {
  21872. pp.onBeforeRender(effect);
  21873. }
  21874. // VBOs
  21875. this._prepareBuffers();
  21876. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21877. // Draw order
  21878. engine.draw(true, 0, 6);
  21879. }
  21880. }
  21881. // Restore depth buffer
  21882. engine.setDepthBuffer(true);
  21883. engine.setDepthWrite(true);
  21884. };
  21885. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21886. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21887. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21888. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21889. return;
  21890. }
  21891. var engine = this._scene.getEngine();
  21892. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  21893. if (index < postProcessesTakenIndices.length - 1) {
  21894. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  21895. }
  21896. else {
  21897. if (targetTexture) {
  21898. engine.bindFramebuffer(targetTexture);
  21899. }
  21900. else {
  21901. engine.restoreDefaultFramebuffer();
  21902. }
  21903. }
  21904. if (doNotPresent) {
  21905. break;
  21906. }
  21907. var pp = postProcesses[postProcessesTakenIndices[index]];
  21908. var effect = pp.apply();
  21909. if (effect) {
  21910. if (pp.onBeforeRender) {
  21911. pp.onBeforeRender(effect);
  21912. }
  21913. // VBOs
  21914. this._prepareBuffers();
  21915. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21916. // Draw order
  21917. engine.draw(true, 0, 6);
  21918. }
  21919. }
  21920. // Restore depth buffer
  21921. engine.setDepthBuffer(true);
  21922. engine.setDepthWrite(true);
  21923. };
  21924. PostProcessManager.prototype.dispose = function () {
  21925. if (this._vertexBuffer) {
  21926. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21927. this._vertexBuffer = null;
  21928. }
  21929. if (this._indexBuffer) {
  21930. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21931. this._indexBuffer = null;
  21932. }
  21933. };
  21934. return PostProcessManager;
  21935. })();
  21936. BABYLON.PostProcessManager = PostProcessManager;
  21937. })(BABYLON || (BABYLON = {}));
  21938. //# sourceMappingURL=babylon.postProcessManager.js.map
  21939. var __extends = this.__extends || function (d, b) {
  21940. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21941. function __() { this.constructor = d; }
  21942. __.prototype = b.prototype;
  21943. d.prototype = new __();
  21944. };
  21945. var BABYLON;
  21946. (function (BABYLON) {
  21947. var PassPostProcess = (function (_super) {
  21948. __extends(PassPostProcess, _super);
  21949. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21950. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  21951. }
  21952. return PassPostProcess;
  21953. })(BABYLON.PostProcess);
  21954. BABYLON.PassPostProcess = PassPostProcess;
  21955. })(BABYLON || (BABYLON = {}));
  21956. //# sourceMappingURL=babylon.passPostProcess.js.map
  21957. var __extends = this.__extends || function (d, b) {
  21958. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21959. function __() { this.constructor = d; }
  21960. __.prototype = b.prototype;
  21961. d.prototype = new __();
  21962. };
  21963. var BABYLON;
  21964. (function (BABYLON) {
  21965. var BlurPostProcess = (function (_super) {
  21966. __extends(BlurPostProcess, _super);
  21967. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  21968. var _this = this;
  21969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  21970. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  21971. this.direction = direction;
  21972. this.blurWidth = blurWidth;
  21973. this.onApply = function (effect) {
  21974. effect.setFloat2("screenSize", _this.width, _this.height);
  21975. effect.setVector2("direction", _this.direction);
  21976. effect.setFloat("blurWidth", _this.blurWidth);
  21977. };
  21978. }
  21979. return BlurPostProcess;
  21980. })(BABYLON.PostProcess);
  21981. BABYLON.BlurPostProcess = BlurPostProcess;
  21982. })(BABYLON || (BABYLON = {}));
  21983. //# sourceMappingURL=babylon.blurPostProcess.js.map
  21984. var __extends = this.__extends || function (d, b) {
  21985. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21986. function __() { this.constructor = d; }
  21987. __.prototype = b.prototype;
  21988. d.prototype = new __();
  21989. };
  21990. var BABYLON;
  21991. (function (BABYLON) {
  21992. var RefractionPostProcess = (function (_super) {
  21993. __extends(RefractionPostProcess, _super);
  21994. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  21995. var _this = this;
  21996. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  21997. this.color = color;
  21998. this.depth = depth;
  21999. this.colorLevel = colorLevel;
  22000. this.onActivate = function (cam) {
  22001. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22002. };
  22003. this.onApply = function (effect) {
  22004. effect.setColor3("baseColor", _this.color);
  22005. effect.setFloat("depth", _this.depth);
  22006. effect.setFloat("colorLevel", _this.colorLevel);
  22007. effect.setTexture("refractionSampler", _this._refRexture);
  22008. };
  22009. }
  22010. // Methods
  22011. RefractionPostProcess.prototype.dispose = function (camera) {
  22012. if (this._refRexture) {
  22013. this._refRexture.dispose();
  22014. }
  22015. _super.prototype.dispose.call(this, camera);
  22016. };
  22017. return RefractionPostProcess;
  22018. })(BABYLON.PostProcess);
  22019. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22020. })(BABYLON || (BABYLON = {}));
  22021. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22022. var __extends = this.__extends || function (d, b) {
  22023. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22024. function __() { this.constructor = d; }
  22025. __.prototype = b.prototype;
  22026. d.prototype = new __();
  22027. };
  22028. var BABYLON;
  22029. (function (BABYLON) {
  22030. var BlackAndWhitePostProcess = (function (_super) {
  22031. __extends(BlackAndWhitePostProcess, _super);
  22032. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22033. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22034. }
  22035. return BlackAndWhitePostProcess;
  22036. })(BABYLON.PostProcess);
  22037. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22038. })(BABYLON || (BABYLON = {}));
  22039. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22040. var __extends = this.__extends || function (d, b) {
  22041. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22042. function __() { this.constructor = d; }
  22043. __.prototype = b.prototype;
  22044. d.prototype = new __();
  22045. };
  22046. var BABYLON;
  22047. (function (BABYLON) {
  22048. var ConvolutionPostProcess = (function (_super) {
  22049. __extends(ConvolutionPostProcess, _super);
  22050. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22051. var _this = this;
  22052. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22053. this.kernel = kernel;
  22054. this.onApply = function (effect) {
  22055. effect.setFloat2("screenSize", _this.width, _this.height);
  22056. effect.setArray("kernel", _this.kernel);
  22057. };
  22058. }
  22059. // Statics
  22060. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22061. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22062. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22063. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22064. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22065. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22066. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22067. return ConvolutionPostProcess;
  22068. })(BABYLON.PostProcess);
  22069. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22070. })(BABYLON || (BABYLON = {}));
  22071. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22072. var __extends = this.__extends || function (d, b) {
  22073. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22074. function __() { this.constructor = d; }
  22075. __.prototype = b.prototype;
  22076. d.prototype = new __();
  22077. };
  22078. var BABYLON;
  22079. (function (BABYLON) {
  22080. var FilterPostProcess = (function (_super) {
  22081. __extends(FilterPostProcess, _super);
  22082. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22083. var _this = this;
  22084. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22085. this.kernelMatrix = kernelMatrix;
  22086. this.onApply = function (effect) {
  22087. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22088. };
  22089. }
  22090. return FilterPostProcess;
  22091. })(BABYLON.PostProcess);
  22092. BABYLON.FilterPostProcess = FilterPostProcess;
  22093. })(BABYLON || (BABYLON = {}));
  22094. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22095. var __extends = this.__extends || function (d, b) {
  22096. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22097. function __() { this.constructor = d; }
  22098. __.prototype = b.prototype;
  22099. d.prototype = new __();
  22100. };
  22101. var BABYLON;
  22102. (function (BABYLON) {
  22103. var FxaaPostProcess = (function (_super) {
  22104. __extends(FxaaPostProcess, _super);
  22105. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22106. var _this = this;
  22107. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22108. this.onSizeChanged = function () {
  22109. _this.texelWidth = 1.0 / _this.width;
  22110. _this.texelHeight = 1.0 / _this.height;
  22111. };
  22112. this.onApply = function (effect) {
  22113. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22114. };
  22115. }
  22116. return FxaaPostProcess;
  22117. })(BABYLON.PostProcess);
  22118. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22119. })(BABYLON || (BABYLON = {}));
  22120. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22121. var __extends = this.__extends || function (d, b) {
  22122. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22123. function __() { this.constructor = d; }
  22124. __.prototype = b.prototype;
  22125. d.prototype = new __();
  22126. };
  22127. var BABYLON;
  22128. (function (BABYLON) {
  22129. var StereogramInterlacePostProcess = (function (_super) {
  22130. __extends(StereogramInterlacePostProcess, _super);
  22131. function StereogramInterlacePostProcess(name, camB, postProcessA, isStereogramHoriz, samplingMode) {
  22132. var _this = this;
  22133. _super.call(this, name, "stereogramInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereogramHoriz ? "#define IS_STEREOGRAM_HORIZ 1" : undefined);
  22134. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22135. this.onSizeChanged = function () {
  22136. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22137. };
  22138. this.onApply = function (effect) {
  22139. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22140. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22141. };
  22142. }
  22143. return StereogramInterlacePostProcess;
  22144. })(BABYLON.PostProcess);
  22145. BABYLON.StereogramInterlacePostProcess = StereogramInterlacePostProcess;
  22146. })(BABYLON || (BABYLON = {}));
  22147. //# sourceMappingURL=babylon.stereogramInterlacePostProcess.js.map
  22148. var BABYLON;
  22149. (function (BABYLON) {
  22150. var LensFlare = (function () {
  22151. function LensFlare(size, position, color, imgUrl, system) {
  22152. this.size = size;
  22153. this.position = position;
  22154. this.dispose = function () {
  22155. if (this.texture) {
  22156. this.texture.dispose();
  22157. }
  22158. // Remove from scene
  22159. var index = this._system.lensFlares.indexOf(this);
  22160. this._system.lensFlares.splice(index, 1);
  22161. };
  22162. this.color = color || new BABYLON.Color3(1, 1, 1);
  22163. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22164. this._system = system;
  22165. system.lensFlares.push(this);
  22166. }
  22167. return LensFlare;
  22168. })();
  22169. BABYLON.LensFlare = LensFlare;
  22170. })(BABYLON || (BABYLON = {}));
  22171. //# sourceMappingURL=babylon.lensFlare.js.map
  22172. var BABYLON;
  22173. (function (BABYLON) {
  22174. var LensFlareSystem = (function () {
  22175. function LensFlareSystem(name, emitter, scene) {
  22176. this.name = name;
  22177. this.lensFlares = new Array();
  22178. this.borderLimit = 300;
  22179. this._vertexDeclaration = [2];
  22180. this._vertexStrideSize = 2 * 4;
  22181. this._isEnabled = true;
  22182. this._scene = scene;
  22183. this._emitter = emitter;
  22184. scene.lensFlareSystems.push(this);
  22185. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22186. // VBO
  22187. var vertices = [];
  22188. vertices.push(1, 1);
  22189. vertices.push(-1, 1);
  22190. vertices.push(-1, -1);
  22191. vertices.push(1, -1);
  22192. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22193. // Indices
  22194. var indices = [];
  22195. indices.push(0);
  22196. indices.push(1);
  22197. indices.push(2);
  22198. indices.push(0);
  22199. indices.push(2);
  22200. indices.push(3);
  22201. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22202. // Effects
  22203. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22204. }
  22205. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22206. get: function () {
  22207. return this._isEnabled;
  22208. },
  22209. set: function (value) {
  22210. this._isEnabled = value;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. LensFlareSystem.prototype.getScene = function () {
  22216. return this._scene;
  22217. };
  22218. LensFlareSystem.prototype.getEmitter = function () {
  22219. return this._emitter;
  22220. };
  22221. LensFlareSystem.prototype.getEmitterPosition = function () {
  22222. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22223. };
  22224. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22225. var position = this.getEmitterPosition();
  22226. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22227. this._positionX = position.x;
  22228. this._positionY = position.y;
  22229. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22230. if (position.z > 0) {
  22231. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22232. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22233. return true;
  22234. }
  22235. }
  22236. return false;
  22237. };
  22238. LensFlareSystem.prototype._isVisible = function () {
  22239. if (!this._isEnabled) {
  22240. return false;
  22241. }
  22242. var emitterPosition = this.getEmitterPosition();
  22243. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22244. var distance = direction.length();
  22245. direction.normalize();
  22246. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22247. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22248. return !pickInfo.hit || pickInfo.distance > distance;
  22249. };
  22250. LensFlareSystem.prototype.render = function () {
  22251. if (!this._effect.isReady())
  22252. return false;
  22253. var engine = this._scene.getEngine();
  22254. var viewport = this._scene.activeCamera.viewport;
  22255. var globalViewport = viewport.toGlobal(engine);
  22256. // Position
  22257. if (!this.computeEffectivePosition(globalViewport)) {
  22258. return false;
  22259. }
  22260. // Visibility
  22261. if (!this._isVisible()) {
  22262. return false;
  22263. }
  22264. // Intensity
  22265. var awayX;
  22266. var awayY;
  22267. if (this._positionX < this.borderLimit + globalViewport.x) {
  22268. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22269. }
  22270. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22271. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22272. }
  22273. else {
  22274. awayX = 0;
  22275. }
  22276. if (this._positionY < this.borderLimit + globalViewport.y) {
  22277. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22278. }
  22279. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22280. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22281. }
  22282. else {
  22283. awayY = 0;
  22284. }
  22285. var away = (awayX > awayY) ? awayX : awayY;
  22286. if (away > this.borderLimit) {
  22287. away = this.borderLimit;
  22288. }
  22289. var intensity = 1.0 - (away / this.borderLimit);
  22290. if (intensity < 0) {
  22291. return false;
  22292. }
  22293. if (intensity > 1.0) {
  22294. intensity = 1.0;
  22295. }
  22296. // Position
  22297. var centerX = globalViewport.x + globalViewport.width / 2;
  22298. var centerY = globalViewport.y + globalViewport.height / 2;
  22299. var distX = centerX - this._positionX;
  22300. var distY = centerY - this._positionY;
  22301. // Effects
  22302. engine.enableEffect(this._effect);
  22303. engine.setState(false);
  22304. engine.setDepthBuffer(false);
  22305. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22306. // VBOs
  22307. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22308. for (var index = 0; index < this.lensFlares.length; index++) {
  22309. var flare = this.lensFlares[index];
  22310. var x = centerX - (distX * flare.position);
  22311. var y = centerY - (distY * flare.position);
  22312. var cw = flare.size;
  22313. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22314. var cx = 2 * (x / globalViewport.width) - 1.0;
  22315. var cy = 1.0 - 2 * (y / globalViewport.height);
  22316. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22317. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22318. // Texture
  22319. this._effect.setTexture("textureSampler", flare.texture);
  22320. // Color
  22321. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22322. // Draw order
  22323. engine.draw(true, 0, 6);
  22324. }
  22325. engine.setDepthBuffer(true);
  22326. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22327. return true;
  22328. };
  22329. LensFlareSystem.prototype.dispose = function () {
  22330. if (this._vertexBuffer) {
  22331. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22332. this._vertexBuffer = null;
  22333. }
  22334. if (this._indexBuffer) {
  22335. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22336. this._indexBuffer = null;
  22337. }
  22338. while (this.lensFlares.length) {
  22339. this.lensFlares[0].dispose();
  22340. }
  22341. // Remove from scene
  22342. var index = this._scene.lensFlareSystems.indexOf(this);
  22343. this._scene.lensFlareSystems.splice(index, 1);
  22344. };
  22345. return LensFlareSystem;
  22346. })();
  22347. BABYLON.LensFlareSystem = LensFlareSystem;
  22348. })(BABYLON || (BABYLON = {}));
  22349. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22350. var BABYLON;
  22351. (function (BABYLON) {
  22352. var CannonJSPlugin = (function () {
  22353. function CannonJSPlugin() {
  22354. this._registeredMeshes = [];
  22355. this._physicsMaterials = [];
  22356. this.updateBodyPosition = function (mesh) {
  22357. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22358. var registeredMesh = this._registeredMeshes[index];
  22359. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22360. var body = registeredMesh.body;
  22361. var center = mesh.getBoundingInfo().boundingBox.center;
  22362. body.position.set(center.x, center.z, center.y);
  22363. body.quaternion.x = mesh.rotationQuaternion.x;
  22364. body.quaternion.z = mesh.rotationQuaternion.y;
  22365. body.quaternion.y = mesh.rotationQuaternion.z;
  22366. body.quaternion.w = -mesh.rotationQuaternion.w;
  22367. return;
  22368. }
  22369. }
  22370. };
  22371. }
  22372. CannonJSPlugin.prototype.initialize = function (iterations) {
  22373. if (iterations === void 0) { iterations = 10; }
  22374. this._world = new CANNON.World();
  22375. this._world.broadphase = new CANNON.NaiveBroadphase();
  22376. this._world.solver.iterations = iterations;
  22377. };
  22378. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22379. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22380. };
  22381. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22382. this._world.step(delta);
  22383. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22384. var registeredMesh = this._registeredMeshes[index];
  22385. if (registeredMesh.isChild) {
  22386. continue;
  22387. }
  22388. // Body position
  22389. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22390. var deltaPos = registeredMesh.delta;
  22391. if (deltaPos) {
  22392. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22393. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22394. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22395. }
  22396. else {
  22397. registeredMesh.mesh.position.x = bodyX;
  22398. registeredMesh.mesh.position.y = bodyZ;
  22399. registeredMesh.mesh.position.z = bodyY;
  22400. }
  22401. if (!registeredMesh.mesh.rotationQuaternion) {
  22402. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22403. }
  22404. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22405. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22406. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22407. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22408. }
  22409. };
  22410. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22411. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22412. };
  22413. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22414. this.unregisterMesh(mesh);
  22415. mesh.computeWorldMatrix(true);
  22416. switch (impostor) {
  22417. case BABYLON.PhysicsEngine.SphereImpostor:
  22418. var bbox = mesh.getBoundingInfo().boundingBox;
  22419. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22420. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22421. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22422. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22423. case BABYLON.PhysicsEngine.BoxImpostor:
  22424. bbox = mesh.getBoundingInfo().boundingBox;
  22425. var min = bbox.minimumWorld;
  22426. var max = bbox.maximumWorld;
  22427. var box = max.subtract(min).scale(0.5);
  22428. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22429. case BABYLON.PhysicsEngine.PlaneImpostor:
  22430. return this._createPlane(mesh, options);
  22431. case BABYLON.PhysicsEngine.MeshImpostor:
  22432. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22433. var rawFaces = mesh.getIndices();
  22434. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22435. }
  22436. return null;
  22437. };
  22438. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22439. var shape = new CANNON.Sphere(radius);
  22440. if (!options) {
  22441. return shape;
  22442. }
  22443. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22444. };
  22445. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22446. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22447. if (!options) {
  22448. return shape;
  22449. }
  22450. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22451. };
  22452. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22453. var shape = new CANNON.Plane();
  22454. if (!options) {
  22455. return shape;
  22456. }
  22457. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22458. };
  22459. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22460. var verts = [], faces = [];
  22461. mesh.computeWorldMatrix(true);
  22462. for (var i = 0; i < rawVerts.length; i += 3) {
  22463. var transformed = BABYLON.Vector3.Zero();
  22464. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22465. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22466. }
  22467. for (var j = 0; j < rawFaces.length; j += 3) {
  22468. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22469. }
  22470. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22471. if (!options) {
  22472. return shape;
  22473. }
  22474. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22475. };
  22476. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22477. var index;
  22478. var mat;
  22479. for (index = 0; index < this._physicsMaterials.length; index++) {
  22480. mat = this._physicsMaterials[index];
  22481. if (mat.friction === friction && mat.restitution === restitution) {
  22482. return mat;
  22483. }
  22484. }
  22485. var currentMat = new CANNON.Material();
  22486. currentMat.friction = friction;
  22487. currentMat.restitution = restitution;
  22488. this._physicsMaterials.push(currentMat);
  22489. for (index = 0; index < this._physicsMaterials.length; index++) {
  22490. mat = this._physicsMaterials[index];
  22491. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22492. contactMaterial.contactEquationStiffness = 1e10;
  22493. contactMaterial.contactEquationRegularizationTime = 10;
  22494. this._world.addContactMaterial(contactMaterial);
  22495. }
  22496. return currentMat;
  22497. };
  22498. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22499. var initialRotation = null;
  22500. if (mesh.rotationQuaternion) {
  22501. initialRotation = mesh.rotationQuaternion.clone();
  22502. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22503. }
  22504. // The delta between the mesh position and the mesh bounding box center
  22505. var bbox = mesh.getBoundingInfo().boundingBox;
  22506. var deltaPosition = mesh.position.subtract(bbox.center);
  22507. var material = this._addMaterial(friction, restitution);
  22508. var body = new CANNON.RigidBody(mass, shape, material);
  22509. if (initialRotation) {
  22510. body.quaternion.x = initialRotation.x;
  22511. body.quaternion.z = initialRotation.y;
  22512. body.quaternion.y = initialRotation.z;
  22513. body.quaternion.w = -initialRotation.w;
  22514. }
  22515. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22516. this._world.add(body);
  22517. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22518. return body;
  22519. };
  22520. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22521. var compoundShape = new CANNON.Compound();
  22522. for (var index = 0; index < parts.length; index++) {
  22523. var mesh = parts[index].mesh;
  22524. var shape = this.registerMesh(mesh, parts[index].impostor);
  22525. if (index == 0) {
  22526. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22527. }
  22528. else {
  22529. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22530. }
  22531. }
  22532. var initialMesh = parts[0].mesh;
  22533. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22534. body.parts = parts;
  22535. return body;
  22536. };
  22537. CannonJSPlugin.prototype._unbindBody = function (body) {
  22538. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22539. var registeredMesh = this._registeredMeshes[index];
  22540. if (registeredMesh.body === body) {
  22541. registeredMesh.body = null;
  22542. registeredMesh.delta = 0;
  22543. }
  22544. }
  22545. };
  22546. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22547. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22548. var registeredMesh = this._registeredMeshes[index];
  22549. if (registeredMesh.mesh === mesh) {
  22550. // Remove body
  22551. if (registeredMesh.body) {
  22552. this._world.remove(registeredMesh.body);
  22553. this._unbindBody(registeredMesh.body);
  22554. }
  22555. this._registeredMeshes.splice(index, 1);
  22556. return;
  22557. }
  22558. }
  22559. };
  22560. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22561. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22562. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22563. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22564. var registeredMesh = this._registeredMeshes[index];
  22565. if (registeredMesh.mesh === mesh) {
  22566. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22567. return;
  22568. }
  22569. }
  22570. };
  22571. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22572. var body1 = null, body2 = null;
  22573. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22574. var registeredMesh = this._registeredMeshes[index];
  22575. if (registeredMesh.mesh === mesh1) {
  22576. body1 = registeredMesh.body;
  22577. }
  22578. else if (registeredMesh.mesh === mesh2) {
  22579. body2 = registeredMesh.body;
  22580. }
  22581. }
  22582. if (!body1 || !body2) {
  22583. return false;
  22584. }
  22585. 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));
  22586. this._world.addConstraint(constraint);
  22587. return true;
  22588. };
  22589. CannonJSPlugin.prototype.dispose = function () {
  22590. while (this._registeredMeshes.length) {
  22591. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22592. }
  22593. };
  22594. CannonJSPlugin.prototype.isSupported = function () {
  22595. return window.CANNON !== undefined;
  22596. };
  22597. return CannonJSPlugin;
  22598. })();
  22599. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22600. })(BABYLON || (BABYLON = {}));
  22601. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22602. var BABYLON;
  22603. (function (BABYLON) {
  22604. var OimoJSPlugin = (function () {
  22605. function OimoJSPlugin() {
  22606. this._registeredMeshes = [];
  22607. /**
  22608. * Update the body position according to the mesh position
  22609. * @param mesh
  22610. */
  22611. this.updateBodyPosition = function (mesh) {
  22612. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22613. var registeredMesh = this._registeredMeshes[index];
  22614. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22615. var body = registeredMesh.body.body;
  22616. mesh.computeWorldMatrix(true);
  22617. var center = mesh.getBoundingInfo().boundingBox.center;
  22618. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22619. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22620. body.sleeping = false;
  22621. return;
  22622. }
  22623. // Case where the parent has been updated
  22624. if (registeredMesh.mesh.parent === mesh) {
  22625. mesh.computeWorldMatrix(true);
  22626. registeredMesh.mesh.computeWorldMatrix(true);
  22627. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22628. var absoluteRotation = mesh.rotation;
  22629. body = registeredMesh.body.body;
  22630. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22631. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22632. body.sleeping = false;
  22633. return;
  22634. }
  22635. }
  22636. };
  22637. }
  22638. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22639. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22640. };
  22641. OimoJSPlugin.prototype.initialize = function (iterations) {
  22642. this._world = new OIMO.World();
  22643. this._world.clear();
  22644. };
  22645. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22646. this._world.gravity = gravity;
  22647. };
  22648. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22649. var body = null;
  22650. this.unregisterMesh(mesh);
  22651. mesh.computeWorldMatrix(true);
  22652. var initialRotation = null;
  22653. if (mesh.rotationQuaternion) {
  22654. initialRotation = mesh.rotationQuaternion.clone();
  22655. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22656. mesh.computeWorldMatrix(true);
  22657. }
  22658. var bbox = mesh.getBoundingInfo().boundingBox;
  22659. // The delta between the mesh position and the mesh bounding box center
  22660. var deltaPosition = mesh.position.subtract(bbox.center);
  22661. // Transform delta position with the rotation
  22662. if (initialRotation) {
  22663. var m = new BABYLON.Matrix();
  22664. initialRotation.toRotationMatrix(m);
  22665. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22666. }
  22667. switch (impostor) {
  22668. case BABYLON.PhysicsEngine.SphereImpostor:
  22669. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22670. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22671. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22672. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22673. body = new OIMO.Body({
  22674. type: 'sphere',
  22675. size: [size],
  22676. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22677. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22678. move: options.mass != 0,
  22679. config: [options.mass, options.friction, options.restitution],
  22680. world: this._world
  22681. });
  22682. break;
  22683. case BABYLON.PhysicsEngine.PlaneImpostor:
  22684. case BABYLON.PhysicsEngine.CylinderImpostor:
  22685. case BABYLON.PhysicsEngine.BoxImpostor:
  22686. var min = bbox.minimumWorld;
  22687. var max = bbox.maximumWorld;
  22688. var box = max.subtract(min);
  22689. var sizeX = this._checkWithEpsilon(box.x);
  22690. var sizeY = this._checkWithEpsilon(box.y);
  22691. var sizeZ = this._checkWithEpsilon(box.z);
  22692. body = new OIMO.Body({
  22693. type: 'box',
  22694. size: [sizeX, sizeY, sizeZ],
  22695. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22696. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22697. move: options.mass != 0,
  22698. config: [options.mass, options.friction, options.restitution],
  22699. world: this._world
  22700. });
  22701. break;
  22702. }
  22703. //If quaternion was set as the rotation of the object
  22704. if (initialRotation) {
  22705. //We have to access the rigid body's properties to set the quaternion.
  22706. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22707. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22708. //update the internal rotation matrix
  22709. body.body.syncShapes();
  22710. }
  22711. this._registeredMeshes.push({
  22712. mesh: mesh,
  22713. body: body,
  22714. delta: deltaPosition
  22715. });
  22716. return body;
  22717. };
  22718. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22719. var types = [], sizes = [], positions = [], rotations = [];
  22720. var initialMesh = parts[0].mesh;
  22721. for (var index = 0; index < parts.length; index++) {
  22722. var part = parts[index];
  22723. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22724. types.push(bodyParameters.type);
  22725. sizes.push.apply(sizes, bodyParameters.size);
  22726. positions.push.apply(positions, bodyParameters.pos);
  22727. rotations.push.apply(rotations, bodyParameters.rot);
  22728. }
  22729. var body = new OIMO.Body({
  22730. type: types,
  22731. size: sizes,
  22732. pos: positions,
  22733. rot: rotations,
  22734. move: options.mass != 0,
  22735. config: [options.mass, options.friction, options.restitution],
  22736. world: this._world
  22737. });
  22738. this._registeredMeshes.push({
  22739. mesh: initialMesh,
  22740. body: body
  22741. });
  22742. return body;
  22743. };
  22744. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22745. var bodyParameters = null;
  22746. var mesh = part.mesh;
  22747. // We need the bounding box/sphere info to compute the physics body
  22748. mesh.computeWorldMatrix();
  22749. switch (part.impostor) {
  22750. case BABYLON.PhysicsEngine.SphereImpostor:
  22751. var bbox = mesh.getBoundingInfo().boundingBox;
  22752. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22753. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22754. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22755. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22756. bodyParameters = {
  22757. type: 'sphere',
  22758. /* bug with oimo : sphere needs 3 sizes in this case */
  22759. size: [size, -1, -1],
  22760. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22761. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22762. };
  22763. break;
  22764. case BABYLON.PhysicsEngine.PlaneImpostor:
  22765. case BABYLON.PhysicsEngine.BoxImpostor:
  22766. bbox = mesh.getBoundingInfo().boundingBox;
  22767. var min = bbox.minimumWorld;
  22768. var max = bbox.maximumWorld;
  22769. var box = max.subtract(min);
  22770. var sizeX = this._checkWithEpsilon(box.x);
  22771. var sizeY = this._checkWithEpsilon(box.y);
  22772. var sizeZ = this._checkWithEpsilon(box.z);
  22773. var relativePosition = mesh.position;
  22774. bodyParameters = {
  22775. type: 'box',
  22776. size: [sizeX, sizeY, sizeZ],
  22777. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22778. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22779. };
  22780. break;
  22781. }
  22782. return bodyParameters;
  22783. };
  22784. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22785. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22786. var registeredMesh = this._registeredMeshes[index];
  22787. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22788. if (registeredMesh.body) {
  22789. this._world.removeRigidBody(registeredMesh.body.body);
  22790. this._unbindBody(registeredMesh.body);
  22791. }
  22792. this._registeredMeshes.splice(index, 1);
  22793. return;
  22794. }
  22795. }
  22796. };
  22797. OimoJSPlugin.prototype._unbindBody = function (body) {
  22798. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22799. var registeredMesh = this._registeredMeshes[index];
  22800. if (registeredMesh.body === body) {
  22801. registeredMesh.body = null;
  22802. }
  22803. }
  22804. };
  22805. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22806. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22807. var registeredMesh = this._registeredMeshes[index];
  22808. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22809. // Get object mass to have a behaviour similar to cannon.js
  22810. var mass = registeredMesh.body.body.massInfo.mass;
  22811. // The force is scaled with the mass of object
  22812. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22813. return;
  22814. }
  22815. }
  22816. };
  22817. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22818. var body1 = null, body2 = null;
  22819. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22820. var registeredMesh = this._registeredMeshes[index];
  22821. if (registeredMesh.mesh === mesh1) {
  22822. body1 = registeredMesh.body.body;
  22823. }
  22824. else if (registeredMesh.mesh === mesh2) {
  22825. body2 = registeredMesh.body.body;
  22826. }
  22827. }
  22828. if (!body1 || !body2) {
  22829. return false;
  22830. }
  22831. if (!options) {
  22832. options = {};
  22833. }
  22834. new OIMO.Link({
  22835. type: options.type,
  22836. body1: body1,
  22837. body2: body2,
  22838. min: options.min,
  22839. max: options.max,
  22840. axe1: options.axe1,
  22841. axe2: options.axe2,
  22842. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22843. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22844. collision: options.collision,
  22845. spring: options.spring,
  22846. world: this._world
  22847. });
  22848. return true;
  22849. };
  22850. OimoJSPlugin.prototype.dispose = function () {
  22851. this._world.clear();
  22852. while (this._registeredMeshes.length) {
  22853. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22854. }
  22855. };
  22856. OimoJSPlugin.prototype.isSupported = function () {
  22857. return OIMO !== undefined;
  22858. };
  22859. OimoJSPlugin.prototype._getLastShape = function (body) {
  22860. var lastShape = body.shapes;
  22861. while (lastShape.next) {
  22862. lastShape = lastShape.next;
  22863. }
  22864. return lastShape;
  22865. };
  22866. OimoJSPlugin.prototype.runOneStep = function (time) {
  22867. this._world.step();
  22868. // Update the position of all registered meshes
  22869. var i = this._registeredMeshes.length;
  22870. var m;
  22871. while (i--) {
  22872. var body = this._registeredMeshes[i].body.body;
  22873. var mesh = this._registeredMeshes[i].mesh;
  22874. var delta = this._registeredMeshes[i].delta;
  22875. if (!body.sleeping) {
  22876. if (body.shapes.next) {
  22877. var parentShape = this._getLastShape(body);
  22878. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22879. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22880. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22881. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22882. if (!mesh.rotationQuaternion) {
  22883. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22884. }
  22885. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22886. mesh.computeWorldMatrix();
  22887. }
  22888. else {
  22889. m = body.getMatrix();
  22890. mtx = BABYLON.Matrix.FromArray(m);
  22891. // Body position
  22892. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22893. if (!delta) {
  22894. mesh.position.x = bodyX;
  22895. mesh.position.y = bodyY;
  22896. mesh.position.z = bodyZ;
  22897. }
  22898. else {
  22899. mesh.position.x = bodyX + delta.x;
  22900. mesh.position.y = bodyY + delta.y;
  22901. mesh.position.z = bodyZ + delta.z;
  22902. }
  22903. if (!mesh.rotationQuaternion) {
  22904. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22905. }
  22906. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22907. mesh.computeWorldMatrix();
  22908. }
  22909. }
  22910. }
  22911. };
  22912. return OimoJSPlugin;
  22913. })();
  22914. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22915. })(BABYLON || (BABYLON = {}));
  22916. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22917. var BABYLON;
  22918. (function (BABYLON) {
  22919. var PhysicsEngine = (function () {
  22920. function PhysicsEngine(plugin) {
  22921. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22922. }
  22923. PhysicsEngine.prototype._initialize = function (gravity) {
  22924. this._currentPlugin.initialize();
  22925. this._setGravity(gravity);
  22926. };
  22927. PhysicsEngine.prototype._runOneStep = function (delta) {
  22928. if (delta > 0.1) {
  22929. delta = 0.1;
  22930. }
  22931. else if (delta <= 0) {
  22932. delta = 1.0 / 60.0;
  22933. }
  22934. this._currentPlugin.runOneStep(delta);
  22935. };
  22936. PhysicsEngine.prototype._setGravity = function (gravity) {
  22937. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  22938. this._currentPlugin.setGravity(this.gravity);
  22939. };
  22940. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22941. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22942. };
  22943. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22944. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22945. };
  22946. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22947. this._currentPlugin.unregisterMesh(mesh);
  22948. };
  22949. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22950. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22951. };
  22952. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22953. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22954. };
  22955. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22956. this._currentPlugin.updateBodyPosition(mesh);
  22957. };
  22958. PhysicsEngine.prototype.dispose = function () {
  22959. this._currentPlugin.dispose();
  22960. };
  22961. PhysicsEngine.prototype.isSupported = function () {
  22962. return this._currentPlugin.isSupported();
  22963. };
  22964. // Statics
  22965. PhysicsEngine.NoImpostor = 0;
  22966. PhysicsEngine.SphereImpostor = 1;
  22967. PhysicsEngine.BoxImpostor = 2;
  22968. PhysicsEngine.PlaneImpostor = 3;
  22969. PhysicsEngine.MeshImpostor = 4;
  22970. PhysicsEngine.CapsuleImpostor = 5;
  22971. PhysicsEngine.ConeImpostor = 6;
  22972. PhysicsEngine.CylinderImpostor = 7;
  22973. PhysicsEngine.ConvexHullImpostor = 8;
  22974. PhysicsEngine.Epsilon = 0.001;
  22975. return PhysicsEngine;
  22976. })();
  22977. BABYLON.PhysicsEngine = PhysicsEngine;
  22978. })(BABYLON || (BABYLON = {}));
  22979. //# sourceMappingURL=babylon.physicsEngine.js.map
  22980. var BABYLON;
  22981. (function (BABYLON) {
  22982. var serializeLight = function (light) {
  22983. var serializationObject = {};
  22984. serializationObject.name = light.name;
  22985. serializationObject.id = light.id;
  22986. serializationObject.tags = BABYLON.Tags.GetTags(light);
  22987. if (light instanceof BABYLON.PointLight) {
  22988. serializationObject.type = 0;
  22989. serializationObject.position = light.position.asArray();
  22990. }
  22991. else if (light instanceof BABYLON.DirectionalLight) {
  22992. serializationObject.type = 1;
  22993. var directionalLight = light;
  22994. serializationObject.position = directionalLight.position.asArray();
  22995. serializationObject.direction = directionalLight.direction.asArray();
  22996. }
  22997. else if (light instanceof BABYLON.SpotLight) {
  22998. serializationObject.type = 2;
  22999. var spotLight = light;
  23000. serializationObject.position = spotLight.position.asArray();
  23001. serializationObject.direction = spotLight.position.asArray();
  23002. serializationObject.angle = spotLight.angle;
  23003. serializationObject.exponent = spotLight.exponent;
  23004. }
  23005. else if (light instanceof BABYLON.HemisphericLight) {
  23006. serializationObject.type = 3;
  23007. var hemisphericLight = light;
  23008. serializationObject.direction = hemisphericLight.direction.asArray();
  23009. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23010. }
  23011. if (light.intensity) {
  23012. serializationObject.intensity = light.intensity;
  23013. }
  23014. serializationObject.range = light.range;
  23015. serializationObject.diffuse = light.diffuse.asArray();
  23016. serializationObject.specular = light.specular.asArray();
  23017. return serializationObject;
  23018. };
  23019. var serializeFresnelParameter = function (fresnelParameter) {
  23020. var serializationObject = {};
  23021. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23022. serializationObject.leftColor = fresnelParameter.leftColor;
  23023. serializationObject.rightColor = fresnelParameter.rightColor;
  23024. serializationObject.bias = fresnelParameter.bias;
  23025. serializationObject.power = fresnelParameter.power;
  23026. return serializationObject;
  23027. };
  23028. var appendAnimations = function (source, destination) {
  23029. if (source.animations) {
  23030. destination.animations = [];
  23031. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23032. var animation = source.animations[animationIndex];
  23033. destination.animations.push(serializeAnimation(animation));
  23034. }
  23035. }
  23036. };
  23037. var serializeCamera = function (camera) {
  23038. var serializationObject = {};
  23039. serializationObject.name = camera.name;
  23040. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23041. serializationObject.id = camera.id;
  23042. serializationObject.position = camera.position.asArray();
  23043. // Parent
  23044. if (camera.parent) {
  23045. serializationObject.parentId = camera.parent.id;
  23046. }
  23047. serializationObject.fov = camera.fov;
  23048. serializationObject.minZ = camera.minZ;
  23049. serializationObject.maxZ = camera.maxZ;
  23050. serializationObject.inertia = camera.inertia;
  23051. //setting the type
  23052. if (camera instanceof BABYLON.FreeCamera) {
  23053. serializationObject.type = "FreeCamera";
  23054. }
  23055. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23056. serializationObject.type = "ArcRotateCamera";
  23057. }
  23058. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23059. serializationObject.type = "AnaglyphArcRotateCamera";
  23060. }
  23061. else if (camera instanceof BABYLON.GamepadCamera) {
  23062. serializationObject.type = "GamepadCamera";
  23063. }
  23064. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23065. serializationObject.type = "AnaglyphFreeCamera";
  23066. }
  23067. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23068. serializationObject.type = "DeviceOrientationCamera";
  23069. }
  23070. else if (camera instanceof BABYLON.FollowCamera) {
  23071. serializationObject.type = "FollowCamera";
  23072. }
  23073. else if (camera instanceof BABYLON.TouchCamera) {
  23074. serializationObject.type = "TouchCamera";
  23075. }
  23076. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23077. serializationObject.type = "VirtualJoysticksCamera";
  23078. }
  23079. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23080. serializationObject.type = "WebVRFreeCamera";
  23081. }
  23082. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23083. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23084. }
  23085. //special properties of specific cameras
  23086. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23087. var arcCamera = camera;
  23088. serializationObject.alpha = arcCamera.alpha;
  23089. serializationObject.beta = arcCamera.beta;
  23090. serializationObject.radius = arcCamera.radius;
  23091. if (arcCamera.target && arcCamera.target.id) {
  23092. serializationObject.lockedTargetId = arcCamera.target.id;
  23093. }
  23094. }
  23095. else if (camera instanceof BABYLON.FollowCamera) {
  23096. var followCam = camera;
  23097. serializationObject.radius = followCam.radius;
  23098. serializationObject.heightOffset = followCam.heightOffset;
  23099. serializationObject.rotationOffset = followCam.rotationOffset;
  23100. }
  23101. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23102. //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.
  23103. if (camera['_eyeSpace'] !== undefined) {
  23104. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23105. }
  23106. }
  23107. //general properties that not all cameras have. The [] is due to typescript's type safety
  23108. if (camera['speed'] !== undefined) {
  23109. serializationObject.speed = camera['speed'];
  23110. }
  23111. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23112. serializationObject.target = camera['target'].asArray();
  23113. }
  23114. // Target
  23115. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23116. serializationObject.rotation = camera['rotation'].asArray();
  23117. }
  23118. // Locked target
  23119. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23120. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23121. }
  23122. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23123. serializationObject.applyGravity = camera['applyGravity'] || false;
  23124. if (camera['ellipsoid']) {
  23125. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23126. }
  23127. // Animations
  23128. appendAnimations(camera, serializationObject);
  23129. // Layer mask
  23130. serializationObject.layerMask = camera.layerMask;
  23131. return serializationObject;
  23132. };
  23133. var serializeAnimation = function (animation) {
  23134. var serializationObject = {};
  23135. serializationObject.name = animation.name;
  23136. serializationObject.property = animation.targetProperty;
  23137. serializationObject.framePerSecond = animation.framePerSecond;
  23138. serializationObject.dataType = animation.dataType;
  23139. serializationObject.loopBehavior = animation.loopMode;
  23140. var dataType = animation.dataType;
  23141. serializationObject.keys = [];
  23142. var keys = animation.getKeys();
  23143. for (var index = 0; index < keys.length; index++) {
  23144. var animationKey = keys[index];
  23145. var key = {};
  23146. key.frame = animationKey.frame;
  23147. switch (dataType) {
  23148. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23149. key.values = [animationKey.value];
  23150. break;
  23151. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23152. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23153. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23154. key.values = animationKey.value.asArray();
  23155. break;
  23156. }
  23157. serializationObject.keys.push(key);
  23158. }
  23159. return serializationObject;
  23160. };
  23161. var serializeMultiMaterial = function (material) {
  23162. var serializationObject = {};
  23163. serializationObject.name = material.name;
  23164. serializationObject.id = material.id;
  23165. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23166. serializationObject.materials = [];
  23167. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23168. var subMat = material.subMaterials[matIndex];
  23169. if (subMat) {
  23170. serializationObject.materials.push(subMat.id);
  23171. }
  23172. else {
  23173. serializationObject.materials.push(null);
  23174. }
  23175. }
  23176. return serializationObject;
  23177. };
  23178. var serializeMaterial = function (material) {
  23179. var serializationObject = {};
  23180. serializationObject.name = material.name;
  23181. serializationObject.ambient = material.ambientColor.asArray();
  23182. serializationObject.diffuse = material.diffuseColor.asArray();
  23183. serializationObject.specular = material.specularColor.asArray();
  23184. serializationObject.specularPower = material.specularPower;
  23185. serializationObject.emissive = material.emissiveColor.asArray();
  23186. serializationObject.alpha = material.alpha;
  23187. serializationObject.id = material.id;
  23188. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23189. serializationObject.backFaceCulling = material.backFaceCulling;
  23190. if (material.diffuseTexture) {
  23191. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23192. }
  23193. if (material.diffuseFresnelParameters) {
  23194. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23195. }
  23196. if (material.ambientTexture) {
  23197. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23198. }
  23199. if (material.opacityTexture) {
  23200. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23201. }
  23202. if (material.opacityFresnelParameters) {
  23203. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23204. }
  23205. if (material.reflectionTexture) {
  23206. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23207. }
  23208. if (material.reflectionFresnelParameters) {
  23209. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23210. }
  23211. if (material.emissiveTexture) {
  23212. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23213. }
  23214. if (material.emissiveFresnelParameters) {
  23215. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23216. }
  23217. if (material.specularTexture) {
  23218. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23219. }
  23220. if (material.bumpTexture) {
  23221. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23222. }
  23223. return serializationObject;
  23224. };
  23225. var serializeTexture = function (texture) {
  23226. var serializationObject = {};
  23227. if (!texture.name) {
  23228. return null;
  23229. }
  23230. if (texture instanceof BABYLON.CubeTexture) {
  23231. serializationObject.name = texture.name;
  23232. serializationObject.hasAlpha = texture.hasAlpha;
  23233. serializationObject.level = texture.level;
  23234. serializationObject.coordinatesMode = texture.coordinatesMode;
  23235. return serializationObject;
  23236. }
  23237. if (texture instanceof BABYLON.MirrorTexture) {
  23238. var mirrorTexture = texture;
  23239. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23240. serializationObject.renderList = [];
  23241. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23242. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23243. }
  23244. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23245. }
  23246. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23247. var renderTargetTexture = texture;
  23248. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23249. serializationObject.renderList = [];
  23250. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23251. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23252. }
  23253. }
  23254. var regularTexture = texture;
  23255. serializationObject.name = texture.name;
  23256. serializationObject.hasAlpha = texture.hasAlpha;
  23257. serializationObject.level = texture.level;
  23258. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23259. serializationObject.coordinatesMode = texture.coordinatesMode;
  23260. serializationObject.uOffset = regularTexture.uOffset;
  23261. serializationObject.vOffset = regularTexture.vOffset;
  23262. serializationObject.uScale = regularTexture.uScale;
  23263. serializationObject.vScale = regularTexture.vScale;
  23264. serializationObject.uAng = regularTexture.uAng;
  23265. serializationObject.vAng = regularTexture.vAng;
  23266. serializationObject.wAng = regularTexture.wAng;
  23267. serializationObject.wrapU = texture.wrapU;
  23268. serializationObject.wrapV = texture.wrapV;
  23269. // Animations
  23270. appendAnimations(texture, serializationObject);
  23271. return serializationObject;
  23272. };
  23273. var serializeSkeleton = function (skeleton) {
  23274. var serializationObject = {};
  23275. serializationObject.name = skeleton.name;
  23276. serializationObject.id = skeleton.id;
  23277. serializationObject.bones = [];
  23278. for (var index = 0; index < skeleton.bones.length; index++) {
  23279. var bone = skeleton.bones[index];
  23280. var serializedBone = {
  23281. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23282. name: bone.name,
  23283. matrix: bone.getLocalMatrix().toArray()
  23284. };
  23285. serializationObject.bones.push(serializedBone);
  23286. if (bone.animations && bone.animations.length > 0) {
  23287. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23288. }
  23289. }
  23290. return serializationObject;
  23291. };
  23292. var serializeParticleSystem = function (particleSystem) {
  23293. var serializationObject = {};
  23294. serializationObject.emitterId = particleSystem.emitter.id;
  23295. serializationObject.capacity = particleSystem.getCapacity();
  23296. if (particleSystem.particleTexture) {
  23297. serializationObject.textureName = particleSystem.particleTexture.name;
  23298. }
  23299. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23300. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23301. serializationObject.minSize = particleSystem.minSize;
  23302. serializationObject.maxSize = particleSystem.maxSize;
  23303. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23304. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23305. serializationObject.emitRate = particleSystem.emitRate;
  23306. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23307. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23308. serializationObject.gravity = particleSystem.gravity.asArray();
  23309. serializationObject.direction1 = particleSystem.direction1.asArray();
  23310. serializationObject.direction2 = particleSystem.direction2.asArray();
  23311. serializationObject.color1 = particleSystem.color1.asArray();
  23312. serializationObject.color2 = particleSystem.color2.asArray();
  23313. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23314. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23315. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23316. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23317. serializationObject.blendMode = particleSystem.blendMode;
  23318. return serializationObject;
  23319. };
  23320. var serializeLensFlareSystem = function (lensFlareSystem) {
  23321. var serializationObject = {};
  23322. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23323. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23324. serializationObject.flares = [];
  23325. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23326. var flare = lensFlareSystem.lensFlares[index];
  23327. serializationObject.flares.push({
  23328. size: flare.size,
  23329. position: flare.position,
  23330. color: flare.color.asArray(),
  23331. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23332. });
  23333. }
  23334. return serializationObject;
  23335. };
  23336. var serializeShadowGenerator = function (light) {
  23337. var serializationObject = {};
  23338. var shadowGenerator = light.getShadowGenerator();
  23339. serializationObject.lightId = light.id;
  23340. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23341. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23342. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23343. serializationObject.renderList = [];
  23344. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23345. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23346. serializationObject.renderList.push(mesh.id);
  23347. }
  23348. return serializationObject;
  23349. };
  23350. var serializedGeometries = [];
  23351. var serializeGeometry = function (geometry, serializationGeometries) {
  23352. if (serializedGeometries[geometry.id]) {
  23353. return;
  23354. }
  23355. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23356. serializationGeometries.boxes.push(serializeBox(geometry));
  23357. }
  23358. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23359. serializationGeometries.spheres.push(serializeSphere(geometry));
  23360. }
  23361. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23362. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23363. }
  23364. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23365. serializationGeometries.toruses.push(serializeTorus(geometry));
  23366. }
  23367. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23368. serializationGeometries.grounds.push(serializeGround(geometry));
  23369. }
  23370. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23371. serializationGeometries.planes.push(serializePlane(geometry));
  23372. }
  23373. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23374. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23375. }
  23376. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23377. throw new Error("Unknow primitive type");
  23378. }
  23379. else {
  23380. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23381. }
  23382. serializedGeometries[geometry.id] = true;
  23383. };
  23384. var serializeGeometryBase = function (geometry) {
  23385. var serializationObject = {};
  23386. serializationObject.id = geometry.id;
  23387. if (BABYLON.Tags.HasTags(geometry)) {
  23388. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23389. }
  23390. return serializationObject;
  23391. };
  23392. var serializeVertexData = function (vertexData) {
  23393. var serializationObject = serializeGeometryBase(vertexData);
  23394. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23395. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23396. }
  23397. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23398. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23399. }
  23400. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23401. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23402. }
  23403. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23404. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23405. }
  23406. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23407. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23408. }
  23409. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23410. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23411. serializationObject.matricesIndices._isExpanded = true;
  23412. }
  23413. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23414. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23415. }
  23416. serializationObject.indices = vertexData.getIndices();
  23417. return serializationObject;
  23418. };
  23419. var serializePrimitive = function (primitive) {
  23420. var serializationObject = serializeGeometryBase(primitive);
  23421. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23422. return serializationObject;
  23423. };
  23424. var serializeBox = function (box) {
  23425. var serializationObject = serializePrimitive(box);
  23426. serializationObject.size = box.size;
  23427. return serializationObject;
  23428. };
  23429. var serializeSphere = function (sphere) {
  23430. var serializationObject = serializePrimitive(sphere);
  23431. serializationObject.segments = sphere.segments;
  23432. serializationObject.diameter = sphere.diameter;
  23433. return serializationObject;
  23434. };
  23435. var serializeCylinder = function (cylinder) {
  23436. var serializationObject = serializePrimitive(cylinder);
  23437. serializationObject.height = cylinder.height;
  23438. serializationObject.diameterTop = cylinder.diameterTop;
  23439. serializationObject.diameterBottom = cylinder.diameterBottom;
  23440. serializationObject.tessellation = cylinder.tessellation;
  23441. return serializationObject;
  23442. };
  23443. var serializeTorus = function (torus) {
  23444. var serializationObject = serializePrimitive(torus);
  23445. serializationObject.diameter = torus.diameter;
  23446. serializationObject.thickness = torus.thickness;
  23447. serializationObject.tessellation = torus.tessellation;
  23448. return serializationObject;
  23449. };
  23450. var serializeGround = function (ground) {
  23451. var serializationObject = serializePrimitive(ground);
  23452. serializationObject.width = ground.width;
  23453. serializationObject.height = ground.height;
  23454. serializationObject.subdivisions = ground.subdivisions;
  23455. return serializationObject;
  23456. };
  23457. var serializePlane = function (plane) {
  23458. var serializationObject = serializePrimitive(plane);
  23459. serializationObject.size = plane.size;
  23460. return serializationObject;
  23461. };
  23462. var serializeTorusKnot = function (torusKnot) {
  23463. var serializationObject = serializePrimitive(torusKnot);
  23464. serializationObject.radius = torusKnot.radius;
  23465. serializationObject.tube = torusKnot.tube;
  23466. serializationObject.radialSegments = torusKnot.radialSegments;
  23467. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23468. serializationObject.p = torusKnot.p;
  23469. serializationObject.q = torusKnot.q;
  23470. return serializationObject;
  23471. };
  23472. var serializeMesh = function (mesh, serializationScene) {
  23473. var serializationObject = {};
  23474. serializationObject.name = mesh.name;
  23475. serializationObject.id = mesh.id;
  23476. if (BABYLON.Tags.HasTags(mesh)) {
  23477. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23478. }
  23479. serializationObject.position = mesh.position.asArray();
  23480. if (mesh.rotationQuaternion) {
  23481. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23482. }
  23483. else if (mesh.rotation) {
  23484. serializationObject.rotation = mesh.rotation.asArray();
  23485. }
  23486. serializationObject.scaling = mesh.scaling.asArray();
  23487. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23488. serializationObject.isEnabled = mesh.isEnabled();
  23489. serializationObject.isVisible = mesh.isVisible;
  23490. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23491. serializationObject.pickable = mesh.isPickable;
  23492. serializationObject.receiveShadows = mesh.receiveShadows;
  23493. serializationObject.billboardMode = mesh.billboardMode;
  23494. serializationObject.visibility = mesh.visibility;
  23495. serializationObject.checkCollisions = mesh.checkCollisions;
  23496. // Parent
  23497. if (mesh.parent) {
  23498. serializationObject.parentId = mesh.parent.id;
  23499. }
  23500. // Geometry
  23501. var geometry = mesh._geometry;
  23502. if (geometry) {
  23503. var geometryId = geometry.id;
  23504. serializationObject.geometryId = geometryId;
  23505. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23506. // 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
  23507. serializeGeometry(geometry, serializationScene.geometries);
  23508. }
  23509. // SubMeshes
  23510. serializationObject.subMeshes = [];
  23511. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23512. var subMesh = mesh.subMeshes[subIndex];
  23513. serializationObject.subMeshes.push({
  23514. materialIndex: subMesh.materialIndex,
  23515. verticesStart: subMesh.verticesStart,
  23516. verticesCount: subMesh.verticesCount,
  23517. indexStart: subMesh.indexStart,
  23518. indexCount: subMesh.indexCount
  23519. });
  23520. }
  23521. }
  23522. // Material
  23523. if (mesh.material) {
  23524. serializationObject.materialId = mesh.material.id;
  23525. }
  23526. else {
  23527. mesh.material = null;
  23528. }
  23529. // Skeleton
  23530. if (mesh.skeleton) {
  23531. serializationObject.skeletonId = mesh.skeleton.id;
  23532. }
  23533. // Physics
  23534. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23535. serializationObject.physicsMass = mesh.getPhysicsMass();
  23536. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23537. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23538. switch (mesh.getPhysicsImpostor()) {
  23539. case BABYLON.PhysicsEngine.BoxImpostor:
  23540. serializationObject.physicsImpostor = 1;
  23541. break;
  23542. case BABYLON.PhysicsEngine.SphereImpostor:
  23543. serializationObject.physicsImpostor = 2;
  23544. break;
  23545. }
  23546. }
  23547. // Instances
  23548. serializationObject.instances = [];
  23549. for (var index = 0; index < mesh.instances.length; index++) {
  23550. var instance = mesh.instances[index];
  23551. var serializationInstance = {
  23552. name: instance.name,
  23553. position: instance.position,
  23554. rotation: instance.rotation,
  23555. rotationQuaternion: instance.rotationQuaternion,
  23556. scaling: instance.scaling
  23557. };
  23558. serializationObject.instances.push(serializationInstance);
  23559. // Animations
  23560. appendAnimations(instance, serializationInstance);
  23561. }
  23562. // Animations
  23563. appendAnimations(mesh, serializationObject);
  23564. // Layer mask
  23565. serializationObject.layerMask = mesh.layerMask;
  23566. return serializationObject;
  23567. };
  23568. var SceneSerializer = (function () {
  23569. function SceneSerializer() {
  23570. }
  23571. SceneSerializer.Serialize = function (scene) {
  23572. var serializationObject = {};
  23573. // Scene
  23574. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23575. serializationObject.autoClear = scene.autoClear;
  23576. serializationObject.clearColor = scene.clearColor.asArray();
  23577. serializationObject.ambientColor = scene.ambientColor.asArray();
  23578. serializationObject.gravity = scene.gravity.asArray();
  23579. // Fog
  23580. if (scene.fogMode && scene.fogMode !== 0) {
  23581. serializationObject.fogMode = scene.fogMode;
  23582. serializationObject.fogColor = scene.fogColor.asArray();
  23583. serializationObject.fogStart = scene.fogStart;
  23584. serializationObject.fogEnd = scene.fogEnd;
  23585. serializationObject.fogDensity = scene.fogDensity;
  23586. }
  23587. // Lights
  23588. serializationObject.lights = [];
  23589. for (var index = 0; index < scene.lights.length; index++) {
  23590. var light = scene.lights[index];
  23591. serializationObject.lights.push(serializeLight(light));
  23592. }
  23593. // Cameras
  23594. serializationObject.cameras = [];
  23595. for (index = 0; index < scene.cameras.length; index++) {
  23596. var camera = scene.cameras[index];
  23597. serializationObject.cameras.push(serializeCamera(camera));
  23598. }
  23599. if (scene.activeCamera) {
  23600. serializationObject.activeCameraID = scene.activeCamera.id;
  23601. }
  23602. // Materials
  23603. serializationObject.materials = [];
  23604. serializationObject.multiMaterials = [];
  23605. for (index = 0; index < scene.materials.length; index++) {
  23606. var material = scene.materials[index];
  23607. if (material instanceof BABYLON.StandardMaterial) {
  23608. serializationObject.materials.push(serializeMaterial(material));
  23609. }
  23610. else if (material instanceof BABYLON.MultiMaterial) {
  23611. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23612. }
  23613. }
  23614. // Skeletons
  23615. serializationObject.skeletons = [];
  23616. for (index = 0; index < scene.skeletons.length; index++) {
  23617. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23618. }
  23619. // Geometries
  23620. serializationObject.geometries = {};
  23621. serializationObject.geometries.boxes = [];
  23622. serializationObject.geometries.spheres = [];
  23623. serializationObject.geometries.cylinders = [];
  23624. serializationObject.geometries.toruses = [];
  23625. serializationObject.geometries.grounds = [];
  23626. serializationObject.geometries.planes = [];
  23627. serializationObject.geometries.torusKnots = [];
  23628. serializationObject.geometries.vertexData = [];
  23629. serializedGeometries = [];
  23630. var geometries = scene.getGeometries();
  23631. for (index = 0; index < geometries.length; index++) {
  23632. var geometry = geometries[index];
  23633. if (geometry.isReady()) {
  23634. serializeGeometry(geometry, serializationObject.geometries);
  23635. }
  23636. }
  23637. // Meshes
  23638. serializationObject.meshes = [];
  23639. for (index = 0; index < scene.meshes.length; index++) {
  23640. var abstractMesh = scene.meshes[index];
  23641. if (abstractMesh instanceof BABYLON.Mesh) {
  23642. var mesh = abstractMesh;
  23643. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23644. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23645. }
  23646. }
  23647. }
  23648. // Particles Systems
  23649. serializationObject.particleSystems = [];
  23650. for (index = 0; index < scene.particleSystems.length; index++) {
  23651. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23652. }
  23653. // Lens flares
  23654. serializationObject.lensFlareSystems = [];
  23655. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23656. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23657. }
  23658. // Shadows
  23659. serializationObject.shadowGenerators = [];
  23660. for (index = 0; index < scene.lights.length; index++) {
  23661. light = scene.lights[index];
  23662. if (light.getShadowGenerator()) {
  23663. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23664. }
  23665. }
  23666. return serializationObject;
  23667. };
  23668. return SceneSerializer;
  23669. })();
  23670. BABYLON.SceneSerializer = SceneSerializer;
  23671. })(BABYLON || (BABYLON = {}));
  23672. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23673. var BABYLON;
  23674. (function (BABYLON) {
  23675. // Unique ID when we import meshes from Babylon to CSG
  23676. var currentCSGMeshId = 0;
  23677. // # class Vertex
  23678. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23679. // one to provide additional features like texture coordinates and vertex
  23680. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23681. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23682. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23683. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23684. // is not used anywhere else.
  23685. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23686. var Vertex = (function () {
  23687. function Vertex(pos, normal, uv) {
  23688. this.pos = pos;
  23689. this.normal = normal;
  23690. this.uv = uv;
  23691. }
  23692. Vertex.prototype.clone = function () {
  23693. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23694. };
  23695. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23696. // orientation of a polygon is flipped.
  23697. Vertex.prototype.flip = function () {
  23698. this.normal = this.normal.scale(-1);
  23699. };
  23700. // Create a new vertex between this vertex and `other` by linearly
  23701. // interpolating all properties using a parameter of `t`. Subclasses should
  23702. // override this to interpolate additional properties.
  23703. Vertex.prototype.interpolate = function (other, t) {
  23704. 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));
  23705. };
  23706. return Vertex;
  23707. })();
  23708. // # class Plane
  23709. // Represents a plane in 3D space.
  23710. var Plane = (function () {
  23711. function Plane(normal, w) {
  23712. this.normal = normal;
  23713. this.w = w;
  23714. }
  23715. Plane.FromPoints = function (a, b, c) {
  23716. var v0 = c.subtract(a);
  23717. var v1 = b.subtract(a);
  23718. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23719. return null;
  23720. }
  23721. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23722. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23723. };
  23724. Plane.prototype.clone = function () {
  23725. return new Plane(this.normal.clone(), this.w);
  23726. };
  23727. Plane.prototype.flip = function () {
  23728. this.normal.scaleInPlace(-1);
  23729. this.w = -this.w;
  23730. };
  23731. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23732. // fragments in the appropriate lists. Coplanar polygons go into either
  23733. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23734. // respect to this plane. Polygons in front or in back of this plane go into
  23735. // either `front` or `back`.
  23736. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23737. var COPLANAR = 0;
  23738. var FRONT = 1;
  23739. var BACK = 2;
  23740. var SPANNING = 3;
  23741. // Classify each point as well as the entire polygon into one of the above
  23742. // four classes.
  23743. var polygonType = 0;
  23744. var types = [];
  23745. for (var i = 0; i < polygon.vertices.length; i++) {
  23746. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23747. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23748. polygonType |= type;
  23749. types.push(type);
  23750. }
  23751. switch (polygonType) {
  23752. case COPLANAR:
  23753. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23754. break;
  23755. case FRONT:
  23756. front.push(polygon);
  23757. break;
  23758. case BACK:
  23759. back.push(polygon);
  23760. break;
  23761. case SPANNING:
  23762. var f = [], b = [];
  23763. for (i = 0; i < polygon.vertices.length; i++) {
  23764. var j = (i + 1) % polygon.vertices.length;
  23765. var ti = types[i], tj = types[j];
  23766. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23767. if (ti != BACK)
  23768. f.push(vi);
  23769. if (ti != FRONT)
  23770. b.push(ti != BACK ? vi.clone() : vi);
  23771. if ((ti | tj) == SPANNING) {
  23772. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23773. var v = vi.interpolate(vj, t);
  23774. f.push(v);
  23775. b.push(v.clone());
  23776. }
  23777. }
  23778. if (f.length >= 3) {
  23779. var poly = new Polygon(f, polygon.shared);
  23780. if (poly.plane)
  23781. front.push(poly);
  23782. }
  23783. if (b.length >= 3) {
  23784. poly = new Polygon(b, polygon.shared);
  23785. if (poly.plane)
  23786. back.push(poly);
  23787. }
  23788. break;
  23789. }
  23790. };
  23791. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23792. // point is on the plane.
  23793. Plane.EPSILON = 1e-5;
  23794. return Plane;
  23795. })();
  23796. // # class Polygon
  23797. // Represents a convex polygon. The vertices used to initialize a polygon must
  23798. // be coplanar and form a convex loop.
  23799. //
  23800. // Each convex polygon has a `shared` property, which is shared between all
  23801. // polygons that are clones of each other or were split from the same polygon.
  23802. // This can be used to define per-polygon properties (such as surface color).
  23803. var Polygon = (function () {
  23804. function Polygon(vertices, shared) {
  23805. this.vertices = vertices;
  23806. this.shared = shared;
  23807. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23808. }
  23809. Polygon.prototype.clone = function () {
  23810. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23811. return new Polygon(vertices, this.shared);
  23812. };
  23813. Polygon.prototype.flip = function () {
  23814. this.vertices.reverse().map(function (v) {
  23815. v.flip();
  23816. });
  23817. this.plane.flip();
  23818. };
  23819. return Polygon;
  23820. })();
  23821. // # class Node
  23822. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23823. // by picking a polygon to split along. That polygon (and all other coplanar
  23824. // polygons) are added directly to that node and the other polygons are added to
  23825. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23826. // no distinction between internal and leaf nodes.
  23827. var Node = (function () {
  23828. function Node(polygons) {
  23829. this.plane = null;
  23830. this.front = null;
  23831. this.back = null;
  23832. this.polygons = [];
  23833. if (polygons) {
  23834. this.build(polygons);
  23835. }
  23836. }
  23837. Node.prototype.clone = function () {
  23838. var node = new Node();
  23839. node.plane = this.plane && this.plane.clone();
  23840. node.front = this.front && this.front.clone();
  23841. node.back = this.back && this.back.clone();
  23842. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23843. return node;
  23844. };
  23845. // Convert solid space to empty space and empty space to solid space.
  23846. Node.prototype.invert = function () {
  23847. for (var i = 0; i < this.polygons.length; i++) {
  23848. this.polygons[i].flip();
  23849. }
  23850. if (this.plane) {
  23851. this.plane.flip();
  23852. }
  23853. if (this.front) {
  23854. this.front.invert();
  23855. }
  23856. if (this.back) {
  23857. this.back.invert();
  23858. }
  23859. var temp = this.front;
  23860. this.front = this.back;
  23861. this.back = temp;
  23862. };
  23863. // Recursively remove all polygons in `polygons` that are inside this BSP
  23864. // tree.
  23865. Node.prototype.clipPolygons = function (polygons) {
  23866. if (!this.plane)
  23867. return polygons.slice();
  23868. var front = [], back = [];
  23869. for (var i = 0; i < polygons.length; i++) {
  23870. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23871. }
  23872. if (this.front) {
  23873. front = this.front.clipPolygons(front);
  23874. }
  23875. if (this.back) {
  23876. back = this.back.clipPolygons(back);
  23877. }
  23878. else {
  23879. back = [];
  23880. }
  23881. return front.concat(back);
  23882. };
  23883. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23884. // `bsp`.
  23885. Node.prototype.clipTo = function (bsp) {
  23886. this.polygons = bsp.clipPolygons(this.polygons);
  23887. if (this.front)
  23888. this.front.clipTo(bsp);
  23889. if (this.back)
  23890. this.back.clipTo(bsp);
  23891. };
  23892. // Return a list of all polygons in this BSP tree.
  23893. Node.prototype.allPolygons = function () {
  23894. var polygons = this.polygons.slice();
  23895. if (this.front)
  23896. polygons = polygons.concat(this.front.allPolygons());
  23897. if (this.back)
  23898. polygons = polygons.concat(this.back.allPolygons());
  23899. return polygons;
  23900. };
  23901. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23902. // new polygons are filtered down to the bottom of the tree and become new
  23903. // nodes there. Each set of polygons is partitioned using the first polygon
  23904. // (no heuristic is used to pick a good split).
  23905. Node.prototype.build = function (polygons) {
  23906. if (!polygons.length)
  23907. return;
  23908. if (!this.plane)
  23909. this.plane = polygons[0].plane.clone();
  23910. var front = [], back = [];
  23911. for (var i = 0; i < polygons.length; i++) {
  23912. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23913. }
  23914. if (front.length) {
  23915. if (!this.front)
  23916. this.front = new Node();
  23917. this.front.build(front);
  23918. }
  23919. if (back.length) {
  23920. if (!this.back)
  23921. this.back = new Node();
  23922. this.back.build(back);
  23923. }
  23924. };
  23925. return Node;
  23926. })();
  23927. var CSG = (function () {
  23928. function CSG() {
  23929. this.polygons = new Array();
  23930. }
  23931. // Convert BABYLON.Mesh to BABYLON.CSG
  23932. CSG.FromMesh = function (mesh) {
  23933. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  23934. if (mesh instanceof BABYLON.Mesh) {
  23935. mesh.computeWorldMatrix(true);
  23936. var matrix = mesh.getWorldMatrix();
  23937. var meshPosition = mesh.position.clone();
  23938. var meshRotation = mesh.rotation.clone();
  23939. var meshRotationQuaternion = mesh.rotationQuaternion.clone();
  23940. var meshScaling = mesh.scaling.clone();
  23941. }
  23942. else {
  23943. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  23944. }
  23945. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23946. var subMeshes = mesh.subMeshes;
  23947. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  23948. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  23949. vertices = [];
  23950. for (var j = 0; j < 3; j++) {
  23951. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  23952. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  23953. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  23954. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  23955. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  23956. vertex = new Vertex(position, normal, uv);
  23957. vertices.push(vertex);
  23958. }
  23959. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  23960. // To handle the case of degenerated triangle
  23961. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  23962. if (polygon.plane)
  23963. polygons.push(polygon);
  23964. }
  23965. }
  23966. var csg = CSG.FromPolygons(polygons);
  23967. csg.matrix = matrix;
  23968. csg.position = meshPosition;
  23969. csg.rotation = meshRotation;
  23970. csg.scaling = meshScaling;
  23971. csg.rotationQuaternion = meshRotationQuaternion;
  23972. currentCSGMeshId++;
  23973. return csg;
  23974. };
  23975. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  23976. CSG.FromPolygons = function (polygons) {
  23977. var csg = new BABYLON.CSG();
  23978. csg.polygons = polygons;
  23979. return csg;
  23980. };
  23981. CSG.prototype.clone = function () {
  23982. var csg = new BABYLON.CSG();
  23983. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  23984. csg.copyTransformAttributes(this);
  23985. return csg;
  23986. };
  23987. CSG.prototype.toPolygons = function () {
  23988. return this.polygons;
  23989. };
  23990. CSG.prototype.union = function (csg) {
  23991. var a = new Node(this.clone().polygons);
  23992. var b = new Node(csg.clone().polygons);
  23993. a.clipTo(b);
  23994. b.clipTo(a);
  23995. b.invert();
  23996. b.clipTo(a);
  23997. b.invert();
  23998. a.build(b.allPolygons());
  23999. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24000. };
  24001. CSG.prototype.unionInPlace = function (csg) {
  24002. var a = new Node(this.polygons);
  24003. var b = new Node(csg.polygons);
  24004. a.clipTo(b);
  24005. b.clipTo(a);
  24006. b.invert();
  24007. b.clipTo(a);
  24008. b.invert();
  24009. a.build(b.allPolygons());
  24010. this.polygons = a.allPolygons();
  24011. };
  24012. CSG.prototype.subtract = function (csg) {
  24013. var a = new Node(this.clone().polygons);
  24014. var b = new Node(csg.clone().polygons);
  24015. a.invert();
  24016. a.clipTo(b);
  24017. b.clipTo(a);
  24018. b.invert();
  24019. b.clipTo(a);
  24020. b.invert();
  24021. a.build(b.allPolygons());
  24022. a.invert();
  24023. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24024. };
  24025. CSG.prototype.subtractInPlace = function (csg) {
  24026. var a = new Node(this.polygons);
  24027. var b = new Node(csg.polygons);
  24028. a.invert();
  24029. a.clipTo(b);
  24030. b.clipTo(a);
  24031. b.invert();
  24032. b.clipTo(a);
  24033. b.invert();
  24034. a.build(b.allPolygons());
  24035. a.invert();
  24036. this.polygons = a.allPolygons();
  24037. };
  24038. CSG.prototype.intersect = function (csg) {
  24039. var a = new Node(this.clone().polygons);
  24040. var b = new Node(csg.clone().polygons);
  24041. a.invert();
  24042. b.clipTo(a);
  24043. b.invert();
  24044. a.clipTo(b);
  24045. b.clipTo(a);
  24046. a.build(b.allPolygons());
  24047. a.invert();
  24048. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24049. };
  24050. CSG.prototype.intersectInPlace = function (csg) {
  24051. var a = new Node(this.polygons);
  24052. var b = new Node(csg.polygons);
  24053. a.invert();
  24054. b.clipTo(a);
  24055. b.invert();
  24056. a.clipTo(b);
  24057. b.clipTo(a);
  24058. a.build(b.allPolygons());
  24059. a.invert();
  24060. this.polygons = a.allPolygons();
  24061. };
  24062. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24063. // not modified.
  24064. CSG.prototype.inverse = function () {
  24065. var csg = this.clone();
  24066. csg.inverseInPlace();
  24067. return csg;
  24068. };
  24069. CSG.prototype.inverseInPlace = function () {
  24070. this.polygons.map(function (p) {
  24071. p.flip();
  24072. });
  24073. };
  24074. // This is used to keep meshes transformations so they can be restored
  24075. // when we build back a Babylon Mesh
  24076. // NB : All CSG operations are performed in world coordinates
  24077. CSG.prototype.copyTransformAttributes = function (csg) {
  24078. this.matrix = csg.matrix;
  24079. this.position = csg.position;
  24080. this.rotation = csg.rotation;
  24081. this.scaling = csg.scaling;
  24082. this.rotationQuaternion = csg.rotationQuaternion;
  24083. return this;
  24084. };
  24085. // Build Raw mesh from CSG
  24086. // Coordinates here are in world space
  24087. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24088. var matrix = this.matrix.clone();
  24089. matrix.invert();
  24090. 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;
  24091. if (keepSubMeshes) {
  24092. // Sort Polygons, since subMeshes are indices range
  24093. polygons.sort(function (a, b) {
  24094. if (a.shared.meshId === b.shared.meshId) {
  24095. return a.shared.subMeshId - b.shared.subMeshId;
  24096. }
  24097. else {
  24098. return a.shared.meshId - b.shared.meshId;
  24099. }
  24100. });
  24101. }
  24102. for (var i = 0, il = polygons.length; i < il; i++) {
  24103. polygon = polygons[i];
  24104. // Building SubMeshes
  24105. if (!subMesh_dict[polygon.shared.meshId]) {
  24106. subMesh_dict[polygon.shared.meshId] = {};
  24107. }
  24108. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24109. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24110. indexStart: +Infinity,
  24111. indexEnd: -Infinity,
  24112. materialIndex: polygon.shared.materialIndex
  24113. };
  24114. }
  24115. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24116. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24117. polygonIndices[0] = 0;
  24118. polygonIndices[1] = j - 1;
  24119. polygonIndices[2] = j;
  24120. for (var k = 0; k < 3; k++) {
  24121. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24122. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24123. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24124. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24125. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24126. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24127. // Check if 2 points can be merged
  24128. 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)) {
  24129. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24130. uvs.push(uv.x, uv.y);
  24131. normals.push(normal.x, normal.y, normal.z);
  24132. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24133. }
  24134. indices.push(vertex_idx);
  24135. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24136. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24137. currentIndex++;
  24138. }
  24139. }
  24140. }
  24141. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24142. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24143. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24144. mesh.setIndices(indices);
  24145. if (keepSubMeshes) {
  24146. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24147. var materialIndexOffset = 0, materialMaxIndex;
  24148. mesh.subMeshes.length = 0;
  24149. for (var m in subMesh_dict) {
  24150. materialMaxIndex = -1;
  24151. for (var sm in subMesh_dict[m]) {
  24152. subMesh_obj = subMesh_dict[m][sm];
  24153. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24154. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24155. }
  24156. materialIndexOffset += ++materialMaxIndex;
  24157. }
  24158. }
  24159. return mesh;
  24160. };
  24161. // Build Mesh from CSG taking material and transforms into account
  24162. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24163. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24164. mesh.material = material;
  24165. mesh.position.copyFrom(this.position);
  24166. mesh.rotation.copyFrom(this.rotation);
  24167. mesh.rotationQuaternion.copyFrom(this.rotationQuaternion);
  24168. mesh.scaling.copyFrom(this.scaling);
  24169. mesh.computeWorldMatrix(true);
  24170. return mesh;
  24171. };
  24172. return CSG;
  24173. })();
  24174. BABYLON.CSG = CSG;
  24175. })(BABYLON || (BABYLON = {}));
  24176. //# sourceMappingURL=babylon.csg.js.map
  24177. var __extends = this.__extends || function (d, b) {
  24178. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24179. function __() { this.constructor = d; }
  24180. __.prototype = b.prototype;
  24181. d.prototype = new __();
  24182. };
  24183. var BABYLON;
  24184. (function (BABYLON) {
  24185. var VRDistortionCorrectionPostProcess = (function (_super) {
  24186. __extends(VRDistortionCorrectionPostProcess, _super);
  24187. //ANY
  24188. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24189. var _this = this;
  24190. _super.call(this, name, "vrDistortionCorrection", [
  24191. 'LensCenter',
  24192. 'Scale',
  24193. 'ScaleIn',
  24194. 'HmdWarpParam'
  24195. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24196. this._isRightEye = isRightEye;
  24197. this._distortionFactors = vrMetrics.distortionK;
  24198. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24199. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24200. this.onSizeChanged = function () {
  24201. _this.aspectRatio = _this.width * .5 / _this.height;
  24202. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24203. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24204. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24205. };
  24206. this.onApply = function (effect) {
  24207. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24208. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24209. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24210. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24211. };
  24212. }
  24213. return VRDistortionCorrectionPostProcess;
  24214. })(BABYLON.PostProcess);
  24215. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24216. })(BABYLON || (BABYLON = {}));
  24217. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24218. // Mainly based on these 2 articles :
  24219. // 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
  24220. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24221. var BABYLON;
  24222. (function (BABYLON) {
  24223. (function (JoystickAxis) {
  24224. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24225. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24226. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24227. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24228. var JoystickAxis = BABYLON.JoystickAxis;
  24229. var VirtualJoystick = (function () {
  24230. function VirtualJoystick(leftJoystick) {
  24231. var _this = this;
  24232. if (leftJoystick) {
  24233. this._leftJoystick = true;
  24234. }
  24235. else {
  24236. this._leftJoystick = false;
  24237. }
  24238. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24239. VirtualJoystick._globalJoystickIndex++;
  24240. // By default left & right arrow keys are moving the X
  24241. // and up & down keys are moving the Y
  24242. this._axisTargetedByLeftAndRight = 0 /* X */;
  24243. this._axisTargetedByUpAndDown = 1 /* Y */;
  24244. this.reverseLeftRight = false;
  24245. this.reverseUpDown = false;
  24246. // collections of pointers
  24247. this._touches = new BABYLON.SmartCollection();
  24248. this.deltaPosition = BABYLON.Vector3.Zero();
  24249. this._joystickSensibility = 25;
  24250. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24251. this._rotationSpeed = 25;
  24252. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24253. this._rotateOnAxisRelativeToMesh = false;
  24254. // injecting a canvas element on top of the canvas 3D game
  24255. if (!VirtualJoystick.vjCanvas) {
  24256. window.addEventListener("resize", function () {
  24257. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24258. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24259. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24260. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24261. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24262. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24263. }, false);
  24264. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24265. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24266. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24267. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24268. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24269. VirtualJoystick.vjCanvas.style.width = "100%";
  24270. VirtualJoystick.vjCanvas.style.height = "100%";
  24271. VirtualJoystick.vjCanvas.style.position = "absolute";
  24272. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24273. VirtualJoystick.vjCanvas.style.top = "0px";
  24274. VirtualJoystick.vjCanvas.style.left = "0px";
  24275. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24276. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24277. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24278. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24279. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24280. document.body.appendChild(VirtualJoystick.vjCanvas);
  24281. }
  24282. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24283. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24284. this.pressed = false;
  24285. // default joystick color
  24286. this._joystickColor = "cyan";
  24287. this._joystickPointerID = -1;
  24288. // current joystick position
  24289. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24290. // origin joystick position
  24291. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24292. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24293. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24294. _this._onPointerDown(evt);
  24295. }, false);
  24296. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24297. _this._onPointerMove(evt);
  24298. }, false);
  24299. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24300. _this._onPointerUp(evt);
  24301. }, false);
  24302. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24303. _this._onPointerUp(evt);
  24304. }, false);
  24305. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24306. evt.preventDefault(); // Disables system menu
  24307. }, false);
  24308. requestAnimationFrame(function () {
  24309. _this._drawVirtualJoystick();
  24310. });
  24311. }
  24312. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24313. this._joystickSensibility = newJoystickSensibility;
  24314. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24315. };
  24316. VirtualJoystick.prototype._onPointerDown = function (e) {
  24317. var positionOnScreenCondition;
  24318. e.preventDefault();
  24319. if (this._leftJoystick === true) {
  24320. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24321. }
  24322. else {
  24323. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24324. }
  24325. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24326. // First contact will be dedicated to the virtual joystick
  24327. this._joystickPointerID = e.pointerId;
  24328. this._joystickPointerStartPos.x = e.clientX;
  24329. this._joystickPointerStartPos.y = e.clientY;
  24330. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24331. this._deltaJoystickVector.x = 0;
  24332. this._deltaJoystickVector.y = 0;
  24333. this.pressed = true;
  24334. this._touches.add(e.pointerId.toString(), e);
  24335. }
  24336. else {
  24337. // You can only trigger the action buttons with a joystick declared
  24338. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24339. this._action();
  24340. this._touches.add(e.pointerId.toString(), e);
  24341. }
  24342. }
  24343. };
  24344. VirtualJoystick.prototype._onPointerMove = function (e) {
  24345. // If the current pointer is the one associated to the joystick (first touch contact)
  24346. if (this._joystickPointerID == e.pointerId) {
  24347. this._joystickPointerPos.x = e.clientX;
  24348. this._joystickPointerPos.y = e.clientY;
  24349. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24350. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24351. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24352. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24353. switch (this._axisTargetedByLeftAndRight) {
  24354. case 0 /* X */:
  24355. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24356. break;
  24357. case 1 /* Y */:
  24358. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24359. break;
  24360. case 2 /* Z */:
  24361. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24362. break;
  24363. }
  24364. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24365. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24366. switch (this._axisTargetedByUpAndDown) {
  24367. case 0 /* X */:
  24368. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24369. break;
  24370. case 1 /* Y */:
  24371. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24372. break;
  24373. case 2 /* Z */:
  24374. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24375. break;
  24376. }
  24377. }
  24378. else {
  24379. if (this._touches.item(e.pointerId.toString())) {
  24380. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24381. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24382. }
  24383. }
  24384. };
  24385. VirtualJoystick.prototype._onPointerUp = function (e) {
  24386. this._clearCanvas();
  24387. if (this._joystickPointerID == e.pointerId) {
  24388. this._joystickPointerID = -1;
  24389. this.pressed = false;
  24390. }
  24391. this._deltaJoystickVector.x = 0;
  24392. this._deltaJoystickVector.y = 0;
  24393. this._touches.remove(e.pointerId.toString());
  24394. };
  24395. /**
  24396. * Change the color of the virtual joystick
  24397. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24398. */
  24399. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24400. this._joystickColor = newColor;
  24401. };
  24402. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24403. this._action = action;
  24404. };
  24405. // Define which axis you'd like to control for left & right
  24406. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24407. switch (axis) {
  24408. case 0 /* X */:
  24409. case 1 /* Y */:
  24410. case 2 /* Z */:
  24411. this._axisTargetedByLeftAndRight = axis;
  24412. break;
  24413. default:
  24414. this._axisTargetedByLeftAndRight = 0 /* X */;
  24415. break;
  24416. }
  24417. };
  24418. // Define which axis you'd like to control for up & down
  24419. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24420. switch (axis) {
  24421. case 0 /* X */:
  24422. case 1 /* Y */:
  24423. case 2 /* Z */:
  24424. this._axisTargetedByUpAndDown = axis;
  24425. break;
  24426. default:
  24427. this._axisTargetedByUpAndDown = 1 /* Y */;
  24428. break;
  24429. }
  24430. };
  24431. VirtualJoystick.prototype._clearCanvas = function () {
  24432. if (this._leftJoystick) {
  24433. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24434. }
  24435. else {
  24436. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24437. }
  24438. };
  24439. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24440. var _this = this;
  24441. if (this.pressed) {
  24442. this._clearCanvas();
  24443. this._touches.forEach(function (touch) {
  24444. if (touch.pointerId === _this._joystickPointerID) {
  24445. VirtualJoystick.vjCanvasContext.beginPath();
  24446. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24447. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24448. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24449. VirtualJoystick.vjCanvasContext.stroke();
  24450. VirtualJoystick.vjCanvasContext.beginPath();
  24451. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24452. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24453. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24454. VirtualJoystick.vjCanvasContext.stroke();
  24455. VirtualJoystick.vjCanvasContext.beginPath();
  24456. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24457. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24458. VirtualJoystick.vjCanvasContext.stroke();
  24459. }
  24460. else {
  24461. VirtualJoystick.vjCanvasContext.beginPath();
  24462. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24463. VirtualJoystick.vjCanvasContext.beginPath();
  24464. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24465. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24466. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24467. VirtualJoystick.vjCanvasContext.stroke();
  24468. }
  24469. ;
  24470. });
  24471. }
  24472. requestAnimationFrame(function () {
  24473. _this._drawVirtualJoystick();
  24474. });
  24475. };
  24476. VirtualJoystick.prototype.releaseCanvas = function () {
  24477. if (VirtualJoystick.vjCanvas) {
  24478. document.body.removeChild(VirtualJoystick.vjCanvas);
  24479. VirtualJoystick.vjCanvas = null;
  24480. }
  24481. };
  24482. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24483. VirtualJoystick._globalJoystickIndex = 0;
  24484. return VirtualJoystick;
  24485. })();
  24486. BABYLON.VirtualJoystick = VirtualJoystick;
  24487. })(BABYLON || (BABYLON = {}));
  24488. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24489. var __extends = this.__extends || function (d, b) {
  24490. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24491. function __() { this.constructor = d; }
  24492. __.prototype = b.prototype;
  24493. d.prototype = new __();
  24494. };
  24495. var BABYLON;
  24496. (function (BABYLON) {
  24497. // We're mainly based on the logic defined into the FreeCamera code
  24498. var VirtualJoysticksCamera = (function (_super) {
  24499. __extends(VirtualJoysticksCamera, _super);
  24500. function VirtualJoysticksCamera(name, position, scene) {
  24501. _super.call(this, name, position, scene);
  24502. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24503. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  24504. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  24505. this._leftjoystick.setJoystickSensibility(0.15);
  24506. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24507. this._rightjoystick.setAxisForUpDown(0 /* X */);
  24508. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  24509. this._rightjoystick.reverseUpDown = true;
  24510. this._rightjoystick.setJoystickSensibility(0.05);
  24511. this._rightjoystick.setJoystickColor("yellow");
  24512. }
  24513. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24514. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24515. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24516. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24517. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24518. if (!this._leftjoystick.pressed) {
  24519. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24520. }
  24521. if (!this._rightjoystick.pressed) {
  24522. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24523. }
  24524. _super.prototype._checkInputs.call(this);
  24525. };
  24526. VirtualJoysticksCamera.prototype.dispose = function () {
  24527. this._leftjoystick.releaseCanvas();
  24528. _super.prototype.dispose.call(this);
  24529. };
  24530. return VirtualJoysticksCamera;
  24531. })(BABYLON.FreeCamera);
  24532. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24533. })(BABYLON || (BABYLON = {}));
  24534. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24535. var __extends = this.__extends || function (d, b) {
  24536. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24537. function __() { this.constructor = d; }
  24538. __.prototype = b.prototype;
  24539. d.prototype = new __();
  24540. };
  24541. var BABYLON;
  24542. (function (BABYLON) {
  24543. var ShaderMaterial = (function (_super) {
  24544. __extends(ShaderMaterial, _super);
  24545. function ShaderMaterial(name, scene, shaderPath, options) {
  24546. _super.call(this, name, scene);
  24547. this._textures = new Array();
  24548. this._floats = new Array();
  24549. this._floatsArrays = {};
  24550. this._colors3 = new Array();
  24551. this._colors4 = new Array();
  24552. this._vectors2 = new Array();
  24553. this._vectors3 = new Array();
  24554. this._matrices = new Array();
  24555. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24556. this._shaderPath = shaderPath;
  24557. options.needAlphaBlending = options.needAlphaBlending || false;
  24558. options.needAlphaTesting = options.needAlphaTesting || false;
  24559. options.attributes = options.attributes || ["position", "normal", "uv"];
  24560. options.uniforms = options.uniforms || ["worldViewProjection"];
  24561. options.samplers = options.samplers || [];
  24562. this._options = options;
  24563. }
  24564. ShaderMaterial.prototype.needAlphaBlending = function () {
  24565. return this._options.needAlphaBlending;
  24566. };
  24567. ShaderMaterial.prototype.needAlphaTesting = function () {
  24568. return this._options.needAlphaTesting;
  24569. };
  24570. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24571. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24572. this._options.uniforms.push(uniformName);
  24573. }
  24574. };
  24575. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24576. if (this._options.samplers.indexOf(name) === -1) {
  24577. this._options.samplers.push(name);
  24578. }
  24579. this._textures[name] = texture;
  24580. return this;
  24581. };
  24582. ShaderMaterial.prototype.setFloat = function (name, value) {
  24583. this._checkUniform(name);
  24584. this._floats[name] = value;
  24585. return this;
  24586. };
  24587. ShaderMaterial.prototype.setFloats = function (name, value) {
  24588. this._checkUniform(name);
  24589. this._floatsArrays[name] = value;
  24590. return this;
  24591. };
  24592. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24593. this._checkUniform(name);
  24594. this._colors3[name] = value;
  24595. return this;
  24596. };
  24597. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24598. this._checkUniform(name);
  24599. this._colors4[name] = value;
  24600. return this;
  24601. };
  24602. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24603. this._checkUniform(name);
  24604. this._vectors2[name] = value;
  24605. return this;
  24606. };
  24607. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24608. this._checkUniform(name);
  24609. this._vectors3[name] = value;
  24610. return this;
  24611. };
  24612. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24613. this._checkUniform(name);
  24614. this._matrices[name] = value;
  24615. return this;
  24616. };
  24617. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24618. var scene = this.getScene();
  24619. var engine = scene.getEngine();
  24620. if (!this.checkReadyOnEveryCall) {
  24621. if (this._renderId === scene.getRenderId()) {
  24622. return true;
  24623. }
  24624. }
  24625. // Instances
  24626. var defines = [];
  24627. var fallbacks = new BABYLON.EffectFallbacks();
  24628. if (useInstances) {
  24629. defines.push("#define INSTANCES");
  24630. }
  24631. // Bones
  24632. if (mesh && mesh.useBones) {
  24633. defines.push("#define BONES");
  24634. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24635. defines.push("#define BONES4");
  24636. fallbacks.addFallback(0, "BONES4");
  24637. }
  24638. // Alpha test
  24639. if (engine.getAlphaTesting()) {
  24640. defines.push("#define ALPHATEST");
  24641. }
  24642. var previousEffect = this._effect;
  24643. var join = defines.join("\n");
  24644. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24645. if (!this._effect.isReady()) {
  24646. return false;
  24647. }
  24648. if (previousEffect !== this._effect) {
  24649. scene.resetCachedMaterial();
  24650. }
  24651. this._renderId = scene.getRenderId();
  24652. return true;
  24653. };
  24654. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24655. var scene = this.getScene();
  24656. if (this._options.uniforms.indexOf("world") !== -1) {
  24657. this._effect.setMatrix("world", world);
  24658. }
  24659. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24660. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24661. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24662. }
  24663. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24664. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24665. }
  24666. };
  24667. ShaderMaterial.prototype.bind = function (world, mesh) {
  24668. // Std values
  24669. this.bindOnlyWorldMatrix(world);
  24670. if (this.getScene().getCachedMaterial() !== this) {
  24671. if (this._options.uniforms.indexOf("view") !== -1) {
  24672. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24673. }
  24674. if (this._options.uniforms.indexOf("projection") !== -1) {
  24675. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24676. }
  24677. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24678. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24679. }
  24680. // Bones
  24681. if (mesh && mesh.useBones) {
  24682. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24683. }
  24684. for (var name in this._textures) {
  24685. this._effect.setTexture(name, this._textures[name]);
  24686. }
  24687. for (name in this._floats) {
  24688. this._effect.setFloat(name, this._floats[name]);
  24689. }
  24690. for (name in this._floatsArrays) {
  24691. this._effect.setArray(name, this._floatsArrays[name]);
  24692. }
  24693. for (name in this._colors3) {
  24694. this._effect.setColor3(name, this._colors3[name]);
  24695. }
  24696. for (name in this._colors4) {
  24697. var color = this._colors4[name];
  24698. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24699. }
  24700. for (name in this._vectors2) {
  24701. this._effect.setVector2(name, this._vectors2[name]);
  24702. }
  24703. for (name in this._vectors3) {
  24704. this._effect.setVector3(name, this._vectors3[name]);
  24705. }
  24706. for (name in this._matrices) {
  24707. this._effect.setMatrix(name, this._matrices[name]);
  24708. }
  24709. }
  24710. _super.prototype.bind.call(this, world, mesh);
  24711. };
  24712. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24713. for (var name in this._textures) {
  24714. this._textures[name].dispose();
  24715. }
  24716. this._textures = [];
  24717. _super.prototype.dispose.call(this, forceDisposeEffect);
  24718. };
  24719. return ShaderMaterial;
  24720. })(BABYLON.Material);
  24721. BABYLON.ShaderMaterial = ShaderMaterial;
  24722. })(BABYLON || (BABYLON = {}));
  24723. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24724. var BABYLON;
  24725. (function (BABYLON) {
  24726. var VertexData = (function () {
  24727. function VertexData() {
  24728. }
  24729. VertexData.prototype.set = function (data, kind) {
  24730. switch (kind) {
  24731. case BABYLON.VertexBuffer.PositionKind:
  24732. this.positions = data;
  24733. break;
  24734. case BABYLON.VertexBuffer.NormalKind:
  24735. this.normals = data;
  24736. break;
  24737. case BABYLON.VertexBuffer.UVKind:
  24738. this.uvs = data;
  24739. break;
  24740. case BABYLON.VertexBuffer.UV2Kind:
  24741. this.uv2s = data;
  24742. break;
  24743. case BABYLON.VertexBuffer.ColorKind:
  24744. this.colors = data;
  24745. break;
  24746. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24747. this.matricesIndices = data;
  24748. break;
  24749. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24750. this.matricesWeights = data;
  24751. break;
  24752. }
  24753. };
  24754. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24755. this._applyTo(mesh, updatable);
  24756. };
  24757. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24758. this._applyTo(geometry, updatable);
  24759. };
  24760. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24761. this._update(mesh);
  24762. };
  24763. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24764. this._update(geometry);
  24765. };
  24766. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24767. if (this.positions) {
  24768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24769. }
  24770. if (this.normals) {
  24771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24772. }
  24773. if (this.uvs) {
  24774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24775. }
  24776. if (this.uv2s) {
  24777. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24778. }
  24779. if (this.colors) {
  24780. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24781. }
  24782. if (this.matricesIndices) {
  24783. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24784. }
  24785. if (this.matricesWeights) {
  24786. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24787. }
  24788. if (this.indices) {
  24789. meshOrGeometry.setIndices(this.indices);
  24790. }
  24791. };
  24792. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24793. if (this.positions) {
  24794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24795. }
  24796. if (this.normals) {
  24797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24798. }
  24799. if (this.uvs) {
  24800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24801. }
  24802. if (this.uv2s) {
  24803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24804. }
  24805. if (this.colors) {
  24806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24807. }
  24808. if (this.matricesIndices) {
  24809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24810. }
  24811. if (this.matricesWeights) {
  24812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24813. }
  24814. if (this.indices) {
  24815. meshOrGeometry.setIndices(this.indices);
  24816. }
  24817. };
  24818. VertexData.prototype.transform = function (matrix) {
  24819. var transformed = BABYLON.Vector3.Zero();
  24820. if (this.positions) {
  24821. var position = BABYLON.Vector3.Zero();
  24822. for (var index = 0; index < this.positions.length; index += 3) {
  24823. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24824. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24825. this.positions[index] = transformed.x;
  24826. this.positions[index + 1] = transformed.y;
  24827. this.positions[index + 2] = transformed.z;
  24828. }
  24829. }
  24830. if (this.normals) {
  24831. var normal = BABYLON.Vector3.Zero();
  24832. for (index = 0; index < this.normals.length; index += 3) {
  24833. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24834. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24835. this.normals[index] = transformed.x;
  24836. this.normals[index + 1] = transformed.y;
  24837. this.normals[index + 2] = transformed.z;
  24838. }
  24839. }
  24840. };
  24841. VertexData.prototype.merge = function (other) {
  24842. if (other.indices) {
  24843. if (!this.indices) {
  24844. this.indices = [];
  24845. }
  24846. var offset = this.positions ? this.positions.length / 3 : 0;
  24847. for (var index = 0; index < other.indices.length; index++) {
  24848. this.indices.push(other.indices[index] + offset);
  24849. }
  24850. }
  24851. if (other.positions) {
  24852. if (!this.positions) {
  24853. this.positions = [];
  24854. }
  24855. for (index = 0; index < other.positions.length; index++) {
  24856. this.positions.push(other.positions[index]);
  24857. }
  24858. }
  24859. if (other.normals) {
  24860. if (!this.normals) {
  24861. this.normals = [];
  24862. }
  24863. for (index = 0; index < other.normals.length; index++) {
  24864. this.normals.push(other.normals[index]);
  24865. }
  24866. }
  24867. if (other.uvs) {
  24868. if (!this.uvs) {
  24869. this.uvs = [];
  24870. }
  24871. for (index = 0; index < other.uvs.length; index++) {
  24872. this.uvs.push(other.uvs[index]);
  24873. }
  24874. }
  24875. if (other.uv2s) {
  24876. if (!this.uv2s) {
  24877. this.uv2s = [];
  24878. }
  24879. for (index = 0; index < other.uv2s.length; index++) {
  24880. this.uv2s.push(other.uv2s[index]);
  24881. }
  24882. }
  24883. if (other.matricesIndices) {
  24884. if (!this.matricesIndices) {
  24885. this.matricesIndices = [];
  24886. }
  24887. for (index = 0; index < other.matricesIndices.length; index++) {
  24888. this.matricesIndices.push(other.matricesIndices[index]);
  24889. }
  24890. }
  24891. if (other.matricesWeights) {
  24892. if (!this.matricesWeights) {
  24893. this.matricesWeights = [];
  24894. }
  24895. for (index = 0; index < other.matricesWeights.length; index++) {
  24896. this.matricesWeights.push(other.matricesWeights[index]);
  24897. }
  24898. }
  24899. if (other.colors) {
  24900. if (!this.colors) {
  24901. this.colors = [];
  24902. }
  24903. for (index = 0; index < other.colors.length; index++) {
  24904. this.colors.push(other.colors[index]);
  24905. }
  24906. }
  24907. };
  24908. // Statics
  24909. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24910. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24911. };
  24912. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24913. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24914. };
  24915. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24916. var result = new VertexData();
  24917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24918. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24919. }
  24920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24921. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24922. }
  24923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24924. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24925. }
  24926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24927. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24928. }
  24929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24930. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24931. }
  24932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24933. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24934. }
  24935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24936. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24937. }
  24938. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24939. return result;
  24940. };
  24941. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24942. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24943. closeArray = closeArray || false;
  24944. closePath = closePath || false;
  24945. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24946. offset = offset || defaultOffset;
  24947. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24948. var positions = [];
  24949. var indices = [];
  24950. var normals = [];
  24951. var uvs = [];
  24952. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24953. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24954. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24955. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24956. var minlg; // minimal length among all paths from pathArray
  24957. var lg = []; // array of path lengths : nb of vertex per path
  24958. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24959. var p; // path iterator
  24960. var i; // point iterator
  24961. var j; // point iterator
  24962. // if single path in pathArray
  24963. if (pathArray.length < 2) {
  24964. var ar1 = [];
  24965. var ar2 = [];
  24966. for (i = 0; i < pathArray[0].length - offset; i++) {
  24967. ar1.push(pathArray[0][i]);
  24968. ar2.push(pathArray[0][i + offset]);
  24969. }
  24970. pathArray = [ar1, ar2];
  24971. }
  24972. // positions and horizontal distances (u)
  24973. var idc = 0;
  24974. minlg = pathArray[0].length;
  24975. for (p = 0; p < pathArray.length; p++) {
  24976. uTotalDistance[p] = 0;
  24977. us[p] = [0];
  24978. var path = pathArray[p];
  24979. var l = path.length;
  24980. minlg = (minlg < l) ? minlg : l;
  24981. lg[p] = l;
  24982. idx[p] = idc;
  24983. j = 0;
  24984. while (j < l) {
  24985. positions.push(path[j].x, path[j].y, path[j].z);
  24986. if (j > 0) {
  24987. var vectlg = path[j].subtract(path[j - 1]).length();
  24988. var dist = vectlg + uTotalDistance[p];
  24989. us[p].push(dist);
  24990. uTotalDistance[p] = dist;
  24991. }
  24992. j++;
  24993. }
  24994. if (closePath) {
  24995. vectlg = path[0].subtract(path[j - 1]).length();
  24996. dist = vectlg + uTotalDistance[p];
  24997. uTotalDistance[p] = dist;
  24998. }
  24999. idc += l;
  25000. }
  25001. for (i = 0; i < minlg; i++) {
  25002. vTotalDistance[i] = 0;
  25003. vs[i] = [0];
  25004. var path1;
  25005. var path2;
  25006. for (p = 0; p < pathArray.length - 1; p++) {
  25007. path1 = pathArray[p];
  25008. path2 = pathArray[p + 1];
  25009. vectlg = path2[i].subtract(path1[i]).length();
  25010. dist = vectlg + vTotalDistance[i];
  25011. vs[i].push(dist);
  25012. vTotalDistance[i] = dist;
  25013. }
  25014. if (closeArray) {
  25015. path1 = pathArray[p];
  25016. path2 = pathArray[0];
  25017. vectlg = path2[i].subtract(path1[i]).length();
  25018. dist = vectlg + vTotalDistance[i];
  25019. vTotalDistance[i] = dist;
  25020. }
  25021. }
  25022. // uvs
  25023. var u;
  25024. var v;
  25025. for (p = 0; p < pathArray.length; p++) {
  25026. for (i = 0; i < minlg; i++) {
  25027. u = us[p][i] / uTotalDistance[p];
  25028. v = vs[i][p] / vTotalDistance[i];
  25029. uvs.push(u, v);
  25030. }
  25031. }
  25032. // indices
  25033. p = 0; // path index
  25034. var pi = 0; // positions array index
  25035. var l1 = lg[p] - 1; // path1 length
  25036. var l2 = lg[p + 1] - 1; // path2 length
  25037. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25038. var shft = idx[1] - idx[0]; // shift
  25039. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25040. var t1; // two consecutive triangles, so 4 points : point1
  25041. var t2; // point2
  25042. var t3; // point3
  25043. var t4; // point4
  25044. while (pi <= min && p < path1nb) {
  25045. // 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
  25046. t1 = pi;
  25047. t2 = pi + shft;
  25048. t3 = pi + 1;
  25049. t4 = pi + shft + 1;
  25050. indices.push(pi, pi + shft, pi + 1);
  25051. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25052. pi += 1;
  25053. if (pi === min) {
  25054. if (closePath) {
  25055. indices.push(pi, pi + shft, idx[p]);
  25056. indices.push(idx[p] + shft, idx[p], pi + shft);
  25057. t3 = idx[p];
  25058. t4 = idx[p] + shft;
  25059. }
  25060. p++;
  25061. if (p === lg.length - 1) {
  25062. shft = idx[0] - idx[p];
  25063. l1 = lg[p] - 1;
  25064. l2 = lg[0] - 1;
  25065. }
  25066. else {
  25067. shft = idx[p + 1] - idx[p];
  25068. l1 = lg[p] - 1;
  25069. l2 = lg[p + 1] - 1;
  25070. }
  25071. pi = idx[p];
  25072. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25073. }
  25074. }
  25075. // normals
  25076. VertexData.ComputeNormals(positions, indices, normals);
  25077. // sides
  25078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25079. // Result
  25080. var vertexData = new VertexData();
  25081. vertexData.indices = indices;
  25082. vertexData.positions = positions;
  25083. vertexData.normals = normals;
  25084. vertexData.uvs = uvs;
  25085. return vertexData;
  25086. };
  25087. VertexData.CreateBox = function (size, sideOrientation) {
  25088. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25089. var normalsSource = [
  25090. new BABYLON.Vector3(0, 0, 1),
  25091. new BABYLON.Vector3(0, 0, -1),
  25092. new BABYLON.Vector3(1, 0, 0),
  25093. new BABYLON.Vector3(-1, 0, 0),
  25094. new BABYLON.Vector3(0, 1, 0),
  25095. new BABYLON.Vector3(0, -1, 0)
  25096. ];
  25097. var indices = [];
  25098. var positions = [];
  25099. var normals = [];
  25100. var uvs = [];
  25101. size = size || 1;
  25102. for (var index = 0; index < normalsSource.length; index++) {
  25103. var normal = normalsSource[index];
  25104. // Get two vectors perpendicular to the face normal and to each other.
  25105. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25106. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25107. // Six indices (two triangles) per face.
  25108. var verticesLength = positions.length / 3;
  25109. indices.push(verticesLength);
  25110. indices.push(verticesLength + 1);
  25111. indices.push(verticesLength + 2);
  25112. indices.push(verticesLength);
  25113. indices.push(verticesLength + 2);
  25114. indices.push(verticesLength + 3);
  25115. // Four vertices per face.
  25116. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25117. positions.push(vertex.x, vertex.y, vertex.z);
  25118. normals.push(normal.x, normal.y, normal.z);
  25119. uvs.push(1.0, 1.0);
  25120. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25121. positions.push(vertex.x, vertex.y, vertex.z);
  25122. normals.push(normal.x, normal.y, normal.z);
  25123. uvs.push(0.0, 1.0);
  25124. vertex = normal.add(side1).add(side2).scale(size / 2);
  25125. positions.push(vertex.x, vertex.y, vertex.z);
  25126. normals.push(normal.x, normal.y, normal.z);
  25127. uvs.push(0.0, 0.0);
  25128. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25129. positions.push(vertex.x, vertex.y, vertex.z);
  25130. normals.push(normal.x, normal.y, normal.z);
  25131. uvs.push(1.0, 0.0);
  25132. }
  25133. // sides
  25134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25135. // Result
  25136. var vertexData = new VertexData();
  25137. vertexData.indices = indices;
  25138. vertexData.positions = positions;
  25139. vertexData.normals = normals;
  25140. vertexData.uvs = uvs;
  25141. return vertexData;
  25142. };
  25143. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25144. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25145. segments = segments || 32;
  25146. diameter = diameter || 1;
  25147. var radius = diameter / 2;
  25148. var totalZRotationSteps = 2 + segments;
  25149. var totalYRotationSteps = 2 * totalZRotationSteps;
  25150. var indices = [];
  25151. var positions = [];
  25152. var normals = [];
  25153. var uvs = [];
  25154. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25155. var normalizedZ = zRotationStep / totalZRotationSteps;
  25156. var angleZ = (normalizedZ * Math.PI);
  25157. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25158. var normalizedY = yRotationStep / totalYRotationSteps;
  25159. var angleY = normalizedY * Math.PI * 2;
  25160. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25161. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25162. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25163. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25164. var vertex = complete.scale(radius);
  25165. var normal = BABYLON.Vector3.Normalize(vertex);
  25166. positions.push(vertex.x, vertex.y, vertex.z);
  25167. normals.push(normal.x, normal.y, normal.z);
  25168. uvs.push(normalizedZ, normalizedY);
  25169. }
  25170. if (zRotationStep > 0) {
  25171. var verticesCount = positions.length / 3;
  25172. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25173. indices.push((firstIndex));
  25174. indices.push((firstIndex + 1));
  25175. indices.push(firstIndex + totalYRotationSteps + 1);
  25176. indices.push((firstIndex + totalYRotationSteps + 1));
  25177. indices.push((firstIndex + 1));
  25178. indices.push((firstIndex + totalYRotationSteps + 2));
  25179. }
  25180. }
  25181. }
  25182. // Sides
  25183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25184. // Result
  25185. var vertexData = new VertexData();
  25186. vertexData.indices = indices;
  25187. vertexData.positions = positions;
  25188. vertexData.normals = normals;
  25189. vertexData.uvs = uvs;
  25190. return vertexData;
  25191. };
  25192. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25193. if (subdivisions === void 0) { subdivisions = 1; }
  25194. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25195. var radiusTop = diameterTop / 2;
  25196. var radiusBottom = diameterBottom / 2;
  25197. var indices = [];
  25198. var positions = [];
  25199. var normals = [];
  25200. var uvs = [];
  25201. height = height || 1;
  25202. diameterTop = diameterTop || 0.5;
  25203. diameterBottom = diameterBottom || 1;
  25204. tessellation = tessellation || 16;
  25205. subdivisions = subdivisions || 1;
  25206. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25207. var getCircleVector = function (i) {
  25208. var angle = (i * 2.0 * Math.PI / tessellation);
  25209. var dx = Math.cos(angle);
  25210. var dz = Math.sin(angle);
  25211. return new BABYLON.Vector3(dx, 0, dz);
  25212. };
  25213. var createCylinderCap = function (isTop) {
  25214. var radius = isTop ? radiusTop : radiusBottom;
  25215. if (radius === 0) {
  25216. return;
  25217. }
  25218. var vbase = positions.length / 3;
  25219. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25220. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25221. if (!isTop) {
  25222. offset.scaleInPlace(-1);
  25223. textureScale.x = -textureScale.x;
  25224. }
  25225. for (var i = 0; i < tessellation; i++) {
  25226. var circleVector = getCircleVector(i);
  25227. var position = circleVector.scale(radius).add(offset);
  25228. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25229. positions.push(position.x, position.y, position.z);
  25230. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25231. }
  25232. for (i = 0; i < tessellation - 2; i++) {
  25233. if (!isTop) {
  25234. indices.push(vbase);
  25235. indices.push(vbase + (i + 2) % tessellation);
  25236. indices.push(vbase + (i + 1) % tessellation);
  25237. }
  25238. else {
  25239. indices.push(vbase);
  25240. indices.push(vbase + (i + 1) % tessellation);
  25241. indices.push(vbase + (i + 2) % tessellation);
  25242. }
  25243. }
  25244. };
  25245. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25246. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25247. var stride = tessellation + 1;
  25248. for (var i = 0; i <= tessellation; i++) {
  25249. var circleVector = getCircleVector(i);
  25250. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25251. var position, radius = radiusBottom;
  25252. for (var s = 0; s <= subdivisions; s++) {
  25253. // Update variables
  25254. position = circleVector.scale(radius);
  25255. position.addInPlace(base.add(offset.scale(s)));
  25256. textureCoordinate.y += 1 / subdivisions;
  25257. radius += (radiusTop - radiusBottom) / subdivisions;
  25258. // Push in arrays
  25259. positions.push(position.x, position.y, position.z);
  25260. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25261. }
  25262. }
  25263. subdivisions += 1;
  25264. for (s = 0; s < subdivisions - 1; s++) {
  25265. for (i = 0; i <= tessellation; i++) {
  25266. indices.push(i * subdivisions + s);
  25267. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25268. indices.push(i * subdivisions + (s + 1));
  25269. indices.push(i * subdivisions + (s + 1));
  25270. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25271. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25272. }
  25273. }
  25274. // Create flat triangle fan caps to seal the top and bottom.
  25275. createCylinderCap(true);
  25276. createCylinderCap(false);
  25277. // Normals
  25278. VertexData.ComputeNormals(positions, indices, normals);
  25279. // Sides
  25280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25281. // Result
  25282. var vertexData = new VertexData();
  25283. vertexData.indices = indices;
  25284. vertexData.positions = positions;
  25285. vertexData.normals = normals;
  25286. vertexData.uvs = uvs;
  25287. return vertexData;
  25288. };
  25289. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25290. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25291. var indices = [];
  25292. var positions = [];
  25293. var normals = [];
  25294. var uvs = [];
  25295. diameter = diameter || 1;
  25296. thickness = thickness || 0.5;
  25297. tessellation = tessellation || 16;
  25298. var stride = tessellation + 1;
  25299. for (var i = 0; i <= tessellation; i++) {
  25300. var u = i / tessellation;
  25301. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25302. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25303. for (var j = 0; j <= tessellation; j++) {
  25304. var v = 1 - j / tessellation;
  25305. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25306. var dx = Math.cos(innerAngle);
  25307. var dy = Math.sin(innerAngle);
  25308. // Create a vertex.
  25309. var normal = new BABYLON.Vector3(dx, dy, 0);
  25310. var position = normal.scale(thickness / 2);
  25311. var textureCoordinate = new BABYLON.Vector2(u, v);
  25312. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25313. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25314. positions.push(position.x, position.y, position.z);
  25315. normals.push(normal.x, normal.y, normal.z);
  25316. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25317. // And create indices for two triangles.
  25318. var nextI = (i + 1) % stride;
  25319. var nextJ = (j + 1) % stride;
  25320. indices.push(i * stride + j);
  25321. indices.push(i * stride + nextJ);
  25322. indices.push(nextI * stride + j);
  25323. indices.push(i * stride + nextJ);
  25324. indices.push(nextI * stride + nextJ);
  25325. indices.push(nextI * stride + j);
  25326. }
  25327. }
  25328. // Sides
  25329. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25330. // Result
  25331. var vertexData = new VertexData();
  25332. vertexData.indices = indices;
  25333. vertexData.positions = positions;
  25334. vertexData.normals = normals;
  25335. vertexData.uvs = uvs;
  25336. return vertexData;
  25337. };
  25338. VertexData.CreateLines = function (points) {
  25339. var indices = [];
  25340. var positions = [];
  25341. for (var index = 0; index < points.length; index++) {
  25342. positions.push(points[index].x, points[index].y, points[index].z);
  25343. if (index > 0) {
  25344. indices.push(index - 1);
  25345. indices.push(index);
  25346. }
  25347. }
  25348. // Result
  25349. var vertexData = new VertexData();
  25350. vertexData.indices = indices;
  25351. vertexData.positions = positions;
  25352. return vertexData;
  25353. };
  25354. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25355. dashSize = dashSize || 3;
  25356. gapSize = gapSize || 1;
  25357. dashNb = dashNb || 200;
  25358. var positions = new Array();
  25359. var indices = new Array();
  25360. var curvect = BABYLON.Vector3.Zero();
  25361. var lg = 0;
  25362. var nb = 0;
  25363. var shft = 0;
  25364. var dashshft = 0;
  25365. var curshft = 0;
  25366. var idx = 0;
  25367. var i = 0;
  25368. for (i = 0; i < points.length - 1; i++) {
  25369. points[i + 1].subtractToRef(points[i], curvect);
  25370. lg += curvect.length();
  25371. }
  25372. shft = lg / dashNb;
  25373. dashshft = dashSize * shft / (dashSize + gapSize);
  25374. for (i = 0; i < points.length - 1; i++) {
  25375. points[i + 1].subtractToRef(points[i], curvect);
  25376. curvect.normalize();
  25377. nb = Math.floor(curvect.length() / shft);
  25378. for (var j = 0; j < nb; j++) {
  25379. curshft = shft * j;
  25380. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25381. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25382. indices.push(idx, idx + 1);
  25383. idx += 2;
  25384. }
  25385. }
  25386. // Result
  25387. var vertexData = new VertexData();
  25388. vertexData.positions = positions;
  25389. vertexData.indices = indices;
  25390. return vertexData;
  25391. };
  25392. VertexData.CreateGround = function (width, height, subdivisions) {
  25393. var indices = [];
  25394. var positions = [];
  25395. var normals = [];
  25396. var uvs = [];
  25397. var row, col;
  25398. width = width || 1;
  25399. height = height || 1;
  25400. subdivisions = subdivisions || 1;
  25401. for (row = 0; row <= subdivisions; row++) {
  25402. for (col = 0; col <= subdivisions; col++) {
  25403. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25404. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25405. positions.push(position.x, position.y, position.z);
  25406. normals.push(normal.x, normal.y, normal.z);
  25407. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25408. }
  25409. }
  25410. for (row = 0; row < subdivisions; row++) {
  25411. for (col = 0; col < subdivisions; col++) {
  25412. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25413. indices.push(col + 1 + row * (subdivisions + 1));
  25414. indices.push(col + row * (subdivisions + 1));
  25415. indices.push(col + (row + 1) * (subdivisions + 1));
  25416. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25417. indices.push(col + row * (subdivisions + 1));
  25418. }
  25419. }
  25420. // Result
  25421. var vertexData = new VertexData();
  25422. vertexData.indices = indices;
  25423. vertexData.positions = positions;
  25424. vertexData.normals = normals;
  25425. vertexData.uvs = uvs;
  25426. return vertexData;
  25427. };
  25428. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25429. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25430. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25431. var indices = [];
  25432. var positions = [];
  25433. var normals = [];
  25434. var uvs = [];
  25435. var row, col, tileRow, tileCol;
  25436. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25437. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25438. precision.w = (precision.w < 1) ? 1 : precision.w;
  25439. precision.h = (precision.h < 1) ? 1 : precision.h;
  25440. var tileSize = {
  25441. 'w': (xmax - xmin) / subdivisions.w,
  25442. 'h': (zmax - zmin) / subdivisions.h
  25443. };
  25444. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25445. // Indices
  25446. var base = positions.length / 3;
  25447. var rowLength = precision.w + 1;
  25448. for (row = 0; row < precision.h; row++) {
  25449. for (col = 0; col < precision.w; col++) {
  25450. var square = [
  25451. base + col + row * rowLength,
  25452. base + (col + 1) + row * rowLength,
  25453. base + (col + 1) + (row + 1) * rowLength,
  25454. base + col + (row + 1) * rowLength
  25455. ];
  25456. indices.push(square[1]);
  25457. indices.push(square[2]);
  25458. indices.push(square[3]);
  25459. indices.push(square[0]);
  25460. indices.push(square[1]);
  25461. indices.push(square[3]);
  25462. }
  25463. }
  25464. // Position, normals and uvs
  25465. var position = BABYLON.Vector3.Zero();
  25466. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25467. for (row = 0; row <= precision.h; row++) {
  25468. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25469. for (col = 0; col <= precision.w; col++) {
  25470. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25471. position.y = 0;
  25472. positions.push(position.x, position.y, position.z);
  25473. normals.push(normal.x, normal.y, normal.z);
  25474. uvs.push(col / precision.w, row / precision.h);
  25475. }
  25476. }
  25477. }
  25478. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25479. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25480. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25481. }
  25482. }
  25483. // Result
  25484. var vertexData = new VertexData();
  25485. vertexData.indices = indices;
  25486. vertexData.positions = positions;
  25487. vertexData.normals = normals;
  25488. vertexData.uvs = uvs;
  25489. return vertexData;
  25490. };
  25491. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25492. var indices = [];
  25493. var positions = [];
  25494. var normals = [];
  25495. var uvs = [];
  25496. var row, col;
  25497. for (row = 0; row <= subdivisions; row++) {
  25498. for (col = 0; col <= subdivisions; col++) {
  25499. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25500. // Compute height
  25501. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25502. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25503. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25504. var r = buffer[pos] / 255.0;
  25505. var g = buffer[pos + 1] / 255.0;
  25506. var b = buffer[pos + 2] / 255.0;
  25507. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25508. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25509. // Add vertex
  25510. positions.push(position.x, position.y, position.z);
  25511. normals.push(0, 0, 0);
  25512. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25513. }
  25514. }
  25515. for (row = 0; row < subdivisions; row++) {
  25516. for (col = 0; col < subdivisions; col++) {
  25517. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25518. indices.push(col + 1 + row * (subdivisions + 1));
  25519. indices.push(col + row * (subdivisions + 1));
  25520. indices.push(col + (row + 1) * (subdivisions + 1));
  25521. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25522. indices.push(col + row * (subdivisions + 1));
  25523. }
  25524. }
  25525. // Normals
  25526. VertexData.ComputeNormals(positions, indices, normals);
  25527. // Result
  25528. var vertexData = new VertexData();
  25529. vertexData.indices = indices;
  25530. vertexData.positions = positions;
  25531. vertexData.normals = normals;
  25532. vertexData.uvs = uvs;
  25533. return vertexData;
  25534. };
  25535. VertexData.CreatePlane = function (size, sideOrientation) {
  25536. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25537. var indices = [];
  25538. var positions = [];
  25539. var normals = [];
  25540. var uvs = [];
  25541. size = size || 1;
  25542. // Vertices
  25543. var halfSize = size / 2.0;
  25544. positions.push(-halfSize, -halfSize, 0);
  25545. normals.push(0, 0, -1.0);
  25546. uvs.push(0.0, 0.0);
  25547. positions.push(halfSize, -halfSize, 0);
  25548. normals.push(0, 0, -1.0);
  25549. uvs.push(1.0, 0.0);
  25550. positions.push(halfSize, halfSize, 0);
  25551. normals.push(0, 0, -1.0);
  25552. uvs.push(1.0, 1.0);
  25553. positions.push(-halfSize, halfSize, 0);
  25554. normals.push(0, 0, -1.0);
  25555. uvs.push(0.0, 1.0);
  25556. // Indices
  25557. indices.push(0);
  25558. indices.push(1);
  25559. indices.push(2);
  25560. indices.push(0);
  25561. indices.push(2);
  25562. indices.push(3);
  25563. // Sides
  25564. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25565. // Result
  25566. var vertexData = new VertexData();
  25567. vertexData.indices = indices;
  25568. vertexData.positions = positions;
  25569. vertexData.normals = normals;
  25570. vertexData.uvs = uvs;
  25571. return vertexData;
  25572. };
  25573. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25574. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25575. var positions = [];
  25576. var indices = [];
  25577. var normals = [];
  25578. var uvs = [];
  25579. // positions and uvs
  25580. positions.push(0, 0, 0); // disc center first
  25581. uvs.push(0.5, 0.5);
  25582. var step = Math.PI * 2 / tessellation;
  25583. for (var a = 0; a < Math.PI * 2; a += step) {
  25584. var x = Math.cos(a);
  25585. var y = Math.sin(a);
  25586. var u = (x + 1) / 2;
  25587. var v = (1 - y) / 2;
  25588. positions.push(radius * x, radius * y, 0);
  25589. uvs.push(u, v);
  25590. }
  25591. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25592. uvs.push(uvs[2], uvs[3]);
  25593. //indices
  25594. var vertexNb = positions.length / 3;
  25595. for (var i = 1; i < vertexNb - 1; i++) {
  25596. indices.push(i + 1, 0, i);
  25597. }
  25598. // result
  25599. VertexData.ComputeNormals(positions, indices, normals);
  25600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25601. var vertexData = new VertexData();
  25602. vertexData.indices = indices;
  25603. vertexData.positions = positions;
  25604. vertexData.normals = normals;
  25605. vertexData.uvs = uvs;
  25606. return vertexData;
  25607. };
  25608. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25609. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25610. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25611. var indices = [];
  25612. var positions = [];
  25613. var normals = [];
  25614. var uvs = [];
  25615. radius = radius || 2;
  25616. tube = tube || 0.5;
  25617. radialSegments = radialSegments || 32;
  25618. tubularSegments = tubularSegments || 32;
  25619. p = p || 2;
  25620. q = q || 3;
  25621. // Helper
  25622. var getPos = function (angle) {
  25623. var cu = Math.cos(angle);
  25624. var su = Math.sin(angle);
  25625. var quOverP = q / p * angle;
  25626. var cs = Math.cos(quOverP);
  25627. var tx = radius * (2 + cs) * 0.5 * cu;
  25628. var ty = radius * (2 + cs) * su * 0.5;
  25629. var tz = radius * Math.sin(quOverP) * 0.5;
  25630. return new BABYLON.Vector3(tx, ty, tz);
  25631. };
  25632. for (var i = 0; i <= radialSegments; i++) {
  25633. var modI = i % radialSegments;
  25634. var u = modI / radialSegments * 2 * p * Math.PI;
  25635. var p1 = getPos(u);
  25636. var p2 = getPos(u + 0.01);
  25637. var tang = p2.subtract(p1);
  25638. var n = p2.add(p1);
  25639. var bitan = BABYLON.Vector3.Cross(tang, n);
  25640. n = BABYLON.Vector3.Cross(bitan, tang);
  25641. bitan.normalize();
  25642. n.normalize();
  25643. for (var j = 0; j < tubularSegments; j++) {
  25644. var modJ = j % tubularSegments;
  25645. var v = modJ / tubularSegments * 2 * Math.PI;
  25646. var cx = -tube * Math.cos(v);
  25647. var cy = tube * Math.sin(v);
  25648. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25649. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25650. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25651. uvs.push(i / radialSegments);
  25652. uvs.push(j / tubularSegments);
  25653. }
  25654. }
  25655. for (i = 0; i < radialSegments; i++) {
  25656. for (j = 0; j < tubularSegments; j++) {
  25657. var jNext = (j + 1) % tubularSegments;
  25658. var a = i * tubularSegments + j;
  25659. var b = (i + 1) * tubularSegments + j;
  25660. var c = (i + 1) * tubularSegments + jNext;
  25661. var d = i * tubularSegments + jNext;
  25662. indices.push(d);
  25663. indices.push(b);
  25664. indices.push(a);
  25665. indices.push(d);
  25666. indices.push(c);
  25667. indices.push(b);
  25668. }
  25669. }
  25670. // Normals
  25671. VertexData.ComputeNormals(positions, indices, normals);
  25672. // Sides
  25673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25674. // Result
  25675. var vertexData = new VertexData();
  25676. vertexData.indices = indices;
  25677. vertexData.positions = positions;
  25678. vertexData.normals = normals;
  25679. vertexData.uvs = uvs;
  25680. return vertexData;
  25681. };
  25682. // Tools
  25683. /**
  25684. * @param {any} - positions (number[] or Float32Array)
  25685. * @param {any} - indices (number[] or Uint16Array)
  25686. * @param {any} - normals (number[] or Float32Array)
  25687. */
  25688. VertexData.ComputeNormals = function (positions, indices, normals) {
  25689. var index = 0;
  25690. // temp Vector3
  25691. var p1 = BABYLON.Vector3.Zero();
  25692. var p2 = BABYLON.Vector3.Zero();
  25693. var p3 = BABYLON.Vector3.Zero();
  25694. var p1p2 = BABYLON.Vector3.Zero();
  25695. var p3p2 = BABYLON.Vector3.Zero();
  25696. var faceNormal = BABYLON.Vector3.Zero();
  25697. var vertexNormali1 = BABYLON.Vector3.Zero();
  25698. var vertexNormali2 = BABYLON.Vector3.Zero();
  25699. var vertexNormali3 = BABYLON.Vector3.Zero();
  25700. // indice triplet = 1 face
  25701. var nbFaces = indices.length / 3;
  25702. for (index = 0; index < nbFaces; index++) {
  25703. var i1 = indices[index * 3];
  25704. var i2 = indices[index * 3 + 1];
  25705. var i3 = indices[index * 3 + 2];
  25706. // setting the temp V3
  25707. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25708. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25709. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25710. p1.subtractToRef(p2, p1p2);
  25711. p3.subtractToRef(p2, p3p2);
  25712. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25713. faceNormal.normalize();
  25714. // All intermediate results are stored in the normals array :
  25715. // get the normals at i1, i2 and i3 indexes
  25716. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25717. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25718. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25719. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25720. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25721. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25722. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25723. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25724. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25725. // make intermediate vectors3 from normals values
  25726. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25727. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25728. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25729. // add the current face normals to these intermediate vectors3
  25730. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25731. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25732. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25733. // store back intermediate vectors3 into the normals array
  25734. normals[i1 * 3] = vertexNormali1.x;
  25735. normals[i1 * 3 + 1] = vertexNormali1.y;
  25736. normals[i1 * 3 + 2] = vertexNormali1.z;
  25737. normals[i2 * 3] = vertexNormali2.x;
  25738. normals[i2 * 3 + 1] = vertexNormali2.y;
  25739. normals[i2 * 3 + 2] = vertexNormali2.z;
  25740. normals[i3 * 3] = vertexNormali3.x;
  25741. normals[i3 * 3 + 1] = vertexNormali3.y;
  25742. normals[i3 * 3 + 2] = vertexNormali3.z;
  25743. }
  25744. for (index = 0; index < normals.length / 3; index++) {
  25745. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25746. vertexNormali1.normalize();
  25747. normals[index * 3] = vertexNormali1.x;
  25748. normals[index * 3 + 1] = vertexNormali1.y;
  25749. normals[index * 3 + 2] = vertexNormali1.z;
  25750. }
  25751. };
  25752. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25753. var li = indices.length;
  25754. var ln = normals.length;
  25755. var i;
  25756. var n;
  25757. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25758. switch (sideOrientation) {
  25759. case BABYLON.Mesh.FRONTSIDE:
  25760. break;
  25761. case BABYLON.Mesh.BACKSIDE:
  25762. var tmp;
  25763. for (i = 0; i < li; i += 3) {
  25764. tmp = indices[i];
  25765. indices[i] = indices[i + 2];
  25766. indices[i + 2] = tmp;
  25767. }
  25768. for (n = 0; n < ln; n++) {
  25769. normals[n] = -normals[n];
  25770. }
  25771. break;
  25772. case BABYLON.Mesh.DOUBLESIDE:
  25773. // positions
  25774. var lp = positions.length;
  25775. var l = lp / 3;
  25776. for (var p = 0; p < lp; p++) {
  25777. positions[lp + p] = positions[p];
  25778. }
  25779. for (i = 0; i < li; i += 3) {
  25780. indices[i + li] = indices[i + 2] + l;
  25781. indices[i + 1 + li] = indices[i + 1] + l;
  25782. indices[i + 2 + li] = indices[i] + l;
  25783. }
  25784. for (n = 0; n < ln; n++) {
  25785. normals[ln + n] = -normals[n];
  25786. }
  25787. // uvs
  25788. var lu = uvs.length;
  25789. for (var u = 0; u < lu; u++) {
  25790. uvs[u + lu] = uvs[u];
  25791. }
  25792. break;
  25793. }
  25794. };
  25795. return VertexData;
  25796. })();
  25797. BABYLON.VertexData = VertexData;
  25798. })(BABYLON || (BABYLON = {}));
  25799. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25800. var __extends = this.__extends || function (d, b) {
  25801. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25802. function __() { this.constructor = d; }
  25803. __.prototype = b.prototype;
  25804. d.prototype = new __();
  25805. };
  25806. var BABYLON;
  25807. (function (BABYLON) {
  25808. var AnaglyphFreeCamera = (function (_super) {
  25809. __extends(AnaglyphFreeCamera, _super);
  25810. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25811. _super.call(this, name, position, scene);
  25812. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25813. }
  25814. return AnaglyphFreeCamera;
  25815. })(BABYLON.FreeCamera);
  25816. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25817. var AnaglyphArcRotateCamera = (function (_super) {
  25818. __extends(AnaglyphArcRotateCamera, _super);
  25819. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25820. _super.call(this, name, alpha, beta, radius, target, scene);
  25821. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25822. }
  25823. return AnaglyphArcRotateCamera;
  25824. })(BABYLON.ArcRotateCamera);
  25825. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25826. var AnaglyphGamepadCamera = (function (_super) {
  25827. __extends(AnaglyphGamepadCamera, _super);
  25828. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  25829. _super.call(this, name, position, scene);
  25830. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25831. }
  25832. return AnaglyphGamepadCamera;
  25833. })(BABYLON.GamepadCamera);
  25834. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  25835. })(BABYLON || (BABYLON = {}));
  25836. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25837. var __extends = this.__extends || function (d, b) {
  25838. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25839. function __() { this.constructor = d; }
  25840. __.prototype = b.prototype;
  25841. d.prototype = new __();
  25842. };
  25843. var BABYLON;
  25844. (function (BABYLON) {
  25845. var AnaglyphPostProcess = (function (_super) {
  25846. __extends(AnaglyphPostProcess, _super);
  25847. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25848. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25849. }
  25850. return AnaglyphPostProcess;
  25851. })(BABYLON.PostProcess);
  25852. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25853. })(BABYLON || (BABYLON = {}));
  25854. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25855. var BABYLON;
  25856. (function (BABYLON) {
  25857. var Tags = (function () {
  25858. function Tags() {
  25859. }
  25860. Tags.EnableFor = function (obj) {
  25861. obj._tags = obj._tags || {};
  25862. obj.hasTags = function () {
  25863. return Tags.HasTags(obj);
  25864. };
  25865. obj.addTags = function (tagsString) {
  25866. return Tags.AddTagsTo(obj, tagsString);
  25867. };
  25868. obj.removeTags = function (tagsString) {
  25869. return Tags.RemoveTagsFrom(obj, tagsString);
  25870. };
  25871. obj.matchesTagsQuery = function (tagsQuery) {
  25872. return Tags.MatchesQuery(obj, tagsQuery);
  25873. };
  25874. };
  25875. Tags.DisableFor = function (obj) {
  25876. delete obj._tags;
  25877. delete obj.hasTags;
  25878. delete obj.addTags;
  25879. delete obj.removeTags;
  25880. delete obj.matchesTagsQuery;
  25881. };
  25882. Tags.HasTags = function (obj) {
  25883. if (!obj._tags) {
  25884. return false;
  25885. }
  25886. return !BABYLON.Tools.IsEmpty(obj._tags);
  25887. };
  25888. Tags.GetTags = function (obj) {
  25889. if (!obj._tags) {
  25890. return null;
  25891. }
  25892. return obj._tags;
  25893. };
  25894. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25895. // a tag cannot start with '||', '&&', and '!'
  25896. // it cannot contain whitespaces
  25897. Tags.AddTagsTo = function (obj, tagsString) {
  25898. if (!tagsString) {
  25899. return;
  25900. }
  25901. var tags = tagsString.split(" ");
  25902. for (var t in tags) {
  25903. Tags._AddTagTo(obj, tags[t]);
  25904. }
  25905. };
  25906. Tags._AddTagTo = function (obj, tag) {
  25907. tag = tag.trim();
  25908. if (tag === "" || tag === "true" || tag === "false") {
  25909. return;
  25910. }
  25911. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25912. return;
  25913. }
  25914. Tags.EnableFor(obj);
  25915. obj._tags[tag] = true;
  25916. };
  25917. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25918. if (!Tags.HasTags(obj)) {
  25919. return;
  25920. }
  25921. var tags = tagsString.split(" ");
  25922. for (var t in tags) {
  25923. Tags._RemoveTagFrom(obj, tags[t]);
  25924. }
  25925. };
  25926. Tags._RemoveTagFrom = function (obj, tag) {
  25927. delete obj._tags[tag];
  25928. };
  25929. Tags.MatchesQuery = function (obj, tagsQuery) {
  25930. if (tagsQuery === undefined) {
  25931. return true;
  25932. }
  25933. if (tagsQuery === "") {
  25934. return Tags.HasTags(obj);
  25935. }
  25936. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25937. };
  25938. return Tags;
  25939. })();
  25940. BABYLON.Tags = Tags;
  25941. })(BABYLON || (BABYLON = {}));
  25942. //# sourceMappingURL=babylon.tags.js.map
  25943. var BABYLON;
  25944. (function (BABYLON) {
  25945. var Internals;
  25946. (function (Internals) {
  25947. var AndOrNotEvaluator = (function () {
  25948. function AndOrNotEvaluator() {
  25949. }
  25950. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25951. if (!query.match(/\([^\(\)]*\)/g)) {
  25952. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25953. }
  25954. else {
  25955. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25956. // remove parenthesis
  25957. r = r.slice(1, r.length - 1);
  25958. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25959. });
  25960. }
  25961. if (query === "true") {
  25962. return true;
  25963. }
  25964. if (query === "false") {
  25965. return false;
  25966. }
  25967. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25968. };
  25969. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25970. evaluateCallback = evaluateCallback || (function (r) {
  25971. return r === "true" ? true : false;
  25972. });
  25973. var result;
  25974. var or = parenthesisContent.split("||");
  25975. for (var i in or) {
  25976. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25977. var and = ori.split("&&");
  25978. if (and.length > 1) {
  25979. for (var j = 0; j < and.length; ++j) {
  25980. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25981. if (andj !== "true" && andj !== "false") {
  25982. if (andj[0] === "!") {
  25983. result = !evaluateCallback(andj.substring(1));
  25984. }
  25985. else {
  25986. result = evaluateCallback(andj);
  25987. }
  25988. }
  25989. else {
  25990. result = andj === "true" ? true : false;
  25991. }
  25992. if (!result) {
  25993. ori = "false";
  25994. break;
  25995. }
  25996. }
  25997. }
  25998. if (result || ori === "true") {
  25999. result = true;
  26000. break;
  26001. }
  26002. // result equals false (or undefined)
  26003. if (ori !== "true" && ori !== "false") {
  26004. if (ori[0] === "!") {
  26005. result = !evaluateCallback(ori.substring(1));
  26006. }
  26007. else {
  26008. result = evaluateCallback(ori);
  26009. }
  26010. }
  26011. else {
  26012. result = ori === "true" ? true : false;
  26013. }
  26014. }
  26015. // the whole parenthesis scope is replaced by 'true' or 'false'
  26016. return result ? "true" : "false";
  26017. };
  26018. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26019. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26020. // remove whitespaces
  26021. r = r.replace(/[\s]/g, function () { return ""; });
  26022. return r.length % 2 ? "!" : "";
  26023. });
  26024. booleanString = booleanString.trim();
  26025. if (booleanString === "!true") {
  26026. booleanString = "false";
  26027. }
  26028. else if (booleanString === "!false") {
  26029. booleanString = "true";
  26030. }
  26031. return booleanString;
  26032. };
  26033. return AndOrNotEvaluator;
  26034. })();
  26035. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26036. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26037. })(BABYLON || (BABYLON = {}));
  26038. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26039. var BABYLON;
  26040. (function (BABYLON) {
  26041. var PostProcessRenderPass = (function () {
  26042. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26043. this._enabled = true;
  26044. this._refCount = 0;
  26045. this._name = name;
  26046. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26047. this.setRenderList(renderList);
  26048. this._renderTexture.onBeforeRender = beforeRender;
  26049. this._renderTexture.onAfterRender = afterRender;
  26050. this._scene = scene;
  26051. this._renderList = renderList;
  26052. }
  26053. // private
  26054. PostProcessRenderPass.prototype._incRefCount = function () {
  26055. if (this._refCount === 0) {
  26056. this._scene.customRenderTargets.push(this._renderTexture);
  26057. }
  26058. return ++this._refCount;
  26059. };
  26060. PostProcessRenderPass.prototype._decRefCount = function () {
  26061. this._refCount--;
  26062. if (this._refCount <= 0) {
  26063. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26064. }
  26065. return this._refCount;
  26066. };
  26067. PostProcessRenderPass.prototype._update = function () {
  26068. this.setRenderList(this._renderList);
  26069. };
  26070. // public
  26071. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26072. this._renderTexture.renderList = renderList;
  26073. };
  26074. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26075. return this._renderTexture;
  26076. };
  26077. return PostProcessRenderPass;
  26078. })();
  26079. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26080. })(BABYLON || (BABYLON = {}));
  26081. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26082. var BABYLON;
  26083. (function (BABYLON) {
  26084. var PostProcessRenderEffect = (function () {
  26085. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26086. this._engine = engine;
  26087. this._name = name;
  26088. this._singleInstance = singleInstance || true;
  26089. this._getPostProcess = getPostProcess;
  26090. this._cameras = [];
  26091. this._indicesForCamera = [];
  26092. this._postProcesses = {};
  26093. this._renderPasses = {};
  26094. this._renderEffectAsPasses = {};
  26095. }
  26096. PostProcessRenderEffect.prototype._update = function () {
  26097. for (var renderPassName in this._renderPasses) {
  26098. this._renderPasses[renderPassName]._update();
  26099. }
  26100. };
  26101. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26102. this._renderPasses[renderPass._name] = renderPass;
  26103. this._linkParameters();
  26104. };
  26105. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26106. delete this._renderPasses[renderPass._name];
  26107. this._linkParameters();
  26108. };
  26109. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26110. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26111. this._linkParameters();
  26112. };
  26113. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26114. for (var renderPassName in this._renderPasses) {
  26115. if (renderPassName === passName) {
  26116. return this._renderPasses[passName];
  26117. }
  26118. }
  26119. };
  26120. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26121. this._renderPasses = {};
  26122. this._linkParameters();
  26123. };
  26124. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26125. var cameraKey;
  26126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26127. for (var i = 0; i < _cam.length; i++) {
  26128. var camera = _cam[i];
  26129. var cameraName = camera.name;
  26130. if (this._singleInstance) {
  26131. cameraKey = 0;
  26132. }
  26133. else {
  26134. cameraKey = cameraName;
  26135. }
  26136. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26137. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26138. if (!this._indicesForCamera[cameraName]) {
  26139. this._indicesForCamera[cameraName] = [];
  26140. }
  26141. this._indicesForCamera[cameraName].push(index);
  26142. if (this._cameras.indexOf(camera) === -1) {
  26143. this._cameras[cameraName] = camera;
  26144. }
  26145. for (var passName in this._renderPasses) {
  26146. this._renderPasses[passName]._incRefCount();
  26147. }
  26148. }
  26149. this._linkParameters();
  26150. };
  26151. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26152. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26153. for (var i = 0; i < _cam.length; i++) {
  26154. var camera = _cam[i];
  26155. var cameraName = camera.name;
  26156. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26157. var index = this._cameras.indexOf(cameraName);
  26158. this._indicesForCamera.splice(index, 1);
  26159. this._cameras.splice(index, 1);
  26160. for (var passName in this._renderPasses) {
  26161. this._renderPasses[passName]._decRefCount();
  26162. }
  26163. }
  26164. };
  26165. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26166. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26167. for (var i = 0; i < _cam.length; i++) {
  26168. var camera = _cam[i];
  26169. var cameraName = camera.name;
  26170. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26171. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26172. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26173. }
  26174. }
  26175. for (var passName in this._renderPasses) {
  26176. this._renderPasses[passName]._incRefCount();
  26177. }
  26178. }
  26179. };
  26180. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26181. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26182. for (var i = 0; i < _cam.length; i++) {
  26183. var camera = _cam[i];
  26184. var cameraName = camera.Name;
  26185. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26186. for (var passName in this._renderPasses) {
  26187. this._renderPasses[passName]._decRefCount();
  26188. }
  26189. }
  26190. };
  26191. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26192. if (this._singleInstance) {
  26193. return this._postProcesses[0];
  26194. }
  26195. else {
  26196. return this._postProcesses[camera.name];
  26197. }
  26198. };
  26199. PostProcessRenderEffect.prototype._linkParameters = function () {
  26200. var _this = this;
  26201. for (var index in this._postProcesses) {
  26202. if (this.applyParameters) {
  26203. this.applyParameters(this._postProcesses[index]);
  26204. }
  26205. this._postProcesses[index].onBeforeRender = function (effect) {
  26206. _this._linkTextures(effect);
  26207. };
  26208. }
  26209. };
  26210. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26211. for (var renderPassName in this._renderPasses) {
  26212. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26213. }
  26214. for (var renderEffectName in this._renderEffectAsPasses) {
  26215. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26216. }
  26217. };
  26218. return PostProcessRenderEffect;
  26219. })();
  26220. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26221. })(BABYLON || (BABYLON = {}));
  26222. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26223. var BABYLON;
  26224. (function (BABYLON) {
  26225. var PostProcessRenderPipeline = (function () {
  26226. function PostProcessRenderPipeline(engine, name) {
  26227. this._engine = engine;
  26228. this._name = name;
  26229. this._renderEffects = {};
  26230. this._renderEffectsForIsolatedPass = {};
  26231. this._cameras = [];
  26232. }
  26233. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26234. this._renderEffects[renderEffect._name] = renderEffect;
  26235. };
  26236. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26237. var renderEffects = this._renderEffects[renderEffectName];
  26238. if (!renderEffects) {
  26239. return;
  26240. }
  26241. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26242. };
  26243. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26244. var renderEffects = this._renderEffects[renderEffectName];
  26245. if (!renderEffects) {
  26246. return;
  26247. }
  26248. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26249. };
  26250. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26251. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26252. var indicesToDelete = [];
  26253. for (var i = 0; i < _cam.length; i++) {
  26254. var camera = _cam[i];
  26255. var cameraName = camera.name;
  26256. if (this._cameras.indexOf(camera) === -1) {
  26257. this._cameras[cameraName] = camera;
  26258. }
  26259. else if (unique) {
  26260. indicesToDelete.push(i);
  26261. }
  26262. }
  26263. for (var i = 0; i < indicesToDelete.length; i++) {
  26264. cameras.splice(indicesToDelete[i], 1);
  26265. }
  26266. for (var renderEffectName in this._renderEffects) {
  26267. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26268. }
  26269. };
  26270. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26271. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26272. for (var renderEffectName in this._renderEffects) {
  26273. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26274. }
  26275. for (var i = 0; i < _cam.length; i++) {
  26276. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26277. }
  26278. };
  26279. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26280. var _this = this;
  26281. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26282. var pass = null;
  26283. for (var renderEffectName in this._renderEffects) {
  26284. pass = this._renderEffects[renderEffectName].getPass(passName);
  26285. if (pass != null) {
  26286. break;
  26287. }
  26288. }
  26289. if (pass === null) {
  26290. return;
  26291. }
  26292. for (var renderEffectName in this._renderEffects) {
  26293. this._renderEffects[renderEffectName]._disable(_cam);
  26294. }
  26295. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26296. for (var i = 0; i < _cam.length; i++) {
  26297. var camera = _cam[i];
  26298. var cameraName = camera.name;
  26299. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  26300. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  26301. });
  26302. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26303. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26304. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26305. }
  26306. };
  26307. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26308. var _this = this;
  26309. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26310. for (var i = 0; i < _cam.length; i++) {
  26311. var camera = _cam[i];
  26312. var cameraName = camera.name;
  26313. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  26314. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  26315. });
  26316. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26317. }
  26318. for (var renderEffectName in this._renderEffects) {
  26319. this._renderEffects[renderEffectName]._enable(_cam);
  26320. }
  26321. };
  26322. PostProcessRenderPipeline.prototype._update = function () {
  26323. for (var renderEffectName in this._renderEffects) {
  26324. this._renderEffects[renderEffectName]._update();
  26325. }
  26326. for (var i = 0; i < this._cameras.length; i++) {
  26327. var cameraName = this._cameras[i].name;
  26328. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26329. this._renderEffectsForIsolatedPass[cameraName]._update();
  26330. }
  26331. }
  26332. };
  26333. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26334. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26335. return PostProcessRenderPipeline;
  26336. })();
  26337. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26338. })(BABYLON || (BABYLON = {}));
  26339. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26340. var BABYLON;
  26341. (function (BABYLON) {
  26342. var PostProcessRenderPipelineManager = (function () {
  26343. function PostProcessRenderPipelineManager() {
  26344. this._renderPipelines = {};
  26345. }
  26346. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26347. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26348. };
  26349. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26350. var renderPipeline = this._renderPipelines[renderPipelineName];
  26351. if (!renderPipeline) {
  26352. return;
  26353. }
  26354. renderPipeline._attachCameras(cameras, unique);
  26355. };
  26356. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26357. var renderPipeline = this._renderPipelines[renderPipelineName];
  26358. if (!renderPipeline) {
  26359. return;
  26360. }
  26361. renderPipeline._detachCameras(cameras);
  26362. };
  26363. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26364. var renderPipeline = this._renderPipelines[renderPipelineName];
  26365. if (!renderPipeline) {
  26366. return;
  26367. }
  26368. renderPipeline._enableEffect(renderEffectName, cameras);
  26369. };
  26370. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26371. var renderPipeline = this._renderPipelines[renderPipelineName];
  26372. if (!renderPipeline) {
  26373. return;
  26374. }
  26375. renderPipeline._disableEffect(renderEffectName, cameras);
  26376. };
  26377. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26378. var renderPipeline = this._renderPipelines[renderPipelineName];
  26379. if (!renderPipeline) {
  26380. return;
  26381. }
  26382. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26383. };
  26384. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26385. var renderPipeline = this._renderPipelines[renderPipelineName];
  26386. if (!renderPipeline) {
  26387. return;
  26388. }
  26389. renderPipeline._disableDisplayOnlyPass(cameras);
  26390. };
  26391. PostProcessRenderPipelineManager.prototype.update = function () {
  26392. for (var renderPipelineName in this._renderPipelines) {
  26393. this._renderPipelines[renderPipelineName]._update();
  26394. }
  26395. };
  26396. return PostProcessRenderPipelineManager;
  26397. })();
  26398. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26399. })(BABYLON || (BABYLON = {}));
  26400. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26401. var __extends = this.__extends || function (d, b) {
  26402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26403. function __() { this.constructor = d; }
  26404. __.prototype = b.prototype;
  26405. d.prototype = new __();
  26406. };
  26407. var BABYLON;
  26408. (function (BABYLON) {
  26409. var DisplayPassPostProcess = (function (_super) {
  26410. __extends(DisplayPassPostProcess, _super);
  26411. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26412. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26413. }
  26414. return DisplayPassPostProcess;
  26415. })(BABYLON.PostProcess);
  26416. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26417. })(BABYLON || (BABYLON = {}));
  26418. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26419. var BABYLON;
  26420. (function (BABYLON) {
  26421. var BoundingBoxRenderer = (function () {
  26422. function BoundingBoxRenderer(scene) {
  26423. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26424. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26425. this.showBackLines = true;
  26426. this.renderList = new BABYLON.SmartArray(32);
  26427. this._scene = scene;
  26428. }
  26429. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26430. if (this._colorShader) {
  26431. return;
  26432. }
  26433. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26434. attributes: ["position"],
  26435. uniforms: ["worldViewProjection", "color"]
  26436. });
  26437. var engine = this._scene.getEngine();
  26438. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26439. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26440. 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]);
  26441. };
  26442. BoundingBoxRenderer.prototype.reset = function () {
  26443. this.renderList.reset();
  26444. };
  26445. BoundingBoxRenderer.prototype.render = function () {
  26446. if (this.renderList.length === 0) {
  26447. return;
  26448. }
  26449. this._prepareRessources();
  26450. if (!this._colorShader.isReady()) {
  26451. return;
  26452. }
  26453. var engine = this._scene.getEngine();
  26454. engine.setDepthWrite(false);
  26455. this._colorShader._preBind();
  26456. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26457. var boundingBox = this.renderList.data[boundingBoxIndex];
  26458. var min = boundingBox.minimum;
  26459. var max = boundingBox.maximum;
  26460. var diff = max.subtract(min);
  26461. var median = min.add(diff.scale(0.5));
  26462. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  26463. // VBOs
  26464. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26465. if (this.showBackLines) {
  26466. // Back
  26467. engine.setDepthFunctionToGreaterOrEqual();
  26468. this._scene.resetCachedMaterial();
  26469. this._colorShader.setColor4("color", this.backColor.toColor4());
  26470. this._colorShader.bind(worldMatrix);
  26471. // Draw order
  26472. engine.draw(false, 0, 24);
  26473. }
  26474. // Front
  26475. engine.setDepthFunctionToLess();
  26476. this._scene.resetCachedMaterial();
  26477. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26478. this._colorShader.bind(worldMatrix);
  26479. // Draw order
  26480. engine.draw(false, 0, 24);
  26481. }
  26482. this._colorShader.unbind();
  26483. engine.setDepthFunctionToLessOrEqual();
  26484. engine.setDepthWrite(true);
  26485. };
  26486. BoundingBoxRenderer.prototype.dispose = function () {
  26487. if (!this._colorShader) {
  26488. return;
  26489. }
  26490. this._colorShader.dispose();
  26491. this._vb.dispose();
  26492. this._scene.getEngine()._releaseBuffer(this._ib);
  26493. };
  26494. return BoundingBoxRenderer;
  26495. })();
  26496. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26497. })(BABYLON || (BABYLON = {}));
  26498. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26499. var __extends = this.__extends || function (d, b) {
  26500. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26501. function __() { this.constructor = d; }
  26502. __.prototype = b.prototype;
  26503. d.prototype = new __();
  26504. };
  26505. var BABYLON;
  26506. (function (BABYLON) {
  26507. var Condition = (function () {
  26508. function Condition(actionManager) {
  26509. this._actionManager = actionManager;
  26510. }
  26511. Condition.prototype.isValid = function () {
  26512. return true;
  26513. };
  26514. Condition.prototype._getProperty = function (propertyPath) {
  26515. return this._actionManager._getProperty(propertyPath);
  26516. };
  26517. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26518. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26519. };
  26520. return Condition;
  26521. })();
  26522. BABYLON.Condition = Condition;
  26523. var ValueCondition = (function (_super) {
  26524. __extends(ValueCondition, _super);
  26525. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26526. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26527. _super.call(this, actionManager);
  26528. this.propertyPath = propertyPath;
  26529. this.value = value;
  26530. this.operator = operator;
  26531. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26532. this._property = this._getProperty(this.propertyPath);
  26533. }
  26534. Object.defineProperty(ValueCondition, "IsEqual", {
  26535. get: function () {
  26536. return ValueCondition._IsEqual;
  26537. },
  26538. enumerable: true,
  26539. configurable: true
  26540. });
  26541. Object.defineProperty(ValueCondition, "IsDifferent", {
  26542. get: function () {
  26543. return ValueCondition._IsDifferent;
  26544. },
  26545. enumerable: true,
  26546. configurable: true
  26547. });
  26548. Object.defineProperty(ValueCondition, "IsGreater", {
  26549. get: function () {
  26550. return ValueCondition._IsGreater;
  26551. },
  26552. enumerable: true,
  26553. configurable: true
  26554. });
  26555. Object.defineProperty(ValueCondition, "IsLesser", {
  26556. get: function () {
  26557. return ValueCondition._IsLesser;
  26558. },
  26559. enumerable: true,
  26560. configurable: true
  26561. });
  26562. // Methods
  26563. ValueCondition.prototype.isValid = function () {
  26564. switch (this.operator) {
  26565. case ValueCondition.IsGreater:
  26566. return this._target[this._property] > this.value;
  26567. case ValueCondition.IsLesser:
  26568. return this._target[this._property] < this.value;
  26569. case ValueCondition.IsEqual:
  26570. case ValueCondition.IsDifferent:
  26571. var check;
  26572. if (this.value.equals) {
  26573. check = this.value.equals(this._target[this._property]);
  26574. }
  26575. else {
  26576. check = this.value === this._target[this._property];
  26577. }
  26578. return this.operator === ValueCondition.IsEqual ? check : !check;
  26579. }
  26580. return false;
  26581. };
  26582. // Statics
  26583. ValueCondition._IsEqual = 0;
  26584. ValueCondition._IsDifferent = 1;
  26585. ValueCondition._IsGreater = 2;
  26586. ValueCondition._IsLesser = 3;
  26587. return ValueCondition;
  26588. })(Condition);
  26589. BABYLON.ValueCondition = ValueCondition;
  26590. var PredicateCondition = (function (_super) {
  26591. __extends(PredicateCondition, _super);
  26592. function PredicateCondition(actionManager, predicate) {
  26593. _super.call(this, actionManager);
  26594. this.predicate = predicate;
  26595. }
  26596. PredicateCondition.prototype.isValid = function () {
  26597. return this.predicate();
  26598. };
  26599. return PredicateCondition;
  26600. })(Condition);
  26601. BABYLON.PredicateCondition = PredicateCondition;
  26602. var StateCondition = (function (_super) {
  26603. __extends(StateCondition, _super);
  26604. function StateCondition(actionManager, target, value) {
  26605. _super.call(this, actionManager);
  26606. this.value = value;
  26607. this._target = target;
  26608. }
  26609. // Methods
  26610. StateCondition.prototype.isValid = function () {
  26611. return this._target.state === this.value;
  26612. };
  26613. return StateCondition;
  26614. })(Condition);
  26615. BABYLON.StateCondition = StateCondition;
  26616. })(BABYLON || (BABYLON = {}));
  26617. //# sourceMappingURL=babylon.condition.js.map
  26618. var BABYLON;
  26619. (function (BABYLON) {
  26620. var Action = (function () {
  26621. function Action(triggerOptions, condition) {
  26622. this.triggerOptions = triggerOptions;
  26623. if (triggerOptions.parameter) {
  26624. this.trigger = triggerOptions.trigger;
  26625. this._triggerParameter = triggerOptions.parameter;
  26626. }
  26627. else {
  26628. this.trigger = triggerOptions;
  26629. }
  26630. this._nextActiveAction = this;
  26631. this._condition = condition;
  26632. }
  26633. // Methods
  26634. Action.prototype._prepare = function () {
  26635. };
  26636. Action.prototype.getTriggerParameter = function () {
  26637. return this._triggerParameter;
  26638. };
  26639. Action.prototype._executeCurrent = function (evt) {
  26640. if (this._nextActiveAction._condition) {
  26641. var condition = this._nextActiveAction._condition;
  26642. var currentRenderId = this._actionManager.getScene().getRenderId();
  26643. // We cache the current evaluation for the current frame
  26644. if (condition._evaluationId === currentRenderId) {
  26645. if (!condition._currentResult) {
  26646. return;
  26647. }
  26648. }
  26649. else {
  26650. condition._evaluationId = currentRenderId;
  26651. if (!condition.isValid()) {
  26652. condition._currentResult = false;
  26653. return;
  26654. }
  26655. condition._currentResult = true;
  26656. }
  26657. }
  26658. this._nextActiveAction.execute(evt);
  26659. if (this._nextActiveAction._child) {
  26660. if (!this._nextActiveAction._child._actionManager) {
  26661. this._nextActiveAction._child._actionManager = this._actionManager;
  26662. }
  26663. this._nextActiveAction = this._nextActiveAction._child;
  26664. }
  26665. else {
  26666. this._nextActiveAction = this;
  26667. }
  26668. };
  26669. Action.prototype.execute = function (evt) {
  26670. };
  26671. Action.prototype.then = function (action) {
  26672. this._child = action;
  26673. action._actionManager = this._actionManager;
  26674. action._prepare();
  26675. return action;
  26676. };
  26677. Action.prototype._getProperty = function (propertyPath) {
  26678. return this._actionManager._getProperty(propertyPath);
  26679. };
  26680. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26681. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26682. };
  26683. return Action;
  26684. })();
  26685. BABYLON.Action = Action;
  26686. })(BABYLON || (BABYLON = {}));
  26687. //# sourceMappingURL=babylon.action.js.map
  26688. var BABYLON;
  26689. (function (BABYLON) {
  26690. /**
  26691. * ActionEvent is the event beint sent when an action is triggered.
  26692. */
  26693. var ActionEvent = (function () {
  26694. /**
  26695. * @constructor
  26696. * @param source The mesh that triggered the action.
  26697. * @param pointerX the X mouse cursor position at the time of the event
  26698. * @param pointerY the Y mouse cursor position at the time of the event
  26699. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26700. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26701. */
  26702. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26703. this.source = source;
  26704. this.pointerX = pointerX;
  26705. this.pointerY = pointerY;
  26706. this.meshUnderPointer = meshUnderPointer;
  26707. this.sourceEvent = sourceEvent;
  26708. }
  26709. /**
  26710. * Helper function to auto-create an ActionEvent from a source mesh.
  26711. * @param source the source mesh that triggered the event
  26712. * @param evt {Event} The original (browser) event
  26713. */
  26714. ActionEvent.CreateNew = function (source, evt) {
  26715. var scene = source.getScene();
  26716. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26717. };
  26718. /**
  26719. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26720. * @param scene the scene where the event occurred
  26721. * @param evt {Event} The original (browser) event
  26722. */
  26723. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26724. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26725. };
  26726. return ActionEvent;
  26727. })();
  26728. BABYLON.ActionEvent = ActionEvent;
  26729. /**
  26730. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26731. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26732. */
  26733. var ActionManager = (function () {
  26734. function ActionManager(scene) {
  26735. // Members
  26736. this.actions = new Array();
  26737. this._scene = scene;
  26738. scene._actionManagers.push(this);
  26739. }
  26740. Object.defineProperty(ActionManager, "NothingTrigger", {
  26741. get: function () {
  26742. return ActionManager._NothingTrigger;
  26743. },
  26744. enumerable: true,
  26745. configurable: true
  26746. });
  26747. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26748. get: function () {
  26749. return ActionManager._OnPickTrigger;
  26750. },
  26751. enumerable: true,
  26752. configurable: true
  26753. });
  26754. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26755. get: function () {
  26756. return ActionManager._OnLeftPickTrigger;
  26757. },
  26758. enumerable: true,
  26759. configurable: true
  26760. });
  26761. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26762. get: function () {
  26763. return ActionManager._OnRightPickTrigger;
  26764. },
  26765. enumerable: true,
  26766. configurable: true
  26767. });
  26768. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26769. get: function () {
  26770. return ActionManager._OnCenterPickTrigger;
  26771. },
  26772. enumerable: true,
  26773. configurable: true
  26774. });
  26775. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26776. get: function () {
  26777. return ActionManager._OnPointerOverTrigger;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26783. get: function () {
  26784. return ActionManager._OnPointerOutTrigger;
  26785. },
  26786. enumerable: true,
  26787. configurable: true
  26788. });
  26789. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26790. get: function () {
  26791. return ActionManager._OnEveryFrameTrigger;
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26797. get: function () {
  26798. return ActionManager._OnIntersectionEnterTrigger;
  26799. },
  26800. enumerable: true,
  26801. configurable: true
  26802. });
  26803. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26804. get: function () {
  26805. return ActionManager._OnIntersectionExitTrigger;
  26806. },
  26807. enumerable: true,
  26808. configurable: true
  26809. });
  26810. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26811. get: function () {
  26812. return ActionManager._OnKeyDownTrigger;
  26813. },
  26814. enumerable: true,
  26815. configurable: true
  26816. });
  26817. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26818. get: function () {
  26819. return ActionManager._OnKeyUpTrigger;
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26825. get: function () {
  26826. return ActionManager._OnPickUpTrigger;
  26827. },
  26828. enumerable: true,
  26829. configurable: true
  26830. });
  26831. // Methods
  26832. ActionManager.prototype.dispose = function () {
  26833. var index = this._scene._actionManagers.indexOf(this);
  26834. if (index > -1) {
  26835. this._scene._actionManagers.splice(index, 1);
  26836. }
  26837. };
  26838. ActionManager.prototype.getScene = function () {
  26839. return this._scene;
  26840. };
  26841. /**
  26842. * Does this action manager handles actions of any of the given triggers
  26843. * @param {number[]} triggers - the triggers to be tested
  26844. * @return {boolean} whether one (or more) of the triggers is handeled
  26845. */
  26846. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26847. for (var index = 0; index < this.actions.length; index++) {
  26848. var action = this.actions[index];
  26849. if (triggers.indexOf(action.trigger) > -1) {
  26850. return true;
  26851. }
  26852. }
  26853. return false;
  26854. };
  26855. /**
  26856. * Does this action manager handles actions of a given trigger
  26857. * @param {number} trigger - the trigger to be tested
  26858. * @return {boolean} whether the trigger is handeled
  26859. */
  26860. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26861. for (var index = 0; index < this.actions.length; index++) {
  26862. var action = this.actions[index];
  26863. if (action.trigger === trigger) {
  26864. return true;
  26865. }
  26866. }
  26867. return false;
  26868. };
  26869. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26870. /**
  26871. * Does this action manager has pointer triggers
  26872. * @return {boolean} whether or not it has pointer triggers
  26873. */
  26874. get: function () {
  26875. for (var index = 0; index < this.actions.length; index++) {
  26876. var action = this.actions[index];
  26877. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26878. return true;
  26879. }
  26880. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26881. return true;
  26882. }
  26883. }
  26884. return false;
  26885. },
  26886. enumerable: true,
  26887. configurable: true
  26888. });
  26889. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26890. /**
  26891. * Does this action manager has pick triggers
  26892. * @return {boolean} whether or not it has pick triggers
  26893. */
  26894. get: function () {
  26895. for (var index = 0; index < this.actions.length; index++) {
  26896. var action = this.actions[index];
  26897. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26898. return true;
  26899. }
  26900. }
  26901. return false;
  26902. },
  26903. enumerable: true,
  26904. configurable: true
  26905. });
  26906. /**
  26907. * Registers an action to this action manager
  26908. * @param {BABYLON.Action} action - the action to be registered
  26909. * @return {BABYLON.Action} the action amended (prepared) after registration
  26910. */
  26911. ActionManager.prototype.registerAction = function (action) {
  26912. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26913. if (this.getScene().actionManager !== this) {
  26914. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26915. return null;
  26916. }
  26917. }
  26918. this.actions.push(action);
  26919. action._actionManager = this;
  26920. action._prepare();
  26921. return action;
  26922. };
  26923. /**
  26924. * Process a specific trigger
  26925. * @param {number} trigger - the trigger to process
  26926. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26927. */
  26928. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26929. for (var index = 0; index < this.actions.length; index++) {
  26930. var action = this.actions[index];
  26931. if (action.trigger === trigger) {
  26932. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26933. var parameter = action.getTriggerParameter();
  26934. if (parameter) {
  26935. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26936. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26937. if (actualkey !== parameter.toLowerCase()) {
  26938. continue;
  26939. }
  26940. }
  26941. }
  26942. action._executeCurrent(evt);
  26943. }
  26944. }
  26945. };
  26946. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26947. var properties = propertyPath.split(".");
  26948. for (var index = 0; index < properties.length - 1; index++) {
  26949. target = target[properties[index]];
  26950. }
  26951. return target;
  26952. };
  26953. ActionManager.prototype._getProperty = function (propertyPath) {
  26954. var properties = propertyPath.split(".");
  26955. return properties[properties.length - 1];
  26956. };
  26957. // Statics
  26958. ActionManager._NothingTrigger = 0;
  26959. ActionManager._OnPickTrigger = 1;
  26960. ActionManager._OnLeftPickTrigger = 2;
  26961. ActionManager._OnRightPickTrigger = 3;
  26962. ActionManager._OnCenterPickTrigger = 4;
  26963. ActionManager._OnPointerOverTrigger = 5;
  26964. ActionManager._OnPointerOutTrigger = 6;
  26965. ActionManager._OnEveryFrameTrigger = 7;
  26966. ActionManager._OnIntersectionEnterTrigger = 8;
  26967. ActionManager._OnIntersectionExitTrigger = 9;
  26968. ActionManager._OnKeyDownTrigger = 10;
  26969. ActionManager._OnKeyUpTrigger = 11;
  26970. ActionManager._OnPickUpTrigger = 12;
  26971. return ActionManager;
  26972. })();
  26973. BABYLON.ActionManager = ActionManager;
  26974. })(BABYLON || (BABYLON = {}));
  26975. //# sourceMappingURL=babylon.actionManager.js.map
  26976. var __extends = this.__extends || function (d, b) {
  26977. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26978. function __() { this.constructor = d; }
  26979. __.prototype = b.prototype;
  26980. d.prototype = new __();
  26981. };
  26982. var BABYLON;
  26983. (function (BABYLON) {
  26984. var InterpolateValueAction = (function (_super) {
  26985. __extends(InterpolateValueAction, _super);
  26986. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26987. if (duration === void 0) { duration = 1000; }
  26988. _super.call(this, triggerOptions, condition);
  26989. this.propertyPath = propertyPath;
  26990. this.value = value;
  26991. this.duration = duration;
  26992. this.stopOtherAnimations = stopOtherAnimations;
  26993. this._target = target;
  26994. }
  26995. InterpolateValueAction.prototype._prepare = function () {
  26996. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26997. this._property = this._getProperty(this.propertyPath);
  26998. };
  26999. InterpolateValueAction.prototype.execute = function () {
  27000. var scene = this._actionManager.getScene();
  27001. var keys = [
  27002. {
  27003. frame: 0,
  27004. value: this._target[this._property]
  27005. },
  27006. {
  27007. frame: 100,
  27008. value: this.value
  27009. }
  27010. ];
  27011. var dataType;
  27012. if (typeof this.value === "number") {
  27013. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27014. }
  27015. else if (this.value instanceof BABYLON.Color3) {
  27016. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27017. }
  27018. else if (this.value instanceof BABYLON.Vector3) {
  27019. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27020. }
  27021. else if (this.value instanceof BABYLON.Matrix) {
  27022. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27023. }
  27024. else if (this.value instanceof BABYLON.Quaternion) {
  27025. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27026. }
  27027. else {
  27028. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27029. return;
  27030. }
  27031. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27032. animation.setKeys(keys);
  27033. if (this.stopOtherAnimations) {
  27034. scene.stopAnimation(this._target);
  27035. }
  27036. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27037. };
  27038. return InterpolateValueAction;
  27039. })(BABYLON.Action);
  27040. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27041. })(BABYLON || (BABYLON = {}));
  27042. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27043. var __extends = this.__extends || function (d, b) {
  27044. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27045. function __() { this.constructor = d; }
  27046. __.prototype = b.prototype;
  27047. d.prototype = new __();
  27048. };
  27049. var BABYLON;
  27050. (function (BABYLON) {
  27051. var SwitchBooleanAction = (function (_super) {
  27052. __extends(SwitchBooleanAction, _super);
  27053. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27054. _super.call(this, triggerOptions, condition);
  27055. this.propertyPath = propertyPath;
  27056. this._target = target;
  27057. }
  27058. SwitchBooleanAction.prototype._prepare = function () {
  27059. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27060. this._property = this._getProperty(this.propertyPath);
  27061. };
  27062. SwitchBooleanAction.prototype.execute = function () {
  27063. this._target[this._property] = !this._target[this._property];
  27064. };
  27065. return SwitchBooleanAction;
  27066. })(BABYLON.Action);
  27067. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27068. var SetStateAction = (function (_super) {
  27069. __extends(SetStateAction, _super);
  27070. function SetStateAction(triggerOptions, target, value, condition) {
  27071. _super.call(this, triggerOptions, condition);
  27072. this.value = value;
  27073. this._target = target;
  27074. }
  27075. SetStateAction.prototype.execute = function () {
  27076. this._target.state = this.value;
  27077. };
  27078. return SetStateAction;
  27079. })(BABYLON.Action);
  27080. BABYLON.SetStateAction = SetStateAction;
  27081. var SetValueAction = (function (_super) {
  27082. __extends(SetValueAction, _super);
  27083. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27084. _super.call(this, triggerOptions, condition);
  27085. this.propertyPath = propertyPath;
  27086. this.value = value;
  27087. this._target = target;
  27088. }
  27089. SetValueAction.prototype._prepare = function () {
  27090. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27091. this._property = this._getProperty(this.propertyPath);
  27092. };
  27093. SetValueAction.prototype.execute = function () {
  27094. this._target[this._property] = this.value;
  27095. };
  27096. return SetValueAction;
  27097. })(BABYLON.Action);
  27098. BABYLON.SetValueAction = SetValueAction;
  27099. var IncrementValueAction = (function (_super) {
  27100. __extends(IncrementValueAction, _super);
  27101. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27102. _super.call(this, triggerOptions, condition);
  27103. this.propertyPath = propertyPath;
  27104. this.value = value;
  27105. this._target = target;
  27106. }
  27107. IncrementValueAction.prototype._prepare = function () {
  27108. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27109. this._property = this._getProperty(this.propertyPath);
  27110. if (typeof this._target[this._property] !== "number") {
  27111. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27112. }
  27113. };
  27114. IncrementValueAction.prototype.execute = function () {
  27115. this._target[this._property] += this.value;
  27116. };
  27117. return IncrementValueAction;
  27118. })(BABYLON.Action);
  27119. BABYLON.IncrementValueAction = IncrementValueAction;
  27120. var PlayAnimationAction = (function (_super) {
  27121. __extends(PlayAnimationAction, _super);
  27122. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27123. _super.call(this, triggerOptions, condition);
  27124. this.from = from;
  27125. this.to = to;
  27126. this.loop = loop;
  27127. this._target = target;
  27128. }
  27129. PlayAnimationAction.prototype._prepare = function () {
  27130. };
  27131. PlayAnimationAction.prototype.execute = function () {
  27132. var scene = this._actionManager.getScene();
  27133. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27134. };
  27135. return PlayAnimationAction;
  27136. })(BABYLON.Action);
  27137. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27138. var StopAnimationAction = (function (_super) {
  27139. __extends(StopAnimationAction, _super);
  27140. function StopAnimationAction(triggerOptions, target, condition) {
  27141. _super.call(this, triggerOptions, condition);
  27142. this._target = target;
  27143. }
  27144. StopAnimationAction.prototype._prepare = function () {
  27145. };
  27146. StopAnimationAction.prototype.execute = function () {
  27147. var scene = this._actionManager.getScene();
  27148. scene.stopAnimation(this._target);
  27149. };
  27150. return StopAnimationAction;
  27151. })(BABYLON.Action);
  27152. BABYLON.StopAnimationAction = StopAnimationAction;
  27153. var DoNothingAction = (function (_super) {
  27154. __extends(DoNothingAction, _super);
  27155. function DoNothingAction(triggerOptions, condition) {
  27156. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27157. _super.call(this, triggerOptions, condition);
  27158. }
  27159. DoNothingAction.prototype.execute = function () {
  27160. };
  27161. return DoNothingAction;
  27162. })(BABYLON.Action);
  27163. BABYLON.DoNothingAction = DoNothingAction;
  27164. var CombineAction = (function (_super) {
  27165. __extends(CombineAction, _super);
  27166. function CombineAction(triggerOptions, children, condition) {
  27167. _super.call(this, triggerOptions, condition);
  27168. this.children = children;
  27169. }
  27170. CombineAction.prototype._prepare = function () {
  27171. for (var index = 0; index < this.children.length; index++) {
  27172. this.children[index]._actionManager = this._actionManager;
  27173. this.children[index]._prepare();
  27174. }
  27175. };
  27176. CombineAction.prototype.execute = function (evt) {
  27177. for (var index = 0; index < this.children.length; index++) {
  27178. this.children[index].execute(evt);
  27179. }
  27180. };
  27181. return CombineAction;
  27182. })(BABYLON.Action);
  27183. BABYLON.CombineAction = CombineAction;
  27184. var ExecuteCodeAction = (function (_super) {
  27185. __extends(ExecuteCodeAction, _super);
  27186. function ExecuteCodeAction(triggerOptions, func, condition) {
  27187. _super.call(this, triggerOptions, condition);
  27188. this.func = func;
  27189. }
  27190. ExecuteCodeAction.prototype.execute = function (evt) {
  27191. this.func(evt);
  27192. };
  27193. return ExecuteCodeAction;
  27194. })(BABYLON.Action);
  27195. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27196. var SetParentAction = (function (_super) {
  27197. __extends(SetParentAction, _super);
  27198. function SetParentAction(triggerOptions, target, parent, condition) {
  27199. _super.call(this, triggerOptions, condition);
  27200. this._target = target;
  27201. this._parent = parent;
  27202. }
  27203. SetParentAction.prototype._prepare = function () {
  27204. };
  27205. SetParentAction.prototype.execute = function () {
  27206. if (this._target.parent === this._parent) {
  27207. return;
  27208. }
  27209. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27210. invertParentWorldMatrix.invert();
  27211. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27212. this._target.parent = this._parent;
  27213. };
  27214. return SetParentAction;
  27215. })(BABYLON.Action);
  27216. BABYLON.SetParentAction = SetParentAction;
  27217. var PlaySoundAction = (function (_super) {
  27218. __extends(PlaySoundAction, _super);
  27219. function PlaySoundAction(triggerOptions, sound, condition) {
  27220. _super.call(this, triggerOptions, condition);
  27221. this._sound = sound;
  27222. }
  27223. PlaySoundAction.prototype._prepare = function () {
  27224. };
  27225. PlaySoundAction.prototype.execute = function () {
  27226. if (this._sound !== undefined)
  27227. this._sound.play();
  27228. };
  27229. return PlaySoundAction;
  27230. })(BABYLON.Action);
  27231. BABYLON.PlaySoundAction = PlaySoundAction;
  27232. var StopSoundAction = (function (_super) {
  27233. __extends(StopSoundAction, _super);
  27234. function StopSoundAction(triggerOptions, sound, condition) {
  27235. _super.call(this, triggerOptions, condition);
  27236. this._sound = sound;
  27237. }
  27238. StopSoundAction.prototype._prepare = function () {
  27239. };
  27240. StopSoundAction.prototype.execute = function () {
  27241. if (this._sound !== undefined)
  27242. this._sound.stop();
  27243. };
  27244. return StopSoundAction;
  27245. })(BABYLON.Action);
  27246. BABYLON.StopSoundAction = StopSoundAction;
  27247. })(BABYLON || (BABYLON = {}));
  27248. //# sourceMappingURL=babylon.directActions.js.map
  27249. var __extends = this.__extends || function (d, b) {
  27250. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27251. function __() { this.constructor = d; }
  27252. __.prototype = b.prototype;
  27253. d.prototype = new __();
  27254. };
  27255. var BABYLON;
  27256. (function (BABYLON) {
  27257. var Geometry = (function () {
  27258. function Geometry(id, scene, vertexData, updatable, mesh) {
  27259. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27260. this._totalVertices = 0;
  27261. this._indices = [];
  27262. this._isDisposed = false;
  27263. this.id = id;
  27264. this._engine = scene.getEngine();
  27265. this._meshes = [];
  27266. this._scene = scene;
  27267. // vertexData
  27268. if (vertexData) {
  27269. this.setAllVerticesData(vertexData, updatable);
  27270. }
  27271. else {
  27272. this._totalVertices = 0;
  27273. this._indices = [];
  27274. }
  27275. // applyToMesh
  27276. if (mesh) {
  27277. this.applyToMesh(mesh);
  27278. mesh.computeWorldMatrix(true);
  27279. }
  27280. }
  27281. Geometry.prototype.getScene = function () {
  27282. return this._scene;
  27283. };
  27284. Geometry.prototype.getEngine = function () {
  27285. return this._engine;
  27286. };
  27287. Geometry.prototype.isReady = function () {
  27288. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27289. };
  27290. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27291. vertexData.applyToGeometry(this, updatable);
  27292. this.notifyUpdate();
  27293. };
  27294. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27295. this._vertexBuffers = this._vertexBuffers || {};
  27296. if (this._vertexBuffers[kind]) {
  27297. this._vertexBuffers[kind].dispose();
  27298. }
  27299. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27300. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27301. stride = this._vertexBuffers[kind].getStrideSize();
  27302. this._totalVertices = data.length / stride;
  27303. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27304. var meshes = this._meshes;
  27305. var numOfMeshes = meshes.length;
  27306. for (var index = 0; index < numOfMeshes; index++) {
  27307. var mesh = meshes[index];
  27308. mesh._resetPointsArrayCache();
  27309. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27310. mesh._createGlobalSubMesh();
  27311. mesh.computeWorldMatrix(true);
  27312. }
  27313. }
  27314. this.notifyUpdate(kind);
  27315. };
  27316. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27317. var vertexBuffer = this.getVertexBuffer(kind);
  27318. if (!vertexBuffer) {
  27319. return;
  27320. }
  27321. vertexBuffer.updateDirectly(data, offset);
  27322. this.notifyUpdate(kind);
  27323. };
  27324. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27325. var vertexBuffer = this.getVertexBuffer(kind);
  27326. if (!vertexBuffer) {
  27327. return;
  27328. }
  27329. vertexBuffer.update(data);
  27330. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27331. var extend;
  27332. var stride = vertexBuffer.getStrideSize();
  27333. this._totalVertices = data.length / stride;
  27334. if (updateExtends) {
  27335. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27336. }
  27337. var meshes = this._meshes;
  27338. var numOfMeshes = meshes.length;
  27339. for (var index = 0; index < numOfMeshes; index++) {
  27340. var mesh = meshes[index];
  27341. mesh._resetPointsArrayCache();
  27342. if (updateExtends) {
  27343. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27344. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27345. var subMesh = mesh.subMeshes[subIndex];
  27346. subMesh.refreshBoundingInfo();
  27347. }
  27348. }
  27349. }
  27350. }
  27351. this.notifyUpdate(kind);
  27352. };
  27353. Geometry.prototype.getTotalVertices = function () {
  27354. if (!this.isReady()) {
  27355. return 0;
  27356. }
  27357. return this._totalVertices;
  27358. };
  27359. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27360. var vertexBuffer = this.getVertexBuffer(kind);
  27361. if (!vertexBuffer) {
  27362. return null;
  27363. }
  27364. var orig = vertexBuffer.getData();
  27365. if (!copyWhenShared || this._meshes.length === 1) {
  27366. return orig;
  27367. }
  27368. else {
  27369. var len = orig.length;
  27370. var copy = [];
  27371. for (var i = 0; i < len; i++) {
  27372. copy.push(orig[i]);
  27373. }
  27374. return copy;
  27375. }
  27376. };
  27377. Geometry.prototype.getVertexBuffer = function (kind) {
  27378. if (!this.isReady()) {
  27379. return null;
  27380. }
  27381. return this._vertexBuffers[kind];
  27382. };
  27383. Geometry.prototype.getVertexBuffers = function () {
  27384. if (!this.isReady()) {
  27385. return null;
  27386. }
  27387. return this._vertexBuffers;
  27388. };
  27389. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27390. if (!this._vertexBuffers) {
  27391. if (this._delayInfo) {
  27392. return this._delayInfo.indexOf(kind) !== -1;
  27393. }
  27394. return false;
  27395. }
  27396. return this._vertexBuffers[kind] !== undefined;
  27397. };
  27398. Geometry.prototype.getVerticesDataKinds = function () {
  27399. var result = [];
  27400. if (!this._vertexBuffers && this._delayInfo) {
  27401. for (var kind in this._delayInfo) {
  27402. result.push(kind);
  27403. }
  27404. }
  27405. else {
  27406. for (kind in this._vertexBuffers) {
  27407. result.push(kind);
  27408. }
  27409. }
  27410. return result;
  27411. };
  27412. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27413. if (this._indexBuffer) {
  27414. this._engine._releaseBuffer(this._indexBuffer);
  27415. }
  27416. this._indices = indices;
  27417. if (this._meshes.length !== 0 && this._indices) {
  27418. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27419. }
  27420. if (totalVertices !== undefined) {
  27421. this._totalVertices = totalVertices;
  27422. }
  27423. var meshes = this._meshes;
  27424. var numOfMeshes = meshes.length;
  27425. for (var index = 0; index < numOfMeshes; index++) {
  27426. meshes[index]._createGlobalSubMesh();
  27427. }
  27428. this.notifyUpdate();
  27429. };
  27430. Geometry.prototype.getTotalIndices = function () {
  27431. if (!this.isReady()) {
  27432. return 0;
  27433. }
  27434. return this._indices.length;
  27435. };
  27436. Geometry.prototype.getIndices = function (copyWhenShared) {
  27437. if (!this.isReady()) {
  27438. return null;
  27439. }
  27440. var orig = this._indices;
  27441. if (!copyWhenShared || this._meshes.length === 1) {
  27442. return orig;
  27443. }
  27444. else {
  27445. var len = orig.length;
  27446. var copy = [];
  27447. for (var i = 0; i < len; i++) {
  27448. copy.push(orig[i]);
  27449. }
  27450. return copy;
  27451. }
  27452. };
  27453. Geometry.prototype.getIndexBuffer = function () {
  27454. if (!this.isReady()) {
  27455. return null;
  27456. }
  27457. return this._indexBuffer;
  27458. };
  27459. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27460. var meshes = this._meshes;
  27461. var index = meshes.indexOf(mesh);
  27462. if (index === -1) {
  27463. return;
  27464. }
  27465. for (var kind in this._vertexBuffers) {
  27466. this._vertexBuffers[kind].dispose();
  27467. }
  27468. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27469. this._indexBuffer = null;
  27470. }
  27471. meshes.splice(index, 1);
  27472. mesh._geometry = null;
  27473. if (meshes.length === 0 && shouldDispose) {
  27474. this.dispose();
  27475. }
  27476. };
  27477. Geometry.prototype.applyToMesh = function (mesh) {
  27478. if (mesh._geometry === this) {
  27479. return;
  27480. }
  27481. var previousGeometry = mesh._geometry;
  27482. if (previousGeometry) {
  27483. previousGeometry.releaseForMesh(mesh);
  27484. }
  27485. var meshes = this._meshes;
  27486. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27487. mesh._geometry = this;
  27488. this._scene.pushGeometry(this);
  27489. meshes.push(mesh);
  27490. if (this.isReady()) {
  27491. this._applyToMesh(mesh);
  27492. }
  27493. else {
  27494. mesh._boundingInfo = this._boundingInfo;
  27495. }
  27496. };
  27497. Geometry.prototype._applyToMesh = function (mesh) {
  27498. var numOfMeshes = this._meshes.length;
  27499. for (var kind in this._vertexBuffers) {
  27500. if (numOfMeshes === 1) {
  27501. this._vertexBuffers[kind].create();
  27502. }
  27503. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27504. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27505. mesh._resetPointsArrayCache();
  27506. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27507. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27508. mesh._createGlobalSubMesh();
  27509. //bounding info was just created again, world matrix should be applied again.
  27510. mesh._updateBoundingInfo();
  27511. }
  27512. }
  27513. // indexBuffer
  27514. if (numOfMeshes === 1 && this._indices) {
  27515. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27516. }
  27517. if (this._indexBuffer) {
  27518. this._indexBuffer.references = numOfMeshes;
  27519. }
  27520. };
  27521. Geometry.prototype.notifyUpdate = function (kind) {
  27522. if (this.onGeometryUpdated) {
  27523. this.onGeometryUpdated(this, kind);
  27524. }
  27525. };
  27526. Geometry.prototype.load = function (scene, onLoaded) {
  27527. var _this = this;
  27528. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27529. return;
  27530. }
  27531. if (this.isReady()) {
  27532. if (onLoaded) {
  27533. onLoaded();
  27534. }
  27535. return;
  27536. }
  27537. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27538. scene._addPendingData(this);
  27539. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27540. _this._delayLoadingFunction(JSON.parse(data), _this);
  27541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27542. _this._delayInfo = [];
  27543. scene._removePendingData(_this);
  27544. var meshes = _this._meshes;
  27545. var numOfMeshes = meshes.length;
  27546. for (var index = 0; index < numOfMeshes; index++) {
  27547. _this._applyToMesh(meshes[index]);
  27548. }
  27549. if (onLoaded) {
  27550. onLoaded();
  27551. }
  27552. }, function () {
  27553. }, scene.database);
  27554. };
  27555. Geometry.prototype.isDisposed = function () {
  27556. return this._isDisposed;
  27557. };
  27558. Geometry.prototype.dispose = function () {
  27559. var meshes = this._meshes;
  27560. var numOfMeshes = meshes.length;
  27561. var index;
  27562. for (index = 0; index < numOfMeshes; index++) {
  27563. this.releaseForMesh(meshes[index]);
  27564. }
  27565. this._meshes = [];
  27566. for (var kind in this._vertexBuffers) {
  27567. this._vertexBuffers[kind].dispose();
  27568. }
  27569. this._vertexBuffers = [];
  27570. this._totalVertices = 0;
  27571. if (this._indexBuffer) {
  27572. this._engine._releaseBuffer(this._indexBuffer);
  27573. }
  27574. this._indexBuffer = null;
  27575. this._indices = [];
  27576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27577. this.delayLoadingFile = null;
  27578. this._delayLoadingFunction = null;
  27579. this._delayInfo = [];
  27580. this._boundingInfo = null; // todo: .dispose()
  27581. this._scene.removeGeometry(this);
  27582. this._isDisposed = true;
  27583. };
  27584. Geometry.prototype.copy = function (id) {
  27585. var vertexData = new BABYLON.VertexData();
  27586. vertexData.indices = [];
  27587. var indices = this.getIndices();
  27588. for (var index = 0; index < indices.length; index++) {
  27589. vertexData.indices.push(indices[index]);
  27590. }
  27591. var updatable = false;
  27592. var stopChecking = false;
  27593. for (var kind in this._vertexBuffers) {
  27594. // using slice() to make a copy of the array and not just reference it
  27595. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27596. if (!stopChecking) {
  27597. updatable = this.getVertexBuffer(kind).isUpdatable();
  27598. stopChecking = !updatable;
  27599. }
  27600. }
  27601. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27602. geometry.delayLoadState = this.delayLoadState;
  27603. geometry.delayLoadingFile = this.delayLoadingFile;
  27604. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27605. for (kind in this._delayInfo) {
  27606. geometry._delayInfo = geometry._delayInfo || [];
  27607. geometry._delayInfo.push(kind);
  27608. }
  27609. // Bounding info
  27610. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27611. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27612. return geometry;
  27613. };
  27614. // Statics
  27615. Geometry.ExtractFromMesh = function (mesh, id) {
  27616. var geometry = mesh._geometry;
  27617. if (!geometry) {
  27618. return null;
  27619. }
  27620. return geometry.copy(id);
  27621. };
  27622. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27623. // be aware Math.random() could cause collisions
  27624. Geometry.RandomId = function () {
  27625. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27626. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27627. return v.toString(16);
  27628. });
  27629. };
  27630. return Geometry;
  27631. })();
  27632. BABYLON.Geometry = Geometry;
  27633. /////// Primitives //////////////////////////////////////////////
  27634. var Geometry;
  27635. (function (Geometry) {
  27636. var Primitives;
  27637. (function (Primitives) {
  27638. /// Abstract class
  27639. var _Primitive = (function (_super) {
  27640. __extends(_Primitive, _super);
  27641. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27642. this._beingRegenerated = true;
  27643. this._canBeRegenerated = canBeRegenerated;
  27644. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27645. this._beingRegenerated = false;
  27646. }
  27647. _Primitive.prototype.canBeRegenerated = function () {
  27648. return this._canBeRegenerated;
  27649. };
  27650. _Primitive.prototype.regenerate = function () {
  27651. if (!this._canBeRegenerated) {
  27652. return;
  27653. }
  27654. this._beingRegenerated = true;
  27655. this.setAllVerticesData(this._regenerateVertexData(), false);
  27656. this._beingRegenerated = false;
  27657. };
  27658. _Primitive.prototype.asNewGeometry = function (id) {
  27659. return _super.prototype.copy.call(this, id);
  27660. };
  27661. // overrides
  27662. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27663. if (!this._beingRegenerated) {
  27664. return;
  27665. }
  27666. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27667. };
  27668. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27669. if (!this._beingRegenerated) {
  27670. return;
  27671. }
  27672. _super.prototype.setVerticesData.call(this, kind, data, false);
  27673. };
  27674. // to override
  27675. // protected
  27676. _Primitive.prototype._regenerateVertexData = function () {
  27677. throw new Error("Abstract method");
  27678. };
  27679. _Primitive.prototype.copy = function (id) {
  27680. throw new Error("Must be overriden in sub-classes.");
  27681. };
  27682. return _Primitive;
  27683. })(Geometry);
  27684. Primitives._Primitive = _Primitive;
  27685. var Ribbon = (function (_super) {
  27686. __extends(Ribbon, _super);
  27687. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27688. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27689. this.pathArray = pathArray;
  27690. this.closeArray = closeArray;
  27691. this.closePath = closePath;
  27692. this.offset = offset;
  27693. this.side = side;
  27694. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27695. }
  27696. Ribbon.prototype._regenerateVertexData = function () {
  27697. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27698. };
  27699. Ribbon.prototype.copy = function (id) {
  27700. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27701. };
  27702. return Ribbon;
  27703. })(_Primitive);
  27704. Primitives.Ribbon = Ribbon;
  27705. var Box = (function (_super) {
  27706. __extends(Box, _super);
  27707. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27709. this.size = size;
  27710. this.side = side;
  27711. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27712. }
  27713. Box.prototype._regenerateVertexData = function () {
  27714. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27715. };
  27716. Box.prototype.copy = function (id) {
  27717. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27718. };
  27719. return Box;
  27720. })(_Primitive);
  27721. Primitives.Box = Box;
  27722. var Sphere = (function (_super) {
  27723. __extends(Sphere, _super);
  27724. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27725. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27726. this.segments = segments;
  27727. this.diameter = diameter;
  27728. this.side = side;
  27729. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27730. }
  27731. Sphere.prototype._regenerateVertexData = function () {
  27732. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27733. };
  27734. Sphere.prototype.copy = function (id) {
  27735. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27736. };
  27737. return Sphere;
  27738. })(_Primitive);
  27739. Primitives.Sphere = Sphere;
  27740. var Cylinder = (function (_super) {
  27741. __extends(Cylinder, _super);
  27742. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27743. if (subdivisions === void 0) { subdivisions = 1; }
  27744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27745. this.height = height;
  27746. this.diameterTop = diameterTop;
  27747. this.diameterBottom = diameterBottom;
  27748. this.tessellation = tessellation;
  27749. this.subdivisions = subdivisions;
  27750. this.side = side;
  27751. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27752. }
  27753. Cylinder.prototype._regenerateVertexData = function () {
  27754. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27755. };
  27756. Cylinder.prototype.copy = function (id) {
  27757. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27758. };
  27759. return Cylinder;
  27760. })(_Primitive);
  27761. Primitives.Cylinder = Cylinder;
  27762. var Torus = (function (_super) {
  27763. __extends(Torus, _super);
  27764. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27765. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27766. this.diameter = diameter;
  27767. this.thickness = thickness;
  27768. this.tessellation = tessellation;
  27769. this.side = side;
  27770. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27771. }
  27772. Torus.prototype._regenerateVertexData = function () {
  27773. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27774. };
  27775. Torus.prototype.copy = function (id) {
  27776. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27777. };
  27778. return Torus;
  27779. })(_Primitive);
  27780. Primitives.Torus = Torus;
  27781. var Ground = (function (_super) {
  27782. __extends(Ground, _super);
  27783. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27784. this.width = width;
  27785. this.height = height;
  27786. this.subdivisions = subdivisions;
  27787. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27788. }
  27789. Ground.prototype._regenerateVertexData = function () {
  27790. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27791. };
  27792. Ground.prototype.copy = function (id) {
  27793. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27794. };
  27795. return Ground;
  27796. })(_Primitive);
  27797. Primitives.Ground = Ground;
  27798. var TiledGround = (function (_super) {
  27799. __extends(TiledGround, _super);
  27800. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27801. this.xmin = xmin;
  27802. this.zmin = zmin;
  27803. this.xmax = xmax;
  27804. this.zmax = zmax;
  27805. this.subdivisions = subdivisions;
  27806. this.precision = precision;
  27807. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27808. }
  27809. TiledGround.prototype._regenerateVertexData = function () {
  27810. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27811. };
  27812. TiledGround.prototype.copy = function (id) {
  27813. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27814. };
  27815. return TiledGround;
  27816. })(_Primitive);
  27817. Primitives.TiledGround = TiledGround;
  27818. var Plane = (function (_super) {
  27819. __extends(Plane, _super);
  27820. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27822. this.size = size;
  27823. this.side = side;
  27824. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27825. }
  27826. Plane.prototype._regenerateVertexData = function () {
  27827. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27828. };
  27829. Plane.prototype.copy = function (id) {
  27830. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27831. };
  27832. return Plane;
  27833. })(_Primitive);
  27834. Primitives.Plane = Plane;
  27835. var TorusKnot = (function (_super) {
  27836. __extends(TorusKnot, _super);
  27837. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27838. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27839. this.radius = radius;
  27840. this.tube = tube;
  27841. this.radialSegments = radialSegments;
  27842. this.tubularSegments = tubularSegments;
  27843. this.p = p;
  27844. this.q = q;
  27845. this.side = side;
  27846. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27847. }
  27848. TorusKnot.prototype._regenerateVertexData = function () {
  27849. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27850. };
  27851. TorusKnot.prototype.copy = function (id) {
  27852. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27853. };
  27854. return TorusKnot;
  27855. })(_Primitive);
  27856. Primitives.TorusKnot = TorusKnot;
  27857. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27858. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27859. })(BABYLON || (BABYLON = {}));
  27860. //# sourceMappingURL=babylon.geometry.js.map
  27861. var __extends = this.__extends || function (d, b) {
  27862. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27863. function __() { this.constructor = d; }
  27864. __.prototype = b.prototype;
  27865. d.prototype = new __();
  27866. };
  27867. var BABYLON;
  27868. (function (BABYLON) {
  27869. var GroundMesh = (function (_super) {
  27870. __extends(GroundMesh, _super);
  27871. function GroundMesh(name, scene) {
  27872. _super.call(this, name, scene);
  27873. this.generateOctree = false;
  27874. this._worldInverse = new BABYLON.Matrix();
  27875. }
  27876. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27877. get: function () {
  27878. return this._subdivisions;
  27879. },
  27880. enumerable: true,
  27881. configurable: true
  27882. });
  27883. GroundMesh.prototype.optimize = function (chunksCount) {
  27884. this.subdivide(this._subdivisions);
  27885. this.createOrUpdateSubmeshesOctree(32);
  27886. };
  27887. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27888. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27889. this.getWorldMatrix().invertToRef(this._worldInverse);
  27890. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27891. var pickInfo = this.intersects(ray);
  27892. if (pickInfo.hit) {
  27893. return pickInfo.pickedPoint.y;
  27894. }
  27895. return 0;
  27896. };
  27897. return GroundMesh;
  27898. })(BABYLON.Mesh);
  27899. BABYLON.GroundMesh = GroundMesh;
  27900. })(BABYLON || (BABYLON = {}));
  27901. //# sourceMappingURL=babylon.groundMesh.js.map
  27902. var __extends = this.__extends || function (d, b) {
  27903. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27904. function __() { this.constructor = d; }
  27905. __.prototype = b.prototype;
  27906. d.prototype = new __();
  27907. };
  27908. var BABYLON;
  27909. (function (BABYLON) {
  27910. var LinesMesh = (function (_super) {
  27911. __extends(LinesMesh, _super);
  27912. function LinesMesh(name, scene, updatable) {
  27913. if (updatable === void 0) { updatable = false; }
  27914. _super.call(this, name, scene);
  27915. this.color = new BABYLON.Color3(1, 1, 1);
  27916. this.alpha = 1;
  27917. this._indices = new Array();
  27918. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27919. attributes: ["position"],
  27920. uniforms: ["worldViewProjection", "color"],
  27921. needAlphaBlending: true
  27922. });
  27923. }
  27924. Object.defineProperty(LinesMesh.prototype, "material", {
  27925. get: function () {
  27926. return this._colorShader;
  27927. },
  27928. enumerable: true,
  27929. configurable: true
  27930. });
  27931. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27932. get: function () {
  27933. return false;
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27939. get: function () {
  27940. return false;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27946. var engine = this.getScene().getEngine();
  27947. var indexToBind = this._geometry.getIndexBuffer();
  27948. // VBOs
  27949. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27950. // Color
  27951. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27952. };
  27953. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27954. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27955. return;
  27956. }
  27957. var engine = this.getScene().getEngine();
  27958. // Draw order
  27959. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27960. };
  27961. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27962. return null;
  27963. };
  27964. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27965. this._colorShader.dispose();
  27966. _super.prototype.dispose.call(this, doNotRecurse);
  27967. };
  27968. return LinesMesh;
  27969. })(BABYLON.Mesh);
  27970. BABYLON.LinesMesh = LinesMesh;
  27971. })(BABYLON || (BABYLON = {}));
  27972. //# sourceMappingURL=babylon.linesMesh.js.map
  27973. var BABYLON;
  27974. (function (BABYLON) {
  27975. var OutlineRenderer = (function () {
  27976. function OutlineRenderer(scene) {
  27977. this._scene = scene;
  27978. }
  27979. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27980. var _this = this;
  27981. if (useOverlay === void 0) { useOverlay = false; }
  27982. var scene = this._scene;
  27983. var engine = this._scene.getEngine();
  27984. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27985. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27986. return;
  27987. }
  27988. var mesh = subMesh.getRenderingMesh();
  27989. var material = subMesh.getMaterial();
  27990. engine.enableEffect(this._effect);
  27991. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27992. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27993. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27994. // Bones
  27995. if (mesh.useBones) {
  27996. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27997. }
  27998. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27999. // Alpha test
  28000. if (material && material.needAlphaTesting()) {
  28001. var alphaTexture = material.getAlphaTestTexture();
  28002. this._effect.setTexture("diffuseSampler", alphaTexture);
  28003. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28004. }
  28005. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  28006. _this._effect.setMatrix("world", world);
  28007. });
  28008. };
  28009. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28010. var defines = [];
  28011. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28012. var mesh = subMesh.getMesh();
  28013. var material = subMesh.getMaterial();
  28014. // Alpha test
  28015. if (material && material.needAlphaTesting()) {
  28016. defines.push("#define ALPHATEST");
  28017. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28018. attribs.push(BABYLON.VertexBuffer.UVKind);
  28019. defines.push("#define UV1");
  28020. }
  28021. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28022. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28023. defines.push("#define UV2");
  28024. }
  28025. }
  28026. // Bones
  28027. if (mesh.useBones) {
  28028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28030. defines.push("#define BONES");
  28031. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28032. }
  28033. // Instances
  28034. if (useInstances) {
  28035. defines.push("#define INSTANCES");
  28036. attribs.push("world0");
  28037. attribs.push("world1");
  28038. attribs.push("world2");
  28039. attribs.push("world3");
  28040. }
  28041. // Get correct effect
  28042. var join = defines.join("\n");
  28043. if (this._cachedDefines !== join) {
  28044. this._cachedDefines = join;
  28045. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28046. }
  28047. return this._effect.isReady();
  28048. };
  28049. return OutlineRenderer;
  28050. })();
  28051. BABYLON.OutlineRenderer = OutlineRenderer;
  28052. })(BABYLON || (BABYLON = {}));
  28053. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28054. var BABYLON;
  28055. (function (BABYLON) {
  28056. var MeshAssetTask = (function () {
  28057. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28058. this.name = name;
  28059. this.meshesNames = meshesNames;
  28060. this.rootUrl = rootUrl;
  28061. this.sceneFilename = sceneFilename;
  28062. this.isCompleted = false;
  28063. }
  28064. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28065. var _this = this;
  28066. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28067. _this.loadedMeshes = meshes;
  28068. _this.loadedParticleSystems = particleSystems;
  28069. _this.loadedSkeletons = skeletons;
  28070. _this.isCompleted = true;
  28071. if (_this.onSuccess) {
  28072. _this.onSuccess(_this);
  28073. }
  28074. onSuccess();
  28075. }, null, function () {
  28076. if (_this.onError) {
  28077. _this.onError(_this);
  28078. }
  28079. onError();
  28080. });
  28081. };
  28082. return MeshAssetTask;
  28083. })();
  28084. BABYLON.MeshAssetTask = MeshAssetTask;
  28085. var TextFileAssetTask = (function () {
  28086. function TextFileAssetTask(name, url) {
  28087. this.name = name;
  28088. this.url = url;
  28089. this.isCompleted = false;
  28090. }
  28091. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28092. var _this = this;
  28093. BABYLON.Tools.LoadFile(this.url, function (data) {
  28094. _this.text = data;
  28095. _this.isCompleted = true;
  28096. if (_this.onSuccess) {
  28097. _this.onSuccess(_this);
  28098. }
  28099. onSuccess();
  28100. }, null, scene.database, false, function () {
  28101. if (_this.onError) {
  28102. _this.onError(_this);
  28103. }
  28104. onError();
  28105. });
  28106. };
  28107. return TextFileAssetTask;
  28108. })();
  28109. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28110. var BinaryFileAssetTask = (function () {
  28111. function BinaryFileAssetTask(name, url) {
  28112. this.name = name;
  28113. this.url = url;
  28114. this.isCompleted = false;
  28115. }
  28116. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28117. var _this = this;
  28118. BABYLON.Tools.LoadFile(this.url, function (data) {
  28119. _this.data = data;
  28120. _this.isCompleted = true;
  28121. if (_this.onSuccess) {
  28122. _this.onSuccess(_this);
  28123. }
  28124. onSuccess();
  28125. }, null, scene.database, true, function () {
  28126. if (_this.onError) {
  28127. _this.onError(_this);
  28128. }
  28129. onError();
  28130. });
  28131. };
  28132. return BinaryFileAssetTask;
  28133. })();
  28134. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28135. var ImageAssetTask = (function () {
  28136. function ImageAssetTask(name, url) {
  28137. this.name = name;
  28138. this.url = url;
  28139. this.isCompleted = false;
  28140. }
  28141. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28142. var _this = this;
  28143. var img = new Image();
  28144. img.onload = function () {
  28145. _this.image = img;
  28146. _this.isCompleted = true;
  28147. if (_this.onSuccess) {
  28148. _this.onSuccess(_this);
  28149. }
  28150. onSuccess();
  28151. };
  28152. img.onerror = function () {
  28153. if (_this.onError) {
  28154. _this.onError(_this);
  28155. }
  28156. onError();
  28157. };
  28158. img.src = this.url;
  28159. };
  28160. return ImageAssetTask;
  28161. })();
  28162. BABYLON.ImageAssetTask = ImageAssetTask;
  28163. var TextureAssetTask = (function () {
  28164. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28165. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28166. this.name = name;
  28167. this.url = url;
  28168. this.noMipmap = noMipmap;
  28169. this.invertY = invertY;
  28170. this.samplingMode = samplingMode;
  28171. this.isCompleted = false;
  28172. }
  28173. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28174. var _this = this;
  28175. var onload = function () {
  28176. _this.isCompleted = true;
  28177. if (_this.onSuccess) {
  28178. _this.onSuccess(_this);
  28179. }
  28180. onSuccess();
  28181. };
  28182. var onerror = function () {
  28183. if (_this.onError) {
  28184. _this.onError(_this);
  28185. }
  28186. onError();
  28187. };
  28188. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28189. };
  28190. return TextureAssetTask;
  28191. })();
  28192. BABYLON.TextureAssetTask = TextureAssetTask;
  28193. var AssetsManager = (function () {
  28194. function AssetsManager(scene) {
  28195. this._tasks = new Array();
  28196. this._waitingTasksCount = 0;
  28197. this.useDefaultLoadingScreen = true;
  28198. this._scene = scene;
  28199. }
  28200. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28201. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28202. this._tasks.push(task);
  28203. return task;
  28204. };
  28205. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28206. var task = new TextFileAssetTask(taskName, url);
  28207. this._tasks.push(task);
  28208. return task;
  28209. };
  28210. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28211. var task = new BinaryFileAssetTask(taskName, url);
  28212. this._tasks.push(task);
  28213. return task;
  28214. };
  28215. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28216. var task = new ImageAssetTask(taskName, url);
  28217. this._tasks.push(task);
  28218. return task;
  28219. };
  28220. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28222. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28223. this._tasks.push(task);
  28224. return task;
  28225. };
  28226. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28227. this._waitingTasksCount--;
  28228. if (this._waitingTasksCount === 0) {
  28229. if (this.onFinish) {
  28230. this.onFinish(this._tasks);
  28231. }
  28232. this._scene.getEngine().hideLoadingUI();
  28233. }
  28234. };
  28235. AssetsManager.prototype._runTask = function (task) {
  28236. var _this = this;
  28237. task.run(this._scene, function () {
  28238. if (_this.onTaskSuccess) {
  28239. _this.onTaskSuccess(task);
  28240. }
  28241. _this._decreaseWaitingTasksCount();
  28242. }, function () {
  28243. if (_this.onTaskError) {
  28244. _this.onTaskError(task);
  28245. }
  28246. _this._decreaseWaitingTasksCount();
  28247. });
  28248. };
  28249. AssetsManager.prototype.reset = function () {
  28250. this._tasks = new Array();
  28251. return this;
  28252. };
  28253. AssetsManager.prototype.load = function () {
  28254. this._waitingTasksCount = this._tasks.length;
  28255. if (this._waitingTasksCount === 0) {
  28256. if (this.onFinish) {
  28257. this.onFinish(this._tasks);
  28258. }
  28259. return this;
  28260. }
  28261. if (this.useDefaultLoadingScreen) {
  28262. this._scene.getEngine().displayLoadingUI();
  28263. }
  28264. for (var index = 0; index < this._tasks.length; index++) {
  28265. var task = this._tasks[index];
  28266. this._runTask(task);
  28267. }
  28268. return this;
  28269. };
  28270. return AssetsManager;
  28271. })();
  28272. BABYLON.AssetsManager = AssetsManager;
  28273. })(BABYLON || (BABYLON = {}));
  28274. //# sourceMappingURL=babylon.assetsManager.js.map
  28275. var __extends = this.__extends || function (d, b) {
  28276. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28277. function __() { this.constructor = d; }
  28278. __.prototype = b.prototype;
  28279. d.prototype = new __();
  28280. };
  28281. var BABYLON;
  28282. (function (BABYLON) {
  28283. var VRDeviceOrientationFreeCamera = (function (_super) {
  28284. __extends(VRDeviceOrientationFreeCamera, _super);
  28285. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28286. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28287. _super.call(this, name, position, scene);
  28288. this._alpha = 0;
  28289. this._beta = 0;
  28290. this._gamma = 0;
  28291. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28292. metrics.compensateDistorsion = compensateDistorsion;
  28293. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28294. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28295. }
  28296. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28297. this._alpha = +evt.alpha | 0;
  28298. this._beta = +evt.beta | 0;
  28299. this._gamma = +evt.gamma | 0;
  28300. if (this._gamma < 0) {
  28301. this._gamma = 90 + this._gamma;
  28302. }
  28303. else {
  28304. // Incline it in the correct angle.
  28305. this._gamma = 270 - this._gamma;
  28306. }
  28307. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28308. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28309. this.rotation.z = this._beta / 180.0 * Math.PI;
  28310. };
  28311. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28312. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28313. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28314. };
  28315. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28316. _super.prototype.detachControl.call(this, element);
  28317. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28318. };
  28319. return VRDeviceOrientationFreeCamera;
  28320. })(BABYLON.FreeCamera);
  28321. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28322. })(BABYLON || (BABYLON = {}));
  28323. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28324. var __extends = this.__extends || function (d, b) {
  28325. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28326. function __() { this.constructor = d; }
  28327. __.prototype = b.prototype;
  28328. d.prototype = new __();
  28329. };
  28330. var BABYLON;
  28331. (function (BABYLON) {
  28332. var WebVRFreeCamera = (function (_super) {
  28333. __extends(WebVRFreeCamera, _super);
  28334. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28335. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28336. _super.call(this, name, position, scene);
  28337. this._hmdDevice = null;
  28338. this._sensorDevice = null;
  28339. this._cacheState = null;
  28340. this._cacheQuaternion = new BABYLON.Quaternion();
  28341. this._cacheRotation = BABYLON.Vector3.Zero();
  28342. this._vrEnabled = false;
  28343. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28344. metrics.compensateDistorsion = compensateDistorsion;
  28345. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28346. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28347. }
  28348. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28349. var size = devices.length;
  28350. var i = 0;
  28351. // Reset devices.
  28352. this._sensorDevice = null;
  28353. this._hmdDevice = null;
  28354. while (i < size && this._hmdDevice === null) {
  28355. if (devices[i] instanceof HMDVRDevice) {
  28356. this._hmdDevice = devices[i];
  28357. }
  28358. i++;
  28359. }
  28360. i = 0;
  28361. while (i < size && this._sensorDevice === null) {
  28362. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28363. this._sensorDevice = devices[i];
  28364. }
  28365. i++;
  28366. }
  28367. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28368. };
  28369. WebVRFreeCamera.prototype._checkInputs = function () {
  28370. if (this._vrEnabled) {
  28371. this._cacheState = this._sensorDevice.getState();
  28372. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28373. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28374. this.rotation.x = -this._cacheRotation.z;
  28375. this.rotation.y = -this._cacheRotation.y;
  28376. this.rotation.z = this._cacheRotation.x;
  28377. }
  28378. _super.prototype._checkInputs.call(this);
  28379. };
  28380. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28381. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28382. if (navigator.getVRDevices) {
  28383. navigator.getVRDevices().then(this._getWebVRDevices);
  28384. }
  28385. else if (navigator.mozGetVRDevices) {
  28386. navigator.mozGetVRDevices(this._getWebVRDevices);
  28387. }
  28388. };
  28389. WebVRFreeCamera.prototype.detachControl = function (element) {
  28390. _super.prototype.detachControl.call(this, element);
  28391. this._vrEnabled = false;
  28392. };
  28393. return WebVRFreeCamera;
  28394. })(BABYLON.FreeCamera);
  28395. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28396. })(BABYLON || (BABYLON = {}));
  28397. //# sourceMappingURL=babylon.webVRCamera.js.map
  28398. var __extends = this.__extends || function (d, b) {
  28399. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28400. function __() { this.constructor = d; }
  28401. __.prototype = b.prototype;
  28402. d.prototype = new __();
  28403. };
  28404. var BABYLON;
  28405. (function (BABYLON) {
  28406. // Standard optimizations
  28407. var SceneOptimization = (function () {
  28408. function SceneOptimization(priority) {
  28409. if (priority === void 0) { priority = 0; }
  28410. this.priority = priority;
  28411. this.apply = function (scene) {
  28412. return true; // Return true if everything that can be done was applied
  28413. };
  28414. }
  28415. return SceneOptimization;
  28416. })();
  28417. BABYLON.SceneOptimization = SceneOptimization;
  28418. var TextureOptimization = (function (_super) {
  28419. __extends(TextureOptimization, _super);
  28420. function TextureOptimization(priority, maximumSize) {
  28421. var _this = this;
  28422. if (priority === void 0) { priority = 0; }
  28423. if (maximumSize === void 0) { maximumSize = 1024; }
  28424. _super.call(this, priority);
  28425. this.priority = priority;
  28426. this.maximumSize = maximumSize;
  28427. this.apply = function (scene) {
  28428. var allDone = true;
  28429. for (var index = 0; index < scene.textures.length; index++) {
  28430. var texture = scene.textures[index];
  28431. if (!texture.canRescale) {
  28432. continue;
  28433. }
  28434. var currentSize = texture.getSize();
  28435. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28436. if (maxDimension > _this.maximumSize) {
  28437. texture.scale(0.5);
  28438. allDone = false;
  28439. }
  28440. }
  28441. return allDone;
  28442. };
  28443. }
  28444. return TextureOptimization;
  28445. })(SceneOptimization);
  28446. BABYLON.TextureOptimization = TextureOptimization;
  28447. var HardwareScalingOptimization = (function (_super) {
  28448. __extends(HardwareScalingOptimization, _super);
  28449. function HardwareScalingOptimization(priority, maximumScale) {
  28450. var _this = this;
  28451. if (priority === void 0) { priority = 0; }
  28452. if (maximumScale === void 0) { maximumScale = 2; }
  28453. _super.call(this, priority);
  28454. this.priority = priority;
  28455. this.maximumScale = maximumScale;
  28456. this._currentScale = 1;
  28457. this.apply = function (scene) {
  28458. _this._currentScale++;
  28459. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28460. return _this._currentScale >= _this.maximumScale;
  28461. };
  28462. }
  28463. return HardwareScalingOptimization;
  28464. })(SceneOptimization);
  28465. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28466. var ShadowsOptimization = (function (_super) {
  28467. __extends(ShadowsOptimization, _super);
  28468. function ShadowsOptimization() {
  28469. _super.apply(this, arguments);
  28470. this.apply = function (scene) {
  28471. scene.shadowsEnabled = false;
  28472. return true;
  28473. };
  28474. }
  28475. return ShadowsOptimization;
  28476. })(SceneOptimization);
  28477. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28478. var PostProcessesOptimization = (function (_super) {
  28479. __extends(PostProcessesOptimization, _super);
  28480. function PostProcessesOptimization() {
  28481. _super.apply(this, arguments);
  28482. this.apply = function (scene) {
  28483. scene.postProcessesEnabled = false;
  28484. return true;
  28485. };
  28486. }
  28487. return PostProcessesOptimization;
  28488. })(SceneOptimization);
  28489. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28490. var LensFlaresOptimization = (function (_super) {
  28491. __extends(LensFlaresOptimization, _super);
  28492. function LensFlaresOptimization() {
  28493. _super.apply(this, arguments);
  28494. this.apply = function (scene) {
  28495. scene.lensFlaresEnabled = false;
  28496. return true;
  28497. };
  28498. }
  28499. return LensFlaresOptimization;
  28500. })(SceneOptimization);
  28501. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28502. var ParticlesOptimization = (function (_super) {
  28503. __extends(ParticlesOptimization, _super);
  28504. function ParticlesOptimization() {
  28505. _super.apply(this, arguments);
  28506. this.apply = function (scene) {
  28507. scene.particlesEnabled = false;
  28508. return true;
  28509. };
  28510. }
  28511. return ParticlesOptimization;
  28512. })(SceneOptimization);
  28513. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28514. var RenderTargetsOptimization = (function (_super) {
  28515. __extends(RenderTargetsOptimization, _super);
  28516. function RenderTargetsOptimization() {
  28517. _super.apply(this, arguments);
  28518. this.apply = function (scene) {
  28519. scene.renderTargetsEnabled = false;
  28520. return true;
  28521. };
  28522. }
  28523. return RenderTargetsOptimization;
  28524. })(SceneOptimization);
  28525. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28526. var MergeMeshesOptimization = (function (_super) {
  28527. __extends(MergeMeshesOptimization, _super);
  28528. function MergeMeshesOptimization() {
  28529. var _this = this;
  28530. _super.apply(this, arguments);
  28531. this._canBeMerged = function (abstractMesh) {
  28532. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28533. return false;
  28534. }
  28535. var mesh = abstractMesh;
  28536. if (!mesh.isVisible || !mesh.isEnabled()) {
  28537. return false;
  28538. }
  28539. if (mesh.instances.length > 0) {
  28540. return false;
  28541. }
  28542. if (mesh.skeleton || mesh.hasLODLevels) {
  28543. return false;
  28544. }
  28545. return true;
  28546. };
  28547. this.apply = function (scene) {
  28548. var globalPool = scene.meshes.slice(0);
  28549. var globalLength = globalPool.length;
  28550. for (var index = 0; index < globalLength; index++) {
  28551. var currentPool = new Array();
  28552. var current = globalPool[index];
  28553. // Checks
  28554. if (!_this._canBeMerged(current)) {
  28555. continue;
  28556. }
  28557. currentPool.push(current);
  28558. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28559. var otherMesh = globalPool[subIndex];
  28560. if (!_this._canBeMerged(otherMesh)) {
  28561. continue;
  28562. }
  28563. if (otherMesh.material !== current.material) {
  28564. continue;
  28565. }
  28566. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28567. continue;
  28568. }
  28569. currentPool.push(otherMesh);
  28570. globalLength--;
  28571. globalPool.splice(subIndex, 1);
  28572. subIndex--;
  28573. }
  28574. if (currentPool.length < 2) {
  28575. continue;
  28576. }
  28577. // Merge meshes
  28578. BABYLON.Mesh.MergeMeshes(currentPool);
  28579. }
  28580. return true;
  28581. };
  28582. }
  28583. return MergeMeshesOptimization;
  28584. })(SceneOptimization);
  28585. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28586. // Options
  28587. var SceneOptimizerOptions = (function () {
  28588. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28589. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28590. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28591. this.targetFrameRate = targetFrameRate;
  28592. this.trackerDuration = trackerDuration;
  28593. this.optimizations = new Array();
  28594. }
  28595. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28596. var result = new SceneOptimizerOptions(targetFrameRate);
  28597. var priority = 0;
  28598. result.optimizations.push(new MergeMeshesOptimization(priority));
  28599. result.optimizations.push(new ShadowsOptimization(priority));
  28600. result.optimizations.push(new LensFlaresOptimization(priority));
  28601. // Next priority
  28602. priority++;
  28603. result.optimizations.push(new PostProcessesOptimization(priority));
  28604. result.optimizations.push(new ParticlesOptimization(priority));
  28605. // Next priority
  28606. priority++;
  28607. result.optimizations.push(new TextureOptimization(priority, 1024));
  28608. return result;
  28609. };
  28610. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28611. var result = new SceneOptimizerOptions(targetFrameRate);
  28612. var priority = 0;
  28613. result.optimizations.push(new MergeMeshesOptimization(priority));
  28614. result.optimizations.push(new ShadowsOptimization(priority));
  28615. result.optimizations.push(new LensFlaresOptimization(priority));
  28616. // Next priority
  28617. priority++;
  28618. result.optimizations.push(new PostProcessesOptimization(priority));
  28619. result.optimizations.push(new ParticlesOptimization(priority));
  28620. // Next priority
  28621. priority++;
  28622. result.optimizations.push(new TextureOptimization(priority, 512));
  28623. // Next priority
  28624. priority++;
  28625. result.optimizations.push(new RenderTargetsOptimization(priority));
  28626. // Next priority
  28627. priority++;
  28628. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28629. return result;
  28630. };
  28631. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28632. var result = new SceneOptimizerOptions(targetFrameRate);
  28633. var priority = 0;
  28634. result.optimizations.push(new MergeMeshesOptimization(priority));
  28635. result.optimizations.push(new ShadowsOptimization(priority));
  28636. result.optimizations.push(new LensFlaresOptimization(priority));
  28637. // Next priority
  28638. priority++;
  28639. result.optimizations.push(new PostProcessesOptimization(priority));
  28640. result.optimizations.push(new ParticlesOptimization(priority));
  28641. // Next priority
  28642. priority++;
  28643. result.optimizations.push(new TextureOptimization(priority, 256));
  28644. // Next priority
  28645. priority++;
  28646. result.optimizations.push(new RenderTargetsOptimization(priority));
  28647. // Next priority
  28648. priority++;
  28649. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28650. return result;
  28651. };
  28652. return SceneOptimizerOptions;
  28653. })();
  28654. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28655. // Scene optimizer tool
  28656. var SceneOptimizer = (function () {
  28657. function SceneOptimizer() {
  28658. }
  28659. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28660. // TODO: add an epsilon
  28661. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28662. if (onSuccess) {
  28663. onSuccess();
  28664. }
  28665. return;
  28666. }
  28667. // Apply current level of optimizations
  28668. var allDone = true;
  28669. var noOptimizationApplied = true;
  28670. for (var index = 0; index < options.optimizations.length; index++) {
  28671. var optimization = options.optimizations[index];
  28672. if (optimization.priority === currentPriorityLevel) {
  28673. noOptimizationApplied = false;
  28674. allDone = allDone && optimization.apply(scene);
  28675. }
  28676. }
  28677. // If no optimization was applied, this is a failure :(
  28678. if (noOptimizationApplied) {
  28679. if (onFailure) {
  28680. onFailure();
  28681. }
  28682. return;
  28683. }
  28684. // If all optimizations were done, move to next level
  28685. if (allDone) {
  28686. currentPriorityLevel++;
  28687. }
  28688. // Let's the system running for a specific amount of time before checking FPS
  28689. scene.executeWhenReady(function () {
  28690. setTimeout(function () {
  28691. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28692. }, options.trackerDuration);
  28693. });
  28694. };
  28695. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28696. if (!options) {
  28697. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28698. }
  28699. // Let's the system running for a specific amount of time before checking FPS
  28700. scene.executeWhenReady(function () {
  28701. setTimeout(function () {
  28702. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28703. }, options.trackerDuration);
  28704. });
  28705. };
  28706. return SceneOptimizer;
  28707. })();
  28708. BABYLON.SceneOptimizer = SceneOptimizer;
  28709. })(BABYLON || (BABYLON = {}));
  28710. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28711. var BABYLON;
  28712. (function (BABYLON) {
  28713. var Internals;
  28714. (function (Internals) {
  28715. var MeshLODLevel = (function () {
  28716. function MeshLODLevel(distance, mesh) {
  28717. this.distance = distance;
  28718. this.mesh = mesh;
  28719. }
  28720. return MeshLODLevel;
  28721. })();
  28722. Internals.MeshLODLevel = MeshLODLevel;
  28723. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28724. })(BABYLON || (BABYLON = {}));
  28725. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28726. var BABYLON;
  28727. (function (BABYLON) {
  28728. var AudioEngine = (function () {
  28729. function AudioEngine() {
  28730. this._audioContext = null;
  28731. this._audioContextInitialized = false;
  28732. this.canUseWebAudio = false;
  28733. this.WarnedWebAudioUnsupported = false;
  28734. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28735. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28736. this.canUseWebAudio = true;
  28737. }
  28738. }
  28739. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28740. get: function () {
  28741. if (!this._audioContextInitialized) {
  28742. this._initializeAudioContext();
  28743. }
  28744. return this._audioContext;
  28745. },
  28746. enumerable: true,
  28747. configurable: true
  28748. });
  28749. AudioEngine.prototype._initializeAudioContext = function () {
  28750. try {
  28751. if (this.canUseWebAudio) {
  28752. this._audioContext = new AudioContext();
  28753. // create a global volume gain node
  28754. this.masterGain = this._audioContext.createGain();
  28755. this.masterGain.gain.value = 1;
  28756. this.masterGain.connect(this._audioContext.destination);
  28757. this._audioContextInitialized = true;
  28758. }
  28759. }
  28760. catch (e) {
  28761. this.canUseWebAudio = false;
  28762. BABYLON.Tools.Error("Web Audio: " + e.message);
  28763. }
  28764. };
  28765. AudioEngine.prototype.dispose = function () {
  28766. if (this.canUseWebAudio && this._audioContextInitialized) {
  28767. if (this._connectedAnalyser) {
  28768. this._connectedAnalyser.stopDebugCanvas();
  28769. this._connectedAnalyser.dispose();
  28770. this.masterGain.disconnect();
  28771. this.masterGain.connect(this._audioContext.destination);
  28772. this._connectedAnalyser = null;
  28773. }
  28774. this.masterGain.gain.value = 1;
  28775. }
  28776. this.WarnedWebAudioUnsupported = false;
  28777. };
  28778. AudioEngine.prototype.getGlobalVolume = function () {
  28779. if (this.canUseWebAudio && this._audioContextInitialized) {
  28780. return this.masterGain.gain.value;
  28781. }
  28782. else {
  28783. return -1;
  28784. }
  28785. };
  28786. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28787. if (this.canUseWebAudio && this._audioContextInitialized) {
  28788. this.masterGain.gain.value = newVolume;
  28789. }
  28790. };
  28791. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28792. if (this._connectedAnalyser) {
  28793. this._connectedAnalyser.stopDebugCanvas();
  28794. }
  28795. if (this.canUseWebAudio && this._audioContextInitialized) {
  28796. this._connectedAnalyser = analyser;
  28797. this.masterGain.disconnect();
  28798. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28799. }
  28800. };
  28801. return AudioEngine;
  28802. })();
  28803. BABYLON.AudioEngine = AudioEngine;
  28804. })(BABYLON || (BABYLON = {}));
  28805. //# sourceMappingURL=babylon.audioEngine.js.map
  28806. var BABYLON;
  28807. (function (BABYLON) {
  28808. var Sound = (function () {
  28809. /**
  28810. * Create a sound and attach it to a scene
  28811. * @param name Name of your sound
  28812. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28813. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28814. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28815. */
  28816. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28817. var _this = this;
  28818. this.autoplay = false;
  28819. this.loop = false;
  28820. this.useCustomAttenuation = false;
  28821. this.spatialSound = false;
  28822. this.refDistance = 1;
  28823. this.rolloffFactor = 1;
  28824. this.maxDistance = 100;
  28825. this.distanceModel = "linear";
  28826. this._panningModel = "equalpower";
  28827. this._playbackRate = 1;
  28828. this._startTime = 0;
  28829. this._startOffset = 0;
  28830. this._position = BABYLON.Vector3.Zero();
  28831. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28832. this._volume = 1;
  28833. this._isLoaded = false;
  28834. this._isReadyToPlay = false;
  28835. this.isPlaying = false;
  28836. this.isPaused = false;
  28837. this._isDirectional = false;
  28838. // Used if you'd like to create a directional sound.
  28839. // If not set, the sound will be omnidirectional
  28840. this._coneInnerAngle = 360;
  28841. this._coneOuterAngle = 360;
  28842. this._coneOuterGain = 0;
  28843. this.name = name;
  28844. this._scene = scene;
  28845. this._readyToPlayCallback = readyToPlayCallback;
  28846. // Default custom attenuation function is a linear attenuation
  28847. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28848. if (currentDistance < maxDistance) {
  28849. return currentVolume * (1 - currentDistance / maxDistance);
  28850. }
  28851. else {
  28852. return 0;
  28853. }
  28854. };
  28855. if (options) {
  28856. this.autoplay = options.autoplay || false;
  28857. this.loop = options.loop || false;
  28858. // if volume === 0, we need another way to check this option
  28859. if (options.volume !== undefined) {
  28860. this._volume = options.volume;
  28861. }
  28862. this.spatialSound = options.spatialSound || false;
  28863. this.maxDistance = options.maxDistance || 100;
  28864. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28865. this.rolloffFactor = options.rolloffFactor || 1;
  28866. this.refDistance = options.refDistance || 1;
  28867. this.distanceModel = options.distanceModel || "linear";
  28868. this._playbackRate = options.playbackRate || 1;
  28869. }
  28870. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28871. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28872. this._soundGain.gain.value = this._volume;
  28873. this._inputAudioNode = this._soundGain;
  28874. this._ouputAudioNode = this._soundGain;
  28875. if (this.spatialSound) {
  28876. this._createSpatialParameters();
  28877. }
  28878. this._scene.mainSoundTrack.AddSound(this);
  28879. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28880. if (urlOrArrayBuffer) {
  28881. // If it's an URL
  28882. if (typeof (urlOrArrayBuffer) === "string") {
  28883. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28884. _this._soundLoaded(data);
  28885. }, null, null, true);
  28886. }
  28887. else {
  28888. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28889. this._soundLoaded(urlOrArrayBuffer);
  28890. }
  28891. else {
  28892. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28893. }
  28894. }
  28895. }
  28896. }
  28897. else {
  28898. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28899. this._scene.mainSoundTrack.AddSound(this);
  28900. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28901. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28902. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28903. }
  28904. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28905. if (this._readyToPlayCallback) {
  28906. window.setTimeout(function () {
  28907. _this._readyToPlayCallback();
  28908. }, 1000);
  28909. }
  28910. }
  28911. }
  28912. Sound.prototype.dispose = function () {
  28913. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28914. if (this.isPlaying) {
  28915. this.stop();
  28916. }
  28917. this._isReadyToPlay = false;
  28918. if (this.soundTrackId === -1) {
  28919. this._scene.mainSoundTrack.RemoveSound(this);
  28920. }
  28921. else {
  28922. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28923. }
  28924. if (this._soundGain) {
  28925. this._soundGain.disconnect();
  28926. this._soundGain = null;
  28927. }
  28928. if (this._soundPanner) {
  28929. this._soundPanner.disconnect();
  28930. this._soundPanner = null;
  28931. }
  28932. if (this._soundSource) {
  28933. this._soundSource.disconnect();
  28934. this._soundSource = null;
  28935. }
  28936. this._audioBuffer = null;
  28937. if (this._connectedMesh) {
  28938. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28939. this._connectedMesh = null;
  28940. }
  28941. }
  28942. };
  28943. Sound.prototype._soundLoaded = function (audioData) {
  28944. var _this = this;
  28945. this._isLoaded = true;
  28946. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28947. _this._audioBuffer = buffer;
  28948. _this._isReadyToPlay = true;
  28949. if (_this.autoplay) {
  28950. _this.play();
  28951. }
  28952. if (_this._readyToPlayCallback) {
  28953. _this._readyToPlayCallback();
  28954. }
  28955. }, function (error) {
  28956. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28957. });
  28958. };
  28959. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28960. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28961. this._audioBuffer = audioBuffer;
  28962. this._isReadyToPlay = true;
  28963. }
  28964. };
  28965. Sound.prototype.updateOptions = function (options) {
  28966. if (options) {
  28967. this.loop = options.loop || this.loop;
  28968. this.maxDistance = options.maxDistance || this.maxDistance;
  28969. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28970. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28971. this.refDistance = options.refDistance || this.refDistance;
  28972. this.distanceModel = options.distanceModel || this.distanceModel;
  28973. this._playbackRate = options.playbackRate || this._playbackRate;
  28974. }
  28975. };
  28976. Sound.prototype._createSpatialParameters = function () {
  28977. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28978. if (this._scene.headphone) {
  28979. this._panningModel = "HRTF";
  28980. }
  28981. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28982. if (this.useCustomAttenuation) {
  28983. // Tricks to disable in a way embedded Web Audio attenuation
  28984. this._soundPanner.distanceModel = "linear";
  28985. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28986. this._soundPanner.refDistance = 1;
  28987. this._soundPanner.rolloffFactor = 1;
  28988. this._soundPanner.panningModel = this._panningModel;
  28989. }
  28990. else {
  28991. this._soundPanner.distanceModel = this.distanceModel;
  28992. this._soundPanner.maxDistance = this.maxDistance;
  28993. this._soundPanner.refDistance = this.refDistance;
  28994. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28995. this._soundPanner.panningModel = this._panningModel;
  28996. }
  28997. this._soundPanner.connect(this._ouputAudioNode);
  28998. this._inputAudioNode = this._soundPanner;
  28999. }
  29000. };
  29001. Sound.prototype.switchPanningModelToHRTF = function () {
  29002. this._panningModel = "HRTF";
  29003. this._switchPanningModel();
  29004. };
  29005. Sound.prototype.switchPanningModelToEqualPower = function () {
  29006. this._panningModel = "equalpower";
  29007. this._switchPanningModel();
  29008. };
  29009. Sound.prototype._switchPanningModel = function () {
  29010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29011. this._soundPanner.panningModel = this._panningModel;
  29012. }
  29013. };
  29014. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29015. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29016. this._ouputAudioNode.disconnect();
  29017. this._ouputAudioNode.connect(soundTrackAudioNode);
  29018. }
  29019. };
  29020. /**
  29021. * Transform this sound into a directional source
  29022. * @param coneInnerAngle Size of the inner cone in degree
  29023. * @param coneOuterAngle Size of the outer cone in degree
  29024. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29025. */
  29026. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29027. if (coneOuterAngle < coneInnerAngle) {
  29028. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29029. return;
  29030. }
  29031. this._coneInnerAngle = coneInnerAngle;
  29032. this._coneOuterAngle = coneOuterAngle;
  29033. this._coneOuterGain = coneOuterGain;
  29034. this._isDirectional = true;
  29035. if (this.isPlaying && this.loop) {
  29036. this.stop();
  29037. this.play();
  29038. }
  29039. };
  29040. Sound.prototype.setPosition = function (newPosition) {
  29041. this._position = newPosition;
  29042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29043. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29044. }
  29045. };
  29046. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29047. this._localDirection = newLocalDirection;
  29048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29049. this._updateDirection();
  29050. }
  29051. };
  29052. Sound.prototype._updateDirection = function () {
  29053. var mat = this._connectedMesh.getWorldMatrix();
  29054. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29055. direction.normalize();
  29056. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29057. };
  29058. Sound.prototype.updateDistanceFromListener = function () {
  29059. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29060. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29061. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29062. }
  29063. };
  29064. Sound.prototype.setAttenuationFunction = function (callback) {
  29065. this._customAttenuationFunction = callback;
  29066. };
  29067. /**
  29068. * Play the sound
  29069. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29070. */
  29071. Sound.prototype.play = function (time) {
  29072. var _this = this;
  29073. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29074. try {
  29075. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29076. if (!this._soundSource) {
  29077. if (this.spatialSound) {
  29078. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29079. if (this._isDirectional) {
  29080. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29081. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29082. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29083. if (this._connectedMesh) {
  29084. this._updateDirection();
  29085. }
  29086. else {
  29087. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29088. }
  29089. }
  29090. }
  29091. }
  29092. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29093. this._soundSource.buffer = this._audioBuffer;
  29094. this._soundSource.connect(this._inputAudioNode);
  29095. this._soundSource.loop = this.loop;
  29096. this._soundSource.playbackRate.value = this._playbackRate;
  29097. this._startTime = startTime;
  29098. this._soundSource.onended = function () {
  29099. _this._onended();
  29100. };
  29101. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29102. this.isPlaying = true;
  29103. this.isPaused = false;
  29104. }
  29105. catch (ex) {
  29106. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29107. }
  29108. }
  29109. };
  29110. Sound.prototype._onended = function () {
  29111. this.isPlaying = false;
  29112. if (this.onended) {
  29113. this.onended();
  29114. }
  29115. };
  29116. /**
  29117. * Stop the sound
  29118. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29119. */
  29120. Sound.prototype.stop = function (time) {
  29121. if (this.isPlaying) {
  29122. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29123. this._soundSource.stop(stopTime);
  29124. this.isPlaying = false;
  29125. }
  29126. };
  29127. Sound.prototype.pause = function () {
  29128. if (this.isPlaying) {
  29129. this.stop(0);
  29130. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29131. this.isPaused = true;
  29132. }
  29133. };
  29134. Sound.prototype.setVolume = function (newVolume, time) {
  29135. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  29136. if (time) {
  29137. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29138. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29139. }
  29140. else {
  29141. this._soundGain.gain.value = newVolume;
  29142. }
  29143. }
  29144. this._volume = newVolume;
  29145. };
  29146. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29147. this._playbackRate = newPlaybackRate;
  29148. if (this.isPlaying) {
  29149. this._soundSource.playbackRate.value = this._playbackRate;
  29150. }
  29151. };
  29152. Sound.prototype.getVolume = function () {
  29153. return this._volume;
  29154. };
  29155. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29156. var _this = this;
  29157. this._connectedMesh = meshToConnectTo;
  29158. if (!this.spatialSound) {
  29159. this._createSpatialParameters();
  29160. this.spatialSound = true;
  29161. if (this.isPlaying && this.loop) {
  29162. this.stop();
  29163. this.play();
  29164. }
  29165. }
  29166. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29167. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29168. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29169. };
  29170. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29171. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29172. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29173. this._updateDirection();
  29174. }
  29175. };
  29176. return Sound;
  29177. })();
  29178. BABYLON.Sound = Sound;
  29179. })(BABYLON || (BABYLON = {}));
  29180. //# sourceMappingURL=babylon.sound.js.map
  29181. var BABYLON;
  29182. (function (BABYLON) {
  29183. var SoundTrack = (function () {
  29184. function SoundTrack(scene, options) {
  29185. this.id = -1;
  29186. this._isMainTrack = false;
  29187. this._scene = scene;
  29188. this._audioEngine = BABYLON.Engine.audioEngine;
  29189. this.soundCollection = new Array();
  29190. if (this._audioEngine.canUseWebAudio) {
  29191. this._trackGain = this._audioEngine.audioContext.createGain();
  29192. this._trackGain.connect(this._audioEngine.masterGain);
  29193. if (options) {
  29194. if (options.volume) {
  29195. this._trackGain.gain.value = options.volume;
  29196. }
  29197. if (options.mainTrack) {
  29198. this._isMainTrack = options.mainTrack;
  29199. }
  29200. }
  29201. }
  29202. if (!this._isMainTrack) {
  29203. this._scene.soundTracks.push(this);
  29204. this.id = this._scene.soundTracks.length - 1;
  29205. }
  29206. }
  29207. SoundTrack.prototype.dispose = function () {
  29208. if (this._audioEngine.canUseWebAudio) {
  29209. if (this._connectedAnalyser) {
  29210. this._connectedAnalyser.stopDebugCanvas();
  29211. }
  29212. while (this.soundCollection.length) {
  29213. this.soundCollection[0].dispose();
  29214. }
  29215. this._trackGain.disconnect();
  29216. this._trackGain = null;
  29217. }
  29218. };
  29219. SoundTrack.prototype.AddSound = function (sound) {
  29220. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29221. sound.connectToSoundTrackAudioNode(this._trackGain);
  29222. }
  29223. if (sound.soundTrackId) {
  29224. if (sound.soundTrackId === -1) {
  29225. this._scene.mainSoundTrack.RemoveSound(sound);
  29226. }
  29227. else {
  29228. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29229. }
  29230. }
  29231. this.soundCollection.push(sound);
  29232. sound.soundTrackId = this.id;
  29233. };
  29234. SoundTrack.prototype.RemoveSound = function (sound) {
  29235. var index = this.soundCollection.indexOf(sound);
  29236. if (index !== -1) {
  29237. this.soundCollection.splice(index, 1);
  29238. }
  29239. };
  29240. SoundTrack.prototype.setVolume = function (newVolume) {
  29241. if (this._audioEngine.canUseWebAudio) {
  29242. this._trackGain.gain.value = newVolume;
  29243. }
  29244. };
  29245. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29246. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29247. for (var i = 0; i < this.soundCollection.length; i++) {
  29248. this.soundCollection[i].switchPanningModelToHRTF();
  29249. }
  29250. }
  29251. };
  29252. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29253. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29254. for (var i = 0; i < this.soundCollection.length; i++) {
  29255. this.soundCollection[i].switchPanningModelToEqualPower();
  29256. }
  29257. }
  29258. };
  29259. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29260. if (this._connectedAnalyser) {
  29261. this._connectedAnalyser.stopDebugCanvas();
  29262. }
  29263. this._connectedAnalyser = analyser;
  29264. if (this._audioEngine.canUseWebAudio) {
  29265. this._trackGain.disconnect();
  29266. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  29267. }
  29268. };
  29269. return SoundTrack;
  29270. })();
  29271. BABYLON.SoundTrack = SoundTrack;
  29272. })(BABYLON || (BABYLON = {}));
  29273. //# sourceMappingURL=babylon.soundtrack.js.map
  29274. var BABYLON;
  29275. (function (BABYLON) {
  29276. var DebugLayer = (function () {
  29277. function DebugLayer(scene) {
  29278. var _this = this;
  29279. this._transformationMatrix = BABYLON.Matrix.Identity();
  29280. this._enabled = false;
  29281. this._labelsEnabled = false;
  29282. this._displayStatistics = true;
  29283. this._displayTree = false;
  29284. this._displayLogs = false;
  29285. this._identityMatrix = BABYLON.Matrix.Identity();
  29286. this.axisRatio = 0.02;
  29287. this.accentColor = "orange";
  29288. this._scene = scene;
  29289. this._syncPositions = function () {
  29290. var engine = _this._scene.getEngine();
  29291. var canvasRect = engine.getRenderingCanvasClientRect();
  29292. if (_this._showUI) {
  29293. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29294. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29295. _this._statsDiv.style.width = "400px";
  29296. _this._statsDiv.style.height = "auto";
  29297. _this._statsSubsetDiv.style.maxHeight = "240px";
  29298. _this._optionsDiv.style.left = "0px";
  29299. _this._optionsDiv.style.top = "10px";
  29300. _this._optionsDiv.style.width = "200px";
  29301. _this._optionsDiv.style.height = "auto";
  29302. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29303. _this._logDiv.style.left = "0px";
  29304. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29305. _this._logDiv.style.width = "600px";
  29306. _this._logDiv.style.height = "160px";
  29307. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29308. _this._treeDiv.style.top = "10px";
  29309. _this._treeDiv.style.width = "300px";
  29310. _this._treeDiv.style.height = "auto";
  29311. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29312. }
  29313. _this._globalDiv.style.left = canvasRect.left + "px";
  29314. _this._globalDiv.style.top = canvasRect.top + "px";
  29315. _this._drawingCanvas.style.left = "0px";
  29316. _this._drawingCanvas.style.top = "0px";
  29317. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29318. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29319. var devicePixelRatio = window.devicePixelRatio || 1;
  29320. var context = _this._drawingContext;
  29321. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29322. _this._ratio = devicePixelRatio / backingStoreRatio;
  29323. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29324. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29325. };
  29326. this._onCanvasClick = function (evt) {
  29327. _this._clickPosition = {
  29328. x: evt.clientX * _this._ratio,
  29329. y: evt.clientY * _this._ratio
  29330. };
  29331. };
  29332. this._syncUI = function () {
  29333. if (_this._showUI) {
  29334. if (_this._displayStatistics) {
  29335. _this._displayStats();
  29336. _this._statsDiv.style.display = "";
  29337. }
  29338. else {
  29339. _this._statsDiv.style.display = "none";
  29340. }
  29341. if (_this._displayLogs) {
  29342. _this._logDiv.style.display = "";
  29343. }
  29344. else {
  29345. _this._logDiv.style.display = "none";
  29346. }
  29347. if (_this._displayTree) {
  29348. _this._treeDiv.style.display = "";
  29349. if (_this._needToRefreshMeshesTree) {
  29350. _this._needToRefreshMeshesTree = false;
  29351. _this._refreshMeshesTreeContent();
  29352. }
  29353. }
  29354. else {
  29355. _this._treeDiv.style.display = "none";
  29356. }
  29357. }
  29358. };
  29359. this._syncData = function () {
  29360. if (_this._labelsEnabled || !_this._showUI) {
  29361. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29362. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29363. var engine = _this._scene.getEngine();
  29364. var viewport = _this._camera.viewport;
  29365. var globalViewport = viewport.toGlobal(engine);
  29366. // Meshes
  29367. var meshes = _this._camera.getActiveMeshes();
  29368. for (var index = 0; index < meshes.length; index++) {
  29369. var mesh = meshes.data[index];
  29370. var position = mesh.getBoundingInfo().boundingSphere.center;
  29371. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29372. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29373. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29374. }
  29375. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29376. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29377. mesh.renderOverlay = !mesh.renderOverlay;
  29378. }, function () {
  29379. return mesh.renderOverlay ? 'red' : 'black';
  29380. });
  29381. }
  29382. }
  29383. // Cameras
  29384. var cameras = _this._scene.cameras;
  29385. for (index = 0; index < cameras.length; index++) {
  29386. var camera = cameras[index];
  29387. if (camera === _this._camera) {
  29388. continue;
  29389. }
  29390. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29391. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29392. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29393. _this._camera.detachControl(engine.getRenderingCanvas());
  29394. _this._camera = camera;
  29395. _this._camera.attachControl(engine.getRenderingCanvas());
  29396. }, function () {
  29397. return "purple";
  29398. });
  29399. }
  29400. }
  29401. // Lights
  29402. var lights = _this._scene.lights;
  29403. for (index = 0; index < lights.length; index++) {
  29404. var light = lights[index];
  29405. if (light.position) {
  29406. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29407. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29408. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29409. light.setEnabled(!light.isEnabled());
  29410. }, function () {
  29411. return light.isEnabled() ? "orange" : "gray";
  29412. });
  29413. }
  29414. }
  29415. }
  29416. }
  29417. _this._clickPosition = undefined;
  29418. };
  29419. }
  29420. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29421. while (this._treeSubsetDiv.hasChildNodes()) {
  29422. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29423. }
  29424. // Add meshes
  29425. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29426. sortedArray.sort(function (a, b) {
  29427. if (a.name === b.name) {
  29428. return 0;
  29429. }
  29430. return (a.name > b.name) ? 1 : -1;
  29431. });
  29432. for (var index = 0; index < sortedArray.length; index++) {
  29433. var mesh = sortedArray[index];
  29434. if (!mesh.isEnabled()) {
  29435. continue;
  29436. }
  29437. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29438. m.isVisible = element.checked;
  29439. }, mesh);
  29440. }
  29441. };
  29442. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29443. this._drawingContext.beginPath();
  29444. this._drawingContext.moveTo(zero.x, zero.y);
  29445. this._drawingContext.lineTo(unit.x, unit.y);
  29446. this._drawingContext.strokeStyle = color;
  29447. this._drawingContext.lineWidth = 4;
  29448. this._drawingContext.stroke();
  29449. this._drawingContext.font = "normal 14px Segoe UI";
  29450. this._drawingContext.fillStyle = color;
  29451. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29452. };
  29453. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29454. var position = mesh.getBoundingInfo().boundingSphere.center;
  29455. var worldMatrix = mesh.getWorldMatrix();
  29456. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29457. var unit = (unprojectedVector.subtract(position)).length();
  29458. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29459. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29460. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29461. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29462. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29463. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29464. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29465. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29466. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29467. };
  29468. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29469. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29470. this._drawingContext.font = "normal 12px Segoe UI";
  29471. var textMetrics = this._drawingContext.measureText(text);
  29472. var centerX = projectedPosition.x - textMetrics.width / 2;
  29473. var centerY = projectedPosition.y;
  29474. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29475. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29476. onClick();
  29477. }
  29478. this._drawingContext.beginPath();
  29479. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29480. this._drawingContext.fillStyle = getFillStyle();
  29481. this._drawingContext.globalAlpha = 0.5;
  29482. this._drawingContext.fill();
  29483. this._drawingContext.globalAlpha = 1.0;
  29484. this._drawingContext.strokeStyle = '#FFFFFF';
  29485. this._drawingContext.lineWidth = 1;
  29486. this._drawingContext.stroke();
  29487. this._drawingContext.fillStyle = "#FFFFFF";
  29488. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29489. this._drawingContext.beginPath();
  29490. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29491. this._drawingContext.fill();
  29492. }
  29493. };
  29494. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29495. if (!this._clickPosition) {
  29496. return false;
  29497. }
  29498. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29499. return false;
  29500. }
  29501. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29502. return false;
  29503. }
  29504. return true;
  29505. };
  29506. DebugLayer.prototype.isVisible = function () {
  29507. return this._enabled;
  29508. };
  29509. DebugLayer.prototype.hide = function () {
  29510. if (!this._enabled) {
  29511. return;
  29512. }
  29513. this._enabled = false;
  29514. var engine = this._scene.getEngine();
  29515. this._scene.unregisterBeforeRender(this._syncData);
  29516. this._scene.unregisterAfterRender(this._syncUI);
  29517. document.body.removeChild(this._globalDiv);
  29518. window.removeEventListener("resize", this._syncPositions);
  29519. this._scene.forceShowBoundingBoxes = false;
  29520. this._scene.forceWireframe = false;
  29521. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29522. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29523. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29524. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29525. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29526. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29527. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29528. this._scene.shadowsEnabled = true;
  29529. this._scene.particlesEnabled = true;
  29530. this._scene.postProcessesEnabled = true;
  29531. this._scene.collisionsEnabled = true;
  29532. this._scene.lightsEnabled = true;
  29533. this._scene.texturesEnabled = true;
  29534. this._scene.lensFlaresEnabled = true;
  29535. this._scene.proceduralTexturesEnabled = true;
  29536. this._scene.renderTargetsEnabled = true;
  29537. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29538. };
  29539. DebugLayer.prototype.show = function (showUI, camera) {
  29540. if (showUI === void 0) { showUI = true; }
  29541. if (camera === void 0) { camera = null; }
  29542. if (this._enabled) {
  29543. return;
  29544. }
  29545. this._enabled = true;
  29546. if (camera) {
  29547. this._camera = camera;
  29548. }
  29549. else {
  29550. this._camera = this._scene.activeCamera;
  29551. }
  29552. this._showUI = showUI;
  29553. var engine = this._scene.getEngine();
  29554. this._globalDiv = document.createElement("div");
  29555. document.body.appendChild(this._globalDiv);
  29556. this._generateDOMelements();
  29557. window.addEventListener("resize", this._syncPositions);
  29558. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29559. this._syncPositions();
  29560. this._scene.registerBeforeRender(this._syncData);
  29561. this._scene.registerAfterRender(this._syncUI);
  29562. };
  29563. DebugLayer.prototype._clearLabels = function () {
  29564. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29565. for (var index = 0; index < this._scene.meshes.length; index++) {
  29566. var mesh = this._scene.meshes[index];
  29567. mesh.renderOverlay = false;
  29568. }
  29569. };
  29570. DebugLayer.prototype._generateheader = function (root, text) {
  29571. var header = document.createElement("div");
  29572. header.innerHTML = text + "&nbsp;";
  29573. header.style.textAlign = "right";
  29574. header.style.width = "100%";
  29575. header.style.color = "white";
  29576. header.style.backgroundColor = "Black";
  29577. header.style.padding = "5px 5px 4px 0px";
  29578. header.style.marginLeft = "-5px";
  29579. header.style.fontWeight = "bold";
  29580. root.appendChild(header);
  29581. };
  29582. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29583. var label = document.createElement("label");
  29584. label.innerHTML = title;
  29585. label.style.color = color;
  29586. root.appendChild(label);
  29587. root.appendChild(document.createElement("br"));
  29588. };
  29589. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29590. if (tag === void 0) { tag = null; }
  29591. var label = document.createElement("label");
  29592. var boundingBoxesCheckbox = document.createElement("input");
  29593. boundingBoxesCheckbox.type = "checkbox";
  29594. boundingBoxesCheckbox.checked = initialState;
  29595. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29596. task(evt.target, tag);
  29597. });
  29598. label.appendChild(boundingBoxesCheckbox);
  29599. var container = document.createElement("span");
  29600. var leftPart = document.createElement("span");
  29601. var rightPart = document.createElement("span");
  29602. rightPart.style.cssFloat = "right";
  29603. leftPart.innerHTML = leftTitle;
  29604. rightPart.innerHTML = rightTitle;
  29605. rightPart.style.fontSize = "12px";
  29606. rightPart.style.maxWidth = "200px";
  29607. container.appendChild(leftPart);
  29608. container.appendChild(rightPart);
  29609. label.appendChild(container);
  29610. root.appendChild(label);
  29611. root.appendChild(document.createElement("br"));
  29612. };
  29613. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29614. if (tag === void 0) { tag = null; }
  29615. var label = document.createElement("label");
  29616. var checkBox = document.createElement("input");
  29617. checkBox.type = "checkbox";
  29618. checkBox.checked = initialState;
  29619. checkBox.addEventListener("change", function (evt) {
  29620. task(evt.target, tag);
  29621. });
  29622. label.appendChild(checkBox);
  29623. label.appendChild(document.createTextNode(title));
  29624. root.appendChild(label);
  29625. root.appendChild(document.createElement("br"));
  29626. };
  29627. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29628. if (tag === void 0) { tag = null; }
  29629. var button = document.createElement("button");
  29630. button.innerHTML = title;
  29631. button.style.height = "24px";
  29632. button.style.color = "#444444";
  29633. button.style.border = "1px solid white";
  29634. button.className = "debugLayerButton";
  29635. button.addEventListener("click", function (evt) {
  29636. task(evt.target, tag);
  29637. });
  29638. root.appendChild(button);
  29639. root.appendChild(document.createElement("br"));
  29640. };
  29641. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29642. if (tag === void 0) { tag = null; }
  29643. var label = document.createElement("label");
  29644. var boundingBoxesRadio = document.createElement("input");
  29645. boundingBoxesRadio.type = "radio";
  29646. boundingBoxesRadio.name = name;
  29647. boundingBoxesRadio.checked = initialState;
  29648. boundingBoxesRadio.addEventListener("change", function (evt) {
  29649. task(evt.target, tag);
  29650. });
  29651. label.appendChild(boundingBoxesRadio);
  29652. label.appendChild(document.createTextNode(title));
  29653. root.appendChild(label);
  29654. root.appendChild(document.createElement("br"));
  29655. };
  29656. DebugLayer.prototype._generateDOMelements = function () {
  29657. var _this = this;
  29658. this._globalDiv.id = "DebugLayer";
  29659. this._globalDiv.style.position = "absolute";
  29660. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29661. this._globalDiv.style.fontSize = "14px";
  29662. this._globalDiv.style.color = "white";
  29663. // Drawing canvas
  29664. this._drawingCanvas = document.createElement("canvas");
  29665. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29666. this._drawingCanvas.style.position = "absolute";
  29667. this._drawingCanvas.style.pointerEvents = "none";
  29668. this._drawingContext = this._drawingCanvas.getContext("2d");
  29669. this._globalDiv.appendChild(this._drawingCanvas);
  29670. if (this._showUI) {
  29671. var background = "rgba(128, 128, 128, 0.4)";
  29672. var border = "rgb(180, 180, 180) solid 1px";
  29673. // Stats
  29674. this._statsDiv = document.createElement("div");
  29675. this._statsDiv.id = "DebugLayerStats";
  29676. this._statsDiv.style.border = border;
  29677. this._statsDiv.style.position = "absolute";
  29678. this._statsDiv.style.background = background;
  29679. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29680. this._generateheader(this._statsDiv, "STATISTICS");
  29681. this._statsSubsetDiv = document.createElement("div");
  29682. this._statsSubsetDiv.style.paddingTop = "5px";
  29683. this._statsSubsetDiv.style.paddingBottom = "5px";
  29684. this._statsSubsetDiv.style.overflowY = "auto";
  29685. this._statsDiv.appendChild(this._statsSubsetDiv);
  29686. // Tree
  29687. this._treeDiv = document.createElement("div");
  29688. this._treeDiv.id = "DebugLayerTree";
  29689. this._treeDiv.style.border = border;
  29690. this._treeDiv.style.position = "absolute";
  29691. this._treeDiv.style.background = background;
  29692. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29693. this._treeDiv.style.display = "none";
  29694. this._generateheader(this._treeDiv, "MESHES TREE");
  29695. this._treeSubsetDiv = document.createElement("div");
  29696. this._treeSubsetDiv.style.paddingTop = "5px";
  29697. this._treeSubsetDiv.style.paddingRight = "5px";
  29698. this._treeSubsetDiv.style.overflowY = "auto";
  29699. this._treeSubsetDiv.style.maxHeight = "300px";
  29700. this._treeDiv.appendChild(this._treeSubsetDiv);
  29701. this._needToRefreshMeshesTree = true;
  29702. // Logs
  29703. this._logDiv = document.createElement("div");
  29704. this._logDiv.style.border = border;
  29705. this._logDiv.id = "DebugLayerLogs";
  29706. this._logDiv.style.position = "absolute";
  29707. this._logDiv.style.background = background;
  29708. this._logDiv.style.padding = "0px 0px 0px 5px";
  29709. this._logDiv.style.display = "none";
  29710. this._generateheader(this._logDiv, "LOGS");
  29711. this._logSubsetDiv = document.createElement("div");
  29712. this._logSubsetDiv.style.height = "127px";
  29713. this._logSubsetDiv.style.paddingTop = "5px";
  29714. this._logSubsetDiv.style.overflowY = "auto";
  29715. this._logSubsetDiv.style.fontSize = "12px";
  29716. this._logSubsetDiv.style.fontFamily = "consolas";
  29717. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29718. this._logDiv.appendChild(this._logSubsetDiv);
  29719. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29720. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29721. };
  29722. // Options
  29723. this._optionsDiv = document.createElement("div");
  29724. this._optionsDiv.id = "DebugLayerOptions";
  29725. this._optionsDiv.style.border = border;
  29726. this._optionsDiv.style.position = "absolute";
  29727. this._optionsDiv.style.background = background;
  29728. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29729. this._optionsDiv.style.overflowY = "auto";
  29730. this._generateheader(this._optionsDiv, "OPTIONS");
  29731. this._optionsSubsetDiv = document.createElement("div");
  29732. this._optionsSubsetDiv.style.paddingTop = "5px";
  29733. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29734. this._optionsSubsetDiv.style.overflowY = "auto";
  29735. this._optionsSubsetDiv.style.maxHeight = "200px";
  29736. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29737. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29738. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29739. _this._displayStatistics = element.checked;
  29740. });
  29741. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29742. _this._displayLogs = element.checked;
  29743. });
  29744. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29745. _this._displayTree = element.checked;
  29746. _this._needToRefreshMeshesTree = true;
  29747. });
  29748. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29749. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29750. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29751. _this._scene.forceShowBoundingBoxes = element.checked;
  29752. });
  29753. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29754. _this._labelsEnabled = element.checked;
  29755. if (!_this._labelsEnabled) {
  29756. _this._clearLabels();
  29757. }
  29758. });
  29759. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29760. if (element.checked) {
  29761. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29762. }
  29763. else {
  29764. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29765. }
  29766. });
  29767. ;
  29768. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29769. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29770. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29771. if (element.checked) {
  29772. _this._scene.forceWireframe = false;
  29773. _this._scene.forcePointsCloud = false;
  29774. }
  29775. });
  29776. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29777. if (element.checked) {
  29778. _this._scene.forceWireframe = true;
  29779. _this._scene.forcePointsCloud = false;
  29780. }
  29781. });
  29782. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29783. if (element.checked) {
  29784. _this._scene.forceWireframe = false;
  29785. _this._scene.forcePointsCloud = true;
  29786. }
  29787. });
  29788. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29789. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29790. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29791. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29792. });
  29793. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29794. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29795. });
  29796. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29797. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29798. });
  29799. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29800. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29801. });
  29802. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29803. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29804. });
  29805. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29806. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29807. });
  29808. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29809. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29810. });
  29811. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29812. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29813. });
  29814. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29815. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29816. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29817. _this._scene.animationsEnabled = element.checked;
  29818. });
  29819. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29820. _this._scene.collisionsEnabled = element.checked;
  29821. });
  29822. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29823. _this._scene.fogEnabled = element.checked;
  29824. });
  29825. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29826. _this._scene.lensFlaresEnabled = element.checked;
  29827. });
  29828. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29829. _this._scene.lightsEnabled = element.checked;
  29830. });
  29831. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29832. _this._scene.particlesEnabled = element.checked;
  29833. });
  29834. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29835. _this._scene.postProcessesEnabled = element.checked;
  29836. });
  29837. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29838. _this._scene.proceduralTexturesEnabled = element.checked;
  29839. });
  29840. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29841. _this._scene.renderTargetsEnabled = element.checked;
  29842. });
  29843. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29844. _this._scene.shadowsEnabled = element.checked;
  29845. });
  29846. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29847. _this._scene.skeletonsEnabled = element.checked;
  29848. });
  29849. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29850. _this._scene.spritesEnabled = element.checked;
  29851. });
  29852. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29853. _this._scene.texturesEnabled = element.checked;
  29854. });
  29855. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29856. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29857. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29858. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29859. if (element.checked) {
  29860. _this._scene.headphone = true;
  29861. }
  29862. });
  29863. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29864. if (element.checked) {
  29865. _this._scene.headphone = false;
  29866. }
  29867. });
  29868. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29869. _this._scene.audioEnabled = !element.checked;
  29870. });
  29871. }
  29872. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29873. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29874. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29875. _this._scene.dumpNextRenderTargets = true;
  29876. });
  29877. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29878. this._globalDiv.appendChild(this._statsDiv);
  29879. this._globalDiv.appendChild(this._logDiv);
  29880. this._globalDiv.appendChild(this._optionsDiv);
  29881. this._globalDiv.appendChild(this._treeDiv);
  29882. }
  29883. };
  29884. DebugLayer.prototype._displayStats = function () {
  29885. var scene = this._scene;
  29886. var engine = scene.getEngine();
  29887. var glInfo = engine.getGlInfo();
  29888. 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>";
  29889. if (this.customStatsFunction) {
  29890. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29891. }
  29892. };
  29893. return DebugLayer;
  29894. })();
  29895. BABYLON.DebugLayer = DebugLayer;
  29896. })(BABYLON || (BABYLON = {}));
  29897. //# sourceMappingURL=babylon.debugLayer.js.map
  29898. var __extends = this.__extends || function (d, b) {
  29899. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29900. function __() { this.constructor = d; }
  29901. __.prototype = b.prototype;
  29902. d.prototype = new __();
  29903. };
  29904. var BABYLON;
  29905. (function (BABYLON) {
  29906. var RawTexture = (function (_super) {
  29907. __extends(RawTexture, _super);
  29908. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29909. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29910. if (invertY === void 0) { invertY = false; }
  29911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29912. _super.call(this, null, scene, !generateMipMaps, invertY);
  29913. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29914. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29915. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29916. }
  29917. // Statics
  29918. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29919. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29920. if (invertY === void 0) { invertY = false; }
  29921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29922. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29923. };
  29924. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29925. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29926. if (invertY === void 0) { invertY = false; }
  29927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29928. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29929. };
  29930. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29931. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29932. if (invertY === void 0) { invertY = false; }
  29933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29934. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29935. };
  29936. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29937. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29938. if (invertY === void 0) { invertY = false; }
  29939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29940. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29941. };
  29942. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29943. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29944. if (invertY === void 0) { invertY = false; }
  29945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29946. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29947. };
  29948. return RawTexture;
  29949. })(BABYLON.Texture);
  29950. BABYLON.RawTexture = RawTexture;
  29951. })(BABYLON || (BABYLON = {}));
  29952. //# sourceMappingURL=babylon.rawTexture.js.map
  29953. var __extends = this.__extends || function (d, b) {
  29954. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29955. function __() { this.constructor = d; }
  29956. __.prototype = b.prototype;
  29957. d.prototype = new __();
  29958. };
  29959. var BABYLON;
  29960. (function (BABYLON) {
  29961. var IndexedVector2 = (function (_super) {
  29962. __extends(IndexedVector2, _super);
  29963. function IndexedVector2(original, index) {
  29964. _super.call(this, original.x, original.y);
  29965. this.index = index;
  29966. }
  29967. return IndexedVector2;
  29968. })(BABYLON.Vector2);
  29969. var PolygonPoints = (function () {
  29970. function PolygonPoints() {
  29971. this.elements = new Array();
  29972. }
  29973. PolygonPoints.prototype.add = function (originalPoints) {
  29974. var _this = this;
  29975. var result = new Array();
  29976. originalPoints.forEach(function (point) {
  29977. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29978. var newPoint = new IndexedVector2(point, _this.elements.length);
  29979. result.push(newPoint);
  29980. _this.elements.push(newPoint);
  29981. }
  29982. });
  29983. return result;
  29984. };
  29985. PolygonPoints.prototype.computeBounds = function () {
  29986. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29987. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29988. this.elements.forEach(function (point) {
  29989. // x
  29990. if (point.x < lmin.x) {
  29991. lmin.x = point.x;
  29992. }
  29993. else if (point.x > lmax.x) {
  29994. lmax.x = point.x;
  29995. }
  29996. // y
  29997. if (point.y < lmin.y) {
  29998. lmin.y = point.y;
  29999. }
  30000. else if (point.y > lmax.y) {
  30001. lmax.y = point.y;
  30002. }
  30003. });
  30004. return {
  30005. min: lmin,
  30006. max: lmax,
  30007. width: lmax.x - lmin.x,
  30008. height: lmax.y - lmin.y
  30009. };
  30010. };
  30011. return PolygonPoints;
  30012. })();
  30013. var Polygon = (function () {
  30014. function Polygon() {
  30015. }
  30016. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30017. return [
  30018. new BABYLON.Vector2(xmin, ymin),
  30019. new BABYLON.Vector2(xmax, ymin),
  30020. new BABYLON.Vector2(xmax, ymax),
  30021. new BABYLON.Vector2(xmin, ymax)
  30022. ];
  30023. };
  30024. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30025. if (cx === void 0) { cx = 0; }
  30026. if (cy === void 0) { cy = 0; }
  30027. if (numberOfSides === void 0) { numberOfSides = 32; }
  30028. var result = new Array();
  30029. var angle = 0;
  30030. var increment = (Math.PI * 2) / numberOfSides;
  30031. for (var i = 0; i < numberOfSides; i++) {
  30032. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30033. angle -= increment;
  30034. }
  30035. return result;
  30036. };
  30037. Polygon.Parse = function (input) {
  30038. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30039. var i, result = [];
  30040. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30041. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30042. }
  30043. return result;
  30044. };
  30045. Polygon.StartingAt = function (x, y) {
  30046. return BABYLON.Path2.StartingAt(x, y);
  30047. };
  30048. return Polygon;
  30049. })();
  30050. BABYLON.Polygon = Polygon;
  30051. var PolygonMeshBuilder = (function () {
  30052. function PolygonMeshBuilder(name, contours, scene) {
  30053. this._points = new PolygonPoints();
  30054. this._outlinepoints = new PolygonPoints();
  30055. this._holes = [];
  30056. if (!("poly2tri" in window)) {
  30057. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30058. }
  30059. this._name = name;
  30060. this._scene = scene;
  30061. var points;
  30062. if (contours instanceof BABYLON.Path2) {
  30063. points = contours.getPoints();
  30064. }
  30065. else {
  30066. points = contours;
  30067. }
  30068. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30069. this._outlinepoints.add(points);
  30070. }
  30071. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30072. this._swctx.addHole(this._points.add(hole));
  30073. var holepoints = new PolygonPoints();
  30074. holepoints.add(hole);
  30075. this._holes.push(holepoints);
  30076. return this;
  30077. };
  30078. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30079. var _this = this;
  30080. if (updatable === void 0) { updatable = false; }
  30081. var result = new BABYLON.Mesh(this._name, this._scene);
  30082. var normals = [];
  30083. var positions = [];
  30084. var uvs = [];
  30085. var bounds = this._points.computeBounds();
  30086. this._points.elements.forEach(function (p) {
  30087. normals.push(0, 1.0, 0);
  30088. positions.push(p.x, 0, p.y);
  30089. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30090. });
  30091. var indices = [];
  30092. this._swctx.triangulate();
  30093. this._swctx.getTriangles().forEach(function (triangle) {
  30094. triangle.getPoints().forEach(function (point) {
  30095. indices.push(point.index);
  30096. });
  30097. });
  30098. if (depth > 0) {
  30099. var positionscount = (positions.length / 3); //get the current pointcount
  30100. this._points.elements.forEach(function (p) {
  30101. normals.push(0, -1.0, 0);
  30102. positions.push(p.x, -depth, p.y);
  30103. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30104. });
  30105. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30106. var p2;
  30107. var poscounter = 0;
  30108. this._swctx.getTriangles().forEach(function (triangle) {
  30109. triangle.getPoints().forEach(function (point) {
  30110. switch (poscounter) {
  30111. case 0:
  30112. p1 = point;
  30113. break;
  30114. case 1:
  30115. p2 = point;
  30116. break;
  30117. case 2:
  30118. indices.push(point.index + positionscount);
  30119. indices.push(p2.index + positionscount);
  30120. indices.push(p1.index + positionscount);
  30121. poscounter = -1;
  30122. break;
  30123. }
  30124. poscounter++;
  30125. //indices.push((<IndexedVector2>point).index + positionscount);
  30126. });
  30127. });
  30128. //Add the sides
  30129. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30130. this._holes.forEach(function (hole) {
  30131. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30132. });
  30133. }
  30134. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30135. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30136. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30137. result.setIndices(indices);
  30138. return result;
  30139. };
  30140. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30141. var StartIndex = positions.length / 3;
  30142. var ulength = 0;
  30143. for (var i = 0; i < points.elements.length; i++) {
  30144. var p = points.elements[i];
  30145. var p1;
  30146. if ((i + 1) > points.elements.length - 1) {
  30147. p1 = points.elements[0];
  30148. }
  30149. else {
  30150. p1 = points.elements[i + 1];
  30151. }
  30152. positions.push(p.x, 0, p.y);
  30153. positions.push(p.x, -depth, p.y);
  30154. positions.push(p1.x, 0, p1.y);
  30155. positions.push(p1.x, -depth, p1.y);
  30156. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30157. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30158. var v3 = v2.subtract(v1);
  30159. var v4 = new BABYLON.Vector3(0, 1, 0);
  30160. var vn = BABYLON.Vector3.Cross(v3, v4);
  30161. vn = vn.normalize();
  30162. uvs.push(ulength / bounds.width, 0);
  30163. uvs.push(ulength / bounds.width, 1);
  30164. ulength += v3.length();
  30165. uvs.push((ulength / bounds.width), 0);
  30166. uvs.push((ulength / bounds.width), 1);
  30167. if (!flip) {
  30168. normals.push(-vn.x, -vn.y, -vn.z);
  30169. normals.push(-vn.x, -vn.y, -vn.z);
  30170. normals.push(-vn.x, -vn.y, -vn.z);
  30171. normals.push(-vn.x, -vn.y, -vn.z);
  30172. indices.push(StartIndex);
  30173. indices.push(StartIndex + 1);
  30174. indices.push(StartIndex + 2);
  30175. indices.push(StartIndex + 1);
  30176. indices.push(StartIndex + 3);
  30177. indices.push(StartIndex + 2);
  30178. }
  30179. else {
  30180. normals.push(vn.x, vn.y, vn.z);
  30181. normals.push(vn.x, vn.y, vn.z);
  30182. normals.push(vn.x, vn.y, vn.z);
  30183. normals.push(vn.x, vn.y, vn.z);
  30184. indices.push(StartIndex);
  30185. indices.push(StartIndex + 2);
  30186. indices.push(StartIndex + 1);
  30187. indices.push(StartIndex + 1);
  30188. indices.push(StartIndex + 2);
  30189. indices.push(StartIndex + 3);
  30190. }
  30191. StartIndex += 4;
  30192. }
  30193. ;
  30194. };
  30195. return PolygonMeshBuilder;
  30196. })();
  30197. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30198. })(BABYLON || (BABYLON = {}));
  30199. //# sourceMappingURL=babylon.polygonMesh.js.map
  30200. var BABYLON;
  30201. (function (BABYLON) {
  30202. var SimplificationSettings = (function () {
  30203. function SimplificationSettings(quality, distance, optimizeMesh) {
  30204. this.quality = quality;
  30205. this.distance = distance;
  30206. this.optimizeMesh = optimizeMesh;
  30207. }
  30208. return SimplificationSettings;
  30209. })();
  30210. BABYLON.SimplificationSettings = SimplificationSettings;
  30211. var SimplificationQueue = (function () {
  30212. function SimplificationQueue() {
  30213. this.running = false;
  30214. this._simplificationArray = [];
  30215. }
  30216. SimplificationQueue.prototype.addTask = function (task) {
  30217. this._simplificationArray.push(task);
  30218. };
  30219. SimplificationQueue.prototype.executeNext = function () {
  30220. var task = this._simplificationArray.pop();
  30221. if (task) {
  30222. this.running = true;
  30223. this.runSimplification(task);
  30224. }
  30225. else {
  30226. this.running = false;
  30227. }
  30228. };
  30229. SimplificationQueue.prototype.runSimplification = function (task) {
  30230. var _this = this;
  30231. if (task.parallelProcessing) {
  30232. //parallel simplifier
  30233. task.settings.forEach(function (setting) {
  30234. var simplifier = _this.getSimplifier(task);
  30235. simplifier.simplify(setting, function (newMesh) {
  30236. task.mesh.addLODLevel(setting.distance, newMesh);
  30237. newMesh.isVisible = true;
  30238. //check if it is the last
  30239. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30240. //all done, run the success callback.
  30241. task.successCallback();
  30242. }
  30243. _this.executeNext();
  30244. });
  30245. });
  30246. }
  30247. else {
  30248. //single simplifier.
  30249. var simplifier = this.getSimplifier(task);
  30250. var runDecimation = function (setting, callback) {
  30251. simplifier.simplify(setting, function (newMesh) {
  30252. task.mesh.addLODLevel(setting.distance, newMesh);
  30253. newMesh.isVisible = true;
  30254. //run the next quality level
  30255. callback();
  30256. });
  30257. };
  30258. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30259. runDecimation(task.settings[loop.index], function () {
  30260. loop.executeNext();
  30261. });
  30262. }, function () {
  30263. //execution ended, run the success callback.
  30264. if (task.successCallback) {
  30265. task.successCallback();
  30266. }
  30267. _this.executeNext();
  30268. });
  30269. }
  30270. };
  30271. SimplificationQueue.prototype.getSimplifier = function (task) {
  30272. switch (task.simplificationType) {
  30273. case 0 /* QUADRATIC */:
  30274. default:
  30275. return new QuadraticErrorSimplification(task.mesh);
  30276. }
  30277. };
  30278. return SimplificationQueue;
  30279. })();
  30280. BABYLON.SimplificationQueue = SimplificationQueue;
  30281. /**
  30282. * The implemented types of simplification.
  30283. * At the moment only Quadratic Error Decimation is implemented.
  30284. */
  30285. (function (SimplificationType) {
  30286. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30287. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30288. var SimplificationType = BABYLON.SimplificationType;
  30289. var DecimationTriangle = (function () {
  30290. function DecimationTriangle(vertices) {
  30291. this.vertices = vertices;
  30292. this.error = new Array(4);
  30293. this.deleted = false;
  30294. this.isDirty = false;
  30295. this.deletePending = false;
  30296. this.borderFactor = 0;
  30297. }
  30298. return DecimationTriangle;
  30299. })();
  30300. BABYLON.DecimationTriangle = DecimationTriangle;
  30301. var DecimationVertex = (function () {
  30302. function DecimationVertex(position, id) {
  30303. this.position = position;
  30304. this.id = id;
  30305. this.isBorder = true;
  30306. this.q = new QuadraticMatrix();
  30307. this.triangleCount = 0;
  30308. this.triangleStart = 0;
  30309. this.originalOffsets = [];
  30310. }
  30311. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30312. this.position.copyFrom(newPosition);
  30313. };
  30314. return DecimationVertex;
  30315. })();
  30316. BABYLON.DecimationVertex = DecimationVertex;
  30317. var QuadraticMatrix = (function () {
  30318. function QuadraticMatrix(data) {
  30319. this.data = new Array(10);
  30320. for (var i = 0; i < 10; ++i) {
  30321. if (data && data[i]) {
  30322. this.data[i] = data[i];
  30323. }
  30324. else {
  30325. this.data[i] = 0;
  30326. }
  30327. }
  30328. }
  30329. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30330. 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];
  30331. return det;
  30332. };
  30333. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30334. for (var i = 0; i < 10; ++i) {
  30335. this.data[i] += matrix.data[i];
  30336. }
  30337. };
  30338. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30339. for (var i = 0; i < 10; ++i) {
  30340. this.data[i] += data[i];
  30341. }
  30342. };
  30343. QuadraticMatrix.prototype.add = function (matrix) {
  30344. var m = new QuadraticMatrix();
  30345. for (var i = 0; i < 10; ++i) {
  30346. m.data[i] = this.data[i] + matrix.data[i];
  30347. }
  30348. return m;
  30349. };
  30350. QuadraticMatrix.FromData = function (a, b, c, d) {
  30351. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30352. };
  30353. //returning an array to avoid garbage collection
  30354. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30355. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30356. };
  30357. return QuadraticMatrix;
  30358. })();
  30359. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30360. var Reference = (function () {
  30361. function Reference(vertexId, triangleId) {
  30362. this.vertexId = vertexId;
  30363. this.triangleId = triangleId;
  30364. }
  30365. return Reference;
  30366. })();
  30367. BABYLON.Reference = Reference;
  30368. /**
  30369. * An implementation of the Quadratic Error simplification algorithm.
  30370. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30371. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30372. * @author RaananW
  30373. */
  30374. var QuadraticErrorSimplification = (function () {
  30375. function QuadraticErrorSimplification(_mesh) {
  30376. this._mesh = _mesh;
  30377. this.initialized = false;
  30378. this.syncIterations = 5000;
  30379. this.aggressiveness = 7;
  30380. this.decimationIterations = 100;
  30381. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30382. }
  30383. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30384. var _this = this;
  30385. this.initDecimatedMesh();
  30386. //iterating through the submeshes array, one after the other.
  30387. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30388. _this.initWithMesh(loop.index, function () {
  30389. _this.runDecimation(settings, loop.index, function () {
  30390. loop.executeNext();
  30391. });
  30392. }, settings.optimizeMesh);
  30393. }, function () {
  30394. setTimeout(function () {
  30395. successCallback(_this._reconstructedMesh);
  30396. }, 0);
  30397. });
  30398. };
  30399. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30400. var _this = this;
  30401. var gCount = 0;
  30402. triangle.vertices.forEach(function (vertex) {
  30403. var count = 0;
  30404. var vPos = vertex.position;
  30405. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30406. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30407. ++count;
  30408. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30409. ++count;
  30410. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30411. ++count;
  30412. if (count > 1) {
  30413. ++gCount;
  30414. }
  30415. ;
  30416. });
  30417. if (gCount > 1) {
  30418. console.log(triangle, gCount);
  30419. }
  30420. return gCount > 1;
  30421. };
  30422. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30423. var _this = this;
  30424. var targetCount = ~~(this.triangles.length * settings.quality);
  30425. var deletedTriangles = 0;
  30426. var triangleCount = this.triangles.length;
  30427. var iterationFunction = function (iteration, callback) {
  30428. setTimeout(function () {
  30429. if (iteration % 5 === 0) {
  30430. _this.updateMesh(iteration === 0);
  30431. }
  30432. for (var i = 0; i < _this.triangles.length; ++i) {
  30433. _this.triangles[i].isDirty = false;
  30434. }
  30435. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30436. var trianglesIterator = function (i) {
  30437. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30438. var t = _this.triangles[tIdx];
  30439. if (!t)
  30440. return;
  30441. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30442. return;
  30443. }
  30444. for (var j = 0; j < 3; ++j) {
  30445. if (t.error[j] < threshold) {
  30446. var deleted0 = [];
  30447. var deleted1 = [];
  30448. var v0 = t.vertices[j];
  30449. var v1 = t.vertices[(j + 1) % 3];
  30450. if (v0.isBorder !== v1.isBorder)
  30451. continue;
  30452. var p = BABYLON.Vector3.Zero();
  30453. var n = BABYLON.Vector3.Zero();
  30454. var uv = BABYLON.Vector2.Zero();
  30455. var color = new BABYLON.Color4(0, 0, 0, 1);
  30456. _this.calculateError(v0, v1, p, n, uv, color);
  30457. var delTr = [];
  30458. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30459. continue;
  30460. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30461. continue;
  30462. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30463. continue;
  30464. var uniqueArray = [];
  30465. delTr.forEach(function (deletedT) {
  30466. if (uniqueArray.indexOf(deletedT) === -1) {
  30467. deletedT.deletePending = true;
  30468. uniqueArray.push(deletedT);
  30469. }
  30470. });
  30471. if (uniqueArray.length % 2 != 0) {
  30472. continue;
  30473. }
  30474. v0.q = v1.q.add(v0.q);
  30475. v0.updatePosition(p);
  30476. var tStart = _this.references.length;
  30477. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30478. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30479. var tCount = _this.references.length - tStart;
  30480. if (tCount <= v0.triangleCount) {
  30481. if (tCount) {
  30482. for (var c = 0; c < tCount; c++) {
  30483. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30484. }
  30485. }
  30486. }
  30487. else {
  30488. v0.triangleStart = tStart;
  30489. }
  30490. v0.triangleCount = tCount;
  30491. break;
  30492. }
  30493. }
  30494. };
  30495. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30496. return (triangleCount - deletedTriangles <= targetCount);
  30497. });
  30498. }, 0);
  30499. };
  30500. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30501. if (triangleCount - deletedTriangles <= targetCount)
  30502. loop.breakLoop();
  30503. else {
  30504. iterationFunction(loop.index, function () {
  30505. loop.executeNext();
  30506. });
  30507. }
  30508. }, function () {
  30509. setTimeout(function () {
  30510. //reconstruct this part of the mesh
  30511. _this.reconstructMesh(submeshIndex);
  30512. successCallback();
  30513. }, 0);
  30514. });
  30515. };
  30516. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30517. var _this = this;
  30518. this.vertices = [];
  30519. this.triangles = [];
  30520. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30521. var indices = this._mesh.getIndices();
  30522. var submesh = this._mesh.subMeshes[submeshIndex];
  30523. var findInVertices = function (positionToSearch) {
  30524. if (optimizeMesh) {
  30525. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30526. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30527. return _this.vertices[ii];
  30528. }
  30529. }
  30530. }
  30531. return null;
  30532. };
  30533. var vertexReferences = [];
  30534. var vertexInit = function (i) {
  30535. var offset = i + submesh.verticesStart;
  30536. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30537. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30538. vertex.originalOffsets.push(offset);
  30539. if (vertex.id == _this.vertices.length) {
  30540. _this.vertices.push(vertex);
  30541. }
  30542. vertexReferences.push(vertex.id);
  30543. };
  30544. //var totalVertices = mesh.getTotalVertices();
  30545. var totalVertices = submesh.verticesCount;
  30546. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30547. var indicesInit = function (i) {
  30548. var offset = (submesh.indexStart / 3) + i;
  30549. var pos = (offset * 3);
  30550. var i0 = indices[pos + 0];
  30551. var i1 = indices[pos + 1];
  30552. var i2 = indices[pos + 2];
  30553. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30554. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30555. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30556. var triangle = new DecimationTriangle([v0, v1, v2]);
  30557. triangle.originalOffset = pos;
  30558. _this.triangles.push(triangle);
  30559. };
  30560. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30561. _this.init(callback);
  30562. });
  30563. });
  30564. };
  30565. QuadraticErrorSimplification.prototype.init = function (callback) {
  30566. var _this = this;
  30567. var triangleInit1 = function (i) {
  30568. var t = _this.triangles[i];
  30569. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30570. for (var j = 0; j < 3; j++) {
  30571. 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))));
  30572. }
  30573. };
  30574. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30575. var triangleInit2 = function (i) {
  30576. var t = _this.triangles[i];
  30577. for (var j = 0; j < 3; ++j) {
  30578. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30579. }
  30580. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30581. };
  30582. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30583. _this.initialized = true;
  30584. callback();
  30585. });
  30586. });
  30587. };
  30588. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30589. var newTriangles = [];
  30590. var i;
  30591. for (i = 0; i < this.vertices.length; ++i) {
  30592. this.vertices[i].triangleCount = 0;
  30593. }
  30594. var t;
  30595. var j;
  30596. for (i = 0; i < this.triangles.length; ++i) {
  30597. if (!this.triangles[i].deleted) {
  30598. t = this.triangles[i];
  30599. for (j = 0; j < 3; ++j) {
  30600. t.vertices[j].triangleCount = 1;
  30601. }
  30602. newTriangles.push(t);
  30603. }
  30604. }
  30605. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30606. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30607. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30608. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30609. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30610. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30611. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30612. var vertexCount = 0;
  30613. for (i = 0; i < this.vertices.length; ++i) {
  30614. var vertex = this.vertices[i];
  30615. vertex.id = vertexCount;
  30616. if (vertex.triangleCount) {
  30617. vertex.originalOffsets.forEach(function (originalOffset) {
  30618. newPositionData.push(vertex.position.x);
  30619. newPositionData.push(vertex.position.y);
  30620. newPositionData.push(vertex.position.z);
  30621. newNormalData.push(normalData[originalOffset * 3]);
  30622. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30623. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30624. if (uvs && uvs.length) {
  30625. newUVsData.push(uvs[(originalOffset * 2)]);
  30626. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30627. }
  30628. else if (colorsData && colorsData.length) {
  30629. newColorsData.push(colorsData[(originalOffset * 4)]);
  30630. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30631. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30632. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30633. }
  30634. ++vertexCount;
  30635. });
  30636. }
  30637. }
  30638. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30639. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30640. var submeshesArray = this._reconstructedMesh.subMeshes;
  30641. this._reconstructedMesh.subMeshes = [];
  30642. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30643. var originalIndices = this._mesh.getIndices();
  30644. for (i = 0; i < newTriangles.length; ++i) {
  30645. var t = newTriangles[i];
  30646. //now get the new referencing point for each vertex
  30647. [0, 1, 2].forEach(function (idx) {
  30648. var id = originalIndices[t.originalOffset + idx];
  30649. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30650. if (offset < 0)
  30651. offset = 0;
  30652. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30653. });
  30654. }
  30655. //overwriting the old vertex buffers and indices.
  30656. this._reconstructedMesh.setIndices(newIndicesArray);
  30657. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30658. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30659. if (newUVsData.length > 0)
  30660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30661. if (newColorsData.length > 0)
  30662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30663. //create submesh
  30664. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30665. if (submeshIndex > 0) {
  30666. this._reconstructedMesh.subMeshes = [];
  30667. submeshesArray.forEach(function (submesh) {
  30668. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30669. });
  30670. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30671. }
  30672. };
  30673. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30674. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30675. this._reconstructedMesh.material = this._mesh.material;
  30676. this._reconstructedMesh.parent = this._mesh.parent;
  30677. this._reconstructedMesh.isVisible = false;
  30678. };
  30679. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30680. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30681. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30682. if (t.deleted)
  30683. continue;
  30684. var s = this.references[vertex1.triangleStart + i].vertexId;
  30685. var v1 = t.vertices[(s + 1) % 3];
  30686. var v2 = t.vertices[(s + 2) % 3];
  30687. if ((v1 === vertex2 || v2 === vertex2)) {
  30688. deletedArray[i] = true;
  30689. delTr.push(t);
  30690. continue;
  30691. }
  30692. var d1 = v1.position.subtract(point);
  30693. d1 = d1.normalize();
  30694. var d2 = v2.position.subtract(point);
  30695. d2 = d2.normalize();
  30696. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30697. return true;
  30698. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30699. deletedArray[i] = false;
  30700. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30701. return true;
  30702. }
  30703. return false;
  30704. };
  30705. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30706. var newDeleted = deletedTriangles;
  30707. for (var i = 0; i < vertex.triangleCount; ++i) {
  30708. var ref = this.references[vertex.triangleStart + i];
  30709. var t = this.triangles[ref.triangleId];
  30710. if (t.deleted)
  30711. continue;
  30712. if (deletedArray[i] && t.deletePending) {
  30713. t.deleted = true;
  30714. newDeleted++;
  30715. continue;
  30716. }
  30717. t.vertices[ref.vertexId] = origVertex;
  30718. t.isDirty = true;
  30719. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30720. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30721. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30722. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30723. this.references.push(ref);
  30724. }
  30725. return newDeleted;
  30726. };
  30727. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30728. for (var i = 0; i < this.vertices.length; ++i) {
  30729. var vCount = [];
  30730. var vId = [];
  30731. var v = this.vertices[i];
  30732. var j;
  30733. for (j = 0; j < v.triangleCount; ++j) {
  30734. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30735. for (var ii = 0; ii < 3; ii++) {
  30736. var ofs = 0;
  30737. var vv = triangle.vertices[ii];
  30738. while (ofs < vCount.length) {
  30739. if (vId[ofs] === vv.id)
  30740. break;
  30741. ++ofs;
  30742. }
  30743. if (ofs === vCount.length) {
  30744. vCount.push(1);
  30745. vId.push(vv.id);
  30746. }
  30747. else {
  30748. vCount[ofs]++;
  30749. }
  30750. }
  30751. }
  30752. for (j = 0; j < vCount.length; ++j) {
  30753. if (vCount[j] === 1) {
  30754. this.vertices[vId[j]].isBorder = true;
  30755. }
  30756. else {
  30757. this.vertices[vId[j]].isBorder = false;
  30758. }
  30759. }
  30760. }
  30761. };
  30762. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30763. if (identifyBorders === void 0) { identifyBorders = false; }
  30764. var i;
  30765. if (!identifyBorders) {
  30766. var newTrianglesVector = [];
  30767. for (i = 0; i < this.triangles.length; ++i) {
  30768. if (!this.triangles[i].deleted) {
  30769. newTrianglesVector.push(this.triangles[i]);
  30770. }
  30771. }
  30772. this.triangles = newTrianglesVector;
  30773. }
  30774. for (i = 0; i < this.vertices.length; ++i) {
  30775. this.vertices[i].triangleCount = 0;
  30776. this.vertices[i].triangleStart = 0;
  30777. }
  30778. var t;
  30779. var j;
  30780. var v;
  30781. for (i = 0; i < this.triangles.length; ++i) {
  30782. t = this.triangles[i];
  30783. for (j = 0; j < 3; ++j) {
  30784. v = t.vertices[j];
  30785. v.triangleCount++;
  30786. }
  30787. }
  30788. var tStart = 0;
  30789. for (i = 0; i < this.vertices.length; ++i) {
  30790. this.vertices[i].triangleStart = tStart;
  30791. tStart += this.vertices[i].triangleCount;
  30792. this.vertices[i].triangleCount = 0;
  30793. }
  30794. var newReferences = new Array(this.triangles.length * 3);
  30795. for (i = 0; i < this.triangles.length; ++i) {
  30796. t = this.triangles[i];
  30797. for (j = 0; j < 3; ++j) {
  30798. v = t.vertices[j];
  30799. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30800. v.triangleCount++;
  30801. }
  30802. }
  30803. this.references = newReferences;
  30804. if (identifyBorders) {
  30805. this.identifyBorder();
  30806. }
  30807. };
  30808. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30809. var x = point.x;
  30810. var y = point.y;
  30811. var z = point.z;
  30812. 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];
  30813. };
  30814. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30815. var q = vertex1.q.add(vertex2.q);
  30816. var border = vertex1.isBorder && vertex2.isBorder;
  30817. var error = 0;
  30818. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30819. if (qDet !== 0 && !border) {
  30820. if (!pointResult) {
  30821. pointResult = BABYLON.Vector3.Zero();
  30822. }
  30823. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30824. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30825. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30826. error = this.vertexError(q, pointResult);
  30827. }
  30828. else {
  30829. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30830. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30831. var error1 = this.vertexError(q, vertex1.position);
  30832. var error2 = this.vertexError(q, vertex2.position);
  30833. var error3 = this.vertexError(q, p3);
  30834. error = Math.min(error1, error2, error3);
  30835. if (error === error1) {
  30836. if (pointResult) {
  30837. pointResult.copyFrom(vertex1.position);
  30838. }
  30839. }
  30840. else if (error === error2) {
  30841. if (pointResult) {
  30842. pointResult.copyFrom(vertex2.position);
  30843. }
  30844. }
  30845. else {
  30846. if (pointResult) {
  30847. pointResult.copyFrom(p3);
  30848. }
  30849. }
  30850. }
  30851. return error;
  30852. };
  30853. return QuadraticErrorSimplification;
  30854. })();
  30855. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30856. })(BABYLON || (BABYLON = {}));
  30857. //# sourceMappingURL=babylon.meshSimplification.js.map
  30858. var BABYLON;
  30859. (function (BABYLON) {
  30860. var Analyser = (function () {
  30861. function Analyser(scene) {
  30862. this.SMOOTHING = 0.75;
  30863. this.FFT_SIZE = 512;
  30864. this.BARGRAPHAMPLITUDE = 256;
  30865. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30866. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30867. this._scene = scene;
  30868. this._audioEngine = BABYLON.Engine.audioEngine;
  30869. if (this._audioEngine.canUseWebAudio) {
  30870. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30871. this._webAudioAnalyser.minDecibels = -140;
  30872. this._webAudioAnalyser.maxDecibels = 0;
  30873. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30874. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30875. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30876. }
  30877. }
  30878. Analyser.prototype.getFrequencyBinCount = function () {
  30879. if (this._audioEngine.canUseWebAudio) {
  30880. return this._webAudioAnalyser.frequencyBinCount;
  30881. }
  30882. else {
  30883. return 0;
  30884. }
  30885. };
  30886. Analyser.prototype.getByteFrequencyData = function () {
  30887. if (this._audioEngine.canUseWebAudio) {
  30888. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30889. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30890. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30891. }
  30892. return this._byteFreqs;
  30893. };
  30894. Analyser.prototype.getByteTimeDomainData = function () {
  30895. if (this._audioEngine.canUseWebAudio) {
  30896. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30897. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30898. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30899. }
  30900. return this._byteTime;
  30901. };
  30902. Analyser.prototype.getFloatFrequencyData = function () {
  30903. if (this._audioEngine.canUseWebAudio) {
  30904. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30905. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30906. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30907. }
  30908. return this._floatFreqs;
  30909. };
  30910. Analyser.prototype.drawDebugCanvas = function () {
  30911. var _this = this;
  30912. if (this._audioEngine.canUseWebAudio) {
  30913. if (!this._debugCanvas) {
  30914. this._debugCanvas = document.createElement("canvas");
  30915. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30916. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30917. this._debugCanvas.style.position = "absolute";
  30918. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30919. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30920. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30921. document.body.appendChild(this._debugCanvas);
  30922. this._registerFunc = function () {
  30923. _this.drawDebugCanvas();
  30924. };
  30925. this._scene.registerBeforeRender(this._registerFunc);
  30926. }
  30927. if (this._registerFunc) {
  30928. var workingArray = this.getByteFrequencyData();
  30929. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30930. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30931. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30932. var value = workingArray[i];
  30933. var percent = value / this.BARGRAPHAMPLITUDE;
  30934. var height = this.DEBUGCANVASSIZE.height * percent;
  30935. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30936. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30937. var hue = i / this.getFrequencyBinCount() * 360;
  30938. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30939. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30940. }
  30941. }
  30942. }
  30943. };
  30944. Analyser.prototype.stopDebugCanvas = function () {
  30945. if (this._debugCanvas) {
  30946. this._scene.unregisterBeforeRender(this._registerFunc);
  30947. this._registerFunc = null;
  30948. document.body.removeChild(this._debugCanvas);
  30949. this._debugCanvas = null;
  30950. this._debugCanvasContext = null;
  30951. }
  30952. };
  30953. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30954. if (this._audioEngine.canUseWebAudio) {
  30955. inputAudioNode.connect(this._webAudioAnalyser);
  30956. this._webAudioAnalyser.connect(outputAudioNode);
  30957. }
  30958. };
  30959. Analyser.prototype.dispose = function () {
  30960. if (this._audioEngine.canUseWebAudio) {
  30961. this._webAudioAnalyser.disconnect();
  30962. }
  30963. };
  30964. return Analyser;
  30965. })();
  30966. BABYLON.Analyser = Analyser;
  30967. })(BABYLON || (BABYLON = {}));
  30968. //# sourceMappingURL=babylon.analyser.js.map
  30969. var BABYLON;
  30970. (function (BABYLON) {
  30971. var DepthRenderer = (function () {
  30972. function DepthRenderer(scene, type) {
  30973. var _this = this;
  30974. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30975. this._viewMatrix = BABYLON.Matrix.Zero();
  30976. this._projectionMatrix = BABYLON.Matrix.Zero();
  30977. this._transformMatrix = BABYLON.Matrix.Zero();
  30978. this._worldViewProjection = BABYLON.Matrix.Zero();
  30979. this._scene = scene;
  30980. var engine = scene.getEngine();
  30981. // Render target
  30982. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30983. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30984. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30985. this._depthMap.refreshRate = 1;
  30986. this._depthMap.renderParticles = false;
  30987. this._depthMap.renderList = null;
  30988. // set default depth value to 1.0 (far away)
  30989. this._depthMap.onClear = function (engine) {
  30990. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30991. };
  30992. // Custom render function
  30993. var renderSubMesh = function (subMesh) {
  30994. var mesh = subMesh.getRenderingMesh();
  30995. var scene = _this._scene;
  30996. var engine = scene.getEngine();
  30997. // Culling
  30998. engine.setState(subMesh.getMaterial().backFaceCulling);
  30999. // Managing instances
  31000. var batch = mesh._getInstancesRenderList(subMesh._id);
  31001. if (batch.mustReturn) {
  31002. return;
  31003. }
  31004. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31005. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31006. engine.enableEffect(_this._effect);
  31007. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31008. var material = subMesh.getMaterial();
  31009. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31010. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31011. // Alpha test
  31012. if (material && material.needAlphaTesting()) {
  31013. var alphaTexture = material.getAlphaTestTexture();
  31014. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31015. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31016. }
  31017. // Bones
  31018. if (mesh.useBones) {
  31019. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31020. }
  31021. // Draw
  31022. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31023. }
  31024. };
  31025. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31026. var index;
  31027. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31028. renderSubMesh(opaqueSubMeshes.data[index]);
  31029. }
  31030. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31031. renderSubMesh(alphaTestSubMeshes.data[index]);
  31032. }
  31033. };
  31034. }
  31035. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31036. var defines = [];
  31037. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31038. var mesh = subMesh.getMesh();
  31039. var scene = mesh.getScene();
  31040. var material = subMesh.getMaterial();
  31041. // Alpha test
  31042. if (material && material.needAlphaTesting()) {
  31043. defines.push("#define ALPHATEST");
  31044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31045. attribs.push(BABYLON.VertexBuffer.UVKind);
  31046. defines.push("#define UV1");
  31047. }
  31048. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31050. defines.push("#define UV2");
  31051. }
  31052. }
  31053. // Bones
  31054. if (mesh.useBones) {
  31055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31057. defines.push("#define BONES");
  31058. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31059. }
  31060. // Instances
  31061. if (useInstances) {
  31062. defines.push("#define INSTANCES");
  31063. attribs.push("world0");
  31064. attribs.push("world1");
  31065. attribs.push("world2");
  31066. attribs.push("world3");
  31067. }
  31068. // Get correct effect
  31069. var join = defines.join("\n");
  31070. if (this._cachedDefines !== join) {
  31071. this._cachedDefines = join;
  31072. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31073. }
  31074. return this._effect.isReady();
  31075. };
  31076. DepthRenderer.prototype.getDepthMap = function () {
  31077. return this._depthMap;
  31078. };
  31079. // Methods
  31080. DepthRenderer.prototype.dispose = function () {
  31081. this._depthMap.dispose();
  31082. };
  31083. return DepthRenderer;
  31084. })();
  31085. BABYLON.DepthRenderer = DepthRenderer;
  31086. })(BABYLON || (BABYLON = {}));
  31087. //# sourceMappingURL=babylon.depthRenderer.js.map
  31088. var __extends = this.__extends || function (d, b) {
  31089. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31090. function __() { this.constructor = d; }
  31091. __.prototype = b.prototype;
  31092. d.prototype = new __();
  31093. };
  31094. var BABYLON;
  31095. (function (BABYLON) {
  31096. var SSAORenderingPipeline = (function (_super) {
  31097. __extends(SSAORenderingPipeline, _super);
  31098. /**
  31099. * @constructor
  31100. * @param {string} name - The rendering pipeline name
  31101. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31102. * @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 }
  31103. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31104. */
  31105. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31106. var _this = this;
  31107. _super.call(this, scene.getEngine(), name);
  31108. // Members
  31109. /**
  31110. * The PassPostProcess id in the pipeline that contains the original scene color
  31111. * @type {string}
  31112. */
  31113. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31114. /**
  31115. * The SSAO PostProcess id in the pipeline
  31116. * @type {string}
  31117. */
  31118. this.SSAORenderEffect = "SSAORenderEffect";
  31119. /**
  31120. * The horizontal blur PostProcess id in the pipeline
  31121. * @type {string}
  31122. */
  31123. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31124. /**
  31125. * The vertical blur PostProcess id in the pipeline
  31126. * @type {string}
  31127. */
  31128. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31129. /**
  31130. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31131. * @type {string}
  31132. */
  31133. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31134. /**
  31135. * The output strength of the SSAO post-process. Default value is 1.0.
  31136. * @type {number}
  31137. */
  31138. this.totalStrength = 1.0;
  31139. /**
  31140. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31141. * @type {number}
  31142. */
  31143. this.radius = 0.0002;
  31144. /**
  31145. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31146. * Must not be equal to fallOff and superior to fallOff.
  31147. * Default value is 0.0075
  31148. * @type {number}
  31149. */
  31150. this.area = 0.0075;
  31151. /**
  31152. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31153. * Must not be equal to area and inferior to area.
  31154. * Default value is 0.0002
  31155. * @type {number}
  31156. */
  31157. this.fallOff = 0.0002;
  31158. this._firstUpdate = true;
  31159. this._scene = scene;
  31160. // Set up assets
  31161. this._createRandomTexture();
  31162. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31163. var ssaoRatio = ratio.ssaoRatio || ratio;
  31164. var combineRatio = ratio.combineRatio || ratio;
  31165. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31166. this._createSSAOPostProcess(ssaoRatio);
  31167. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31168. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31169. this._createSSAOCombinePostProcess(combineRatio);
  31170. // Set up pipeline
  31171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  31172. return _this._originalColorPostProcess;
  31173. }, true));
  31174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  31175. return _this._ssaoPostProcess;
  31176. }, true));
  31177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  31178. return _this._blurHPostProcess;
  31179. }, true));
  31180. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  31181. return _this._blurVPostProcess;
  31182. }, true));
  31183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  31184. return _this._ssaoCombinePostProcess;
  31185. }, true));
  31186. // Finish
  31187. scene.postProcessRenderPipelineManager.addPipeline(this);
  31188. if (cameras)
  31189. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31190. }
  31191. // Public Methods
  31192. /**
  31193. * Returns the horizontal blur PostProcess
  31194. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31195. */
  31196. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31197. return this._blurHPostProcess;
  31198. };
  31199. /**
  31200. * Returns the vertical blur PostProcess
  31201. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31202. */
  31203. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31204. return this._blurVPostProcess;
  31205. };
  31206. /**
  31207. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31208. */
  31209. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31210. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31211. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31212. this._originalColorPostProcess = undefined;
  31213. this._ssaoPostProcess = undefined;
  31214. this._blurHPostProcess = undefined;
  31215. this._blurVPostProcess = undefined;
  31216. this._ssaoCombinePostProcess = undefined;
  31217. this._randomTexture.dispose();
  31218. if (disableDepthRender)
  31219. this._scene.disableDepthRenderer();
  31220. };
  31221. // Private Methods
  31222. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31223. var _this = this;
  31224. var sampleSphere = [
  31225. 0.5381,
  31226. 0.1856,
  31227. -0.4319,
  31228. 0.1379,
  31229. 0.2486,
  31230. 0.4430,
  31231. 0.3371,
  31232. 0.5679,
  31233. -0.0057,
  31234. -0.6999,
  31235. -0.0451,
  31236. -0.0019,
  31237. 0.0689,
  31238. -0.1598,
  31239. -0.8547,
  31240. 0.0560,
  31241. 0.0069,
  31242. -0.1843,
  31243. -0.0146,
  31244. 0.1402,
  31245. 0.0762,
  31246. 0.0100,
  31247. -0.1924,
  31248. -0.0344,
  31249. -0.3577,
  31250. -0.5301,
  31251. -0.4358,
  31252. -0.3169,
  31253. 0.1063,
  31254. 0.0158,
  31255. 0.0103,
  31256. -0.5869,
  31257. 0.0046,
  31258. -0.0897,
  31259. -0.4940,
  31260. 0.3287,
  31261. 0.7119,
  31262. -0.0154,
  31263. -0.0918,
  31264. -0.0533,
  31265. 0.0596,
  31266. -0.5411,
  31267. 0.0352,
  31268. -0.0631,
  31269. 0.5460,
  31270. -0.4776,
  31271. 0.2847,
  31272. -0.0271
  31273. ];
  31274. var samplesFactor = 1.0 / 16.0;
  31275. 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);
  31276. this._ssaoPostProcess.onApply = function (effect) {
  31277. if (_this._firstUpdate) {
  31278. effect.setArray3("sampleSphere", sampleSphere);
  31279. effect.setFloat("samplesFactor", samplesFactor);
  31280. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31281. _this._firstUpdate = false;
  31282. }
  31283. effect.setFloat("totalStrength", _this.totalStrength);
  31284. effect.setFloat("radius", _this.radius);
  31285. effect.setFloat("area", _this.area);
  31286. effect.setFloat("fallOff", _this.fallOff);
  31287. effect.setTexture("textureSampler", _this._depthTexture);
  31288. effect.setTexture("randomSampler", _this._randomTexture);
  31289. };
  31290. };
  31291. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31292. var _this = this;
  31293. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31294. this._ssaoCombinePostProcess.onApply = function (effect) {
  31295. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31296. };
  31297. };
  31298. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31299. var size = 512;
  31300. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31301. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31302. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31303. var context = this._randomTexture.getContext();
  31304. var rand = function (min, max) {
  31305. return Math.random() * (max - min) + min;
  31306. };
  31307. for (var x = 0; x < size; x++) {
  31308. for (var y = 0; y < size; y++) {
  31309. var randVector = BABYLON.Vector3.Zero();
  31310. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31311. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31312. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31313. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31314. context.fillRect(x, y, 1, 1);
  31315. }
  31316. }
  31317. this._randomTexture.update(false);
  31318. };
  31319. return SSAORenderingPipeline;
  31320. })(BABYLON.PostProcessRenderPipeline);
  31321. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31322. })(BABYLON || (BABYLON = {}));
  31323. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31324. var __extends = this.__extends || function (d, b) {
  31325. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31326. function __() { this.constructor = d; }
  31327. __.prototype = b.prototype;
  31328. d.prototype = new __();
  31329. };
  31330. var BABYLON;
  31331. (function (BABYLON) {
  31332. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31333. var VolumetricLightScatteringPostProcess = (function (_super) {
  31334. __extends(VolumetricLightScatteringPostProcess, _super);
  31335. /**
  31336. * @constructor
  31337. * @param {string} name - The post-process name
  31338. * @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)
  31339. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31340. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31341. * @param {number} samples - The post-process quality, default 100
  31342. * @param {number} samplingMode - The post-process filtering mode
  31343. * @param {BABYLON.Engine} engine - The babylon engine
  31344. * @param {boolean} reusable - If the post-process is reusable
  31345. */
  31346. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31347. var _this = this;
  31348. if (samples === void 0) { samples = 100; }
  31349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31350. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31351. this._screenCoordinates = BABYLON.Vector2.Zero();
  31352. /**
  31353. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31354. * @type {boolean}
  31355. */
  31356. this.useCustomMeshPosition = false;
  31357. /**
  31358. * If the post-process should inverse the light scattering direction
  31359. * @type {boolean}
  31360. */
  31361. this.invert = true;
  31362. /**
  31363. * Array containing the excluded meshes not rendered in the internal pass
  31364. */
  31365. this.excludedMeshes = new Array();
  31366. this.exposure = 0.3;
  31367. this.decay = 0.96815;
  31368. this.weight = 0.58767;
  31369. this.density = 0.926;
  31370. var scene = camera.getScene();
  31371. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31372. // Configure mesh
  31373. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31374. // Configure
  31375. this._createPass(scene, ratio.passRatio || ratio);
  31376. this.onApply = function (effect) {
  31377. _this._updateMeshScreenCoordinates(scene);
  31378. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31379. effect.setFloat("exposure", _this.exposure);
  31380. effect.setFloat("decay", _this.decay);
  31381. effect.setFloat("weight", _this.weight);
  31382. effect.setFloat("density", _this.density);
  31383. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31384. };
  31385. }
  31386. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31387. var mesh = subMesh.getMesh();
  31388. var defines = [];
  31389. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31390. var material = subMesh.getMaterial();
  31391. var needUV = false;
  31392. // Render this.mesh as default
  31393. if (mesh === this.mesh) {
  31394. defines.push("#define BASIC_RENDER");
  31395. defines.push("#define NEED_UV");
  31396. needUV = true;
  31397. }
  31398. // Alpha test
  31399. if (material) {
  31400. if (material.needAlphaTesting() || mesh === this.mesh)
  31401. defines.push("#define ALPHATEST");
  31402. if (material.opacityTexture !== undefined) {
  31403. defines.push("#define OPACITY");
  31404. if (material.opacityTexture.getAlphaFromRGB)
  31405. defines.push("#define OPACITYRGB");
  31406. if (!needUV)
  31407. defines.push("#define NEED_UV");
  31408. }
  31409. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31410. attribs.push(BABYLON.VertexBuffer.UVKind);
  31411. defines.push("#define UV1");
  31412. }
  31413. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31414. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31415. defines.push("#define UV2");
  31416. }
  31417. }
  31418. // Bones
  31419. if (mesh.useBones) {
  31420. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31421. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31422. defines.push("#define BONES");
  31423. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31424. }
  31425. // Instances
  31426. if (useInstances) {
  31427. defines.push("#define INSTANCES");
  31428. attribs.push("world0");
  31429. attribs.push("world1");
  31430. attribs.push("world2");
  31431. attribs.push("world3");
  31432. }
  31433. // Get correct effect
  31434. var join = defines.join("\n");
  31435. if (this._cachedDefines !== join) {
  31436. this._cachedDefines = join;
  31437. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31438. }
  31439. return this._volumetricLightScatteringPass.isReady();
  31440. };
  31441. /**
  31442. * Sets the new light position for light scattering effect
  31443. * @param {BABYLON.Vector3} The new custom light position
  31444. */
  31445. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31446. this._customMeshPosition = position;
  31447. };
  31448. /**
  31449. * Returns the light position for light scattering effect
  31450. * @return {BABYLON.Vector3} The custom light position
  31451. */
  31452. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31453. return this._customMeshPosition;
  31454. };
  31455. /**
  31456. * Disposes the internal assets and detaches the post-process from the camera
  31457. */
  31458. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31459. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31460. if (rttIndex !== -1) {
  31461. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31462. }
  31463. this._volumetricLightScatteringRTT.dispose();
  31464. _super.prototype.dispose.call(this, camera);
  31465. };
  31466. /**
  31467. * Returns the render target texture used by the post-process
  31468. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31469. */
  31470. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31471. return this._volumetricLightScatteringRTT;
  31472. };
  31473. // Private methods
  31474. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31475. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31476. return true;
  31477. }
  31478. return false;
  31479. };
  31480. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31481. var _this = this;
  31482. var engine = scene.getEngine();
  31483. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31484. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31485. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31486. this._volumetricLightScatteringRTT.renderList = null;
  31487. this._volumetricLightScatteringRTT.renderParticles = false;
  31488. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31489. // Custom render function for submeshes
  31490. var renderSubMesh = function (subMesh) {
  31491. var mesh = subMesh.getRenderingMesh();
  31492. if (_this._meshExcluded(mesh)) {
  31493. return;
  31494. }
  31495. var scene = mesh.getScene();
  31496. var engine = scene.getEngine();
  31497. // Culling
  31498. engine.setState(subMesh.getMaterial().backFaceCulling);
  31499. // Managing instances
  31500. var batch = mesh._getInstancesRenderList(subMesh._id);
  31501. if (batch.mustReturn) {
  31502. return;
  31503. }
  31504. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31505. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31506. engine.enableEffect(_this._volumetricLightScatteringPass);
  31507. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31508. var material = subMesh.getMaterial();
  31509. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31510. // Alpha test
  31511. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31512. var alphaTexture = material.getAlphaTestTexture();
  31513. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31514. if (alphaTexture) {
  31515. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31516. }
  31517. if (material.opacityTexture !== undefined) {
  31518. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31519. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31520. }
  31521. }
  31522. // Bones
  31523. if (mesh.useBones) {
  31524. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31525. }
  31526. // Draw
  31527. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31528. }
  31529. };
  31530. // Render target texture callbacks
  31531. var savedSceneClearColor;
  31532. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31533. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31534. savedSceneClearColor = scene.clearColor;
  31535. scene.clearColor = sceneClearColor;
  31536. };
  31537. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31538. scene.clearColor = savedSceneClearColor;
  31539. };
  31540. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31541. var engine = scene.getEngine();
  31542. var index;
  31543. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31544. renderSubMesh(opaqueSubMeshes.data[index]);
  31545. }
  31546. engine.setAlphaTesting(true);
  31547. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31548. renderSubMesh(alphaTestSubMeshes.data[index]);
  31549. }
  31550. engine.setAlphaTesting(false);
  31551. if (transparentSubMeshes.length) {
  31552. for (index = 0; index < transparentSubMeshes.length; index++) {
  31553. var submesh = transparentSubMeshes.data[index];
  31554. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31555. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31556. }
  31557. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31558. sortedArray.sort(function (a, b) {
  31559. // Alpha index first
  31560. if (a._alphaIndex > b._alphaIndex) {
  31561. return 1;
  31562. }
  31563. if (a._alphaIndex < b._alphaIndex) {
  31564. return -1;
  31565. }
  31566. // Then distance to camera
  31567. if (a._distanceToCamera < b._distanceToCamera) {
  31568. return 1;
  31569. }
  31570. if (a._distanceToCamera > b._distanceToCamera) {
  31571. return -1;
  31572. }
  31573. return 0;
  31574. });
  31575. // Render sub meshes
  31576. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31577. for (index = 0; index < sortedArray.length; index++) {
  31578. renderSubMesh(sortedArray[index]);
  31579. }
  31580. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31581. }
  31582. };
  31583. };
  31584. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31585. var transform = scene.getTransformMatrix();
  31586. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31587. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31588. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31589. if (this.invert)
  31590. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31591. };
  31592. // Static methods
  31593. /**
  31594. * Creates a default mesh for the Volumeric Light Scattering post-process
  31595. * @param {string} The mesh name
  31596. * @param {BABYLON.Scene} The scene where to create the mesh
  31597. * @return {BABYLON.Mesh} the default mesh
  31598. */
  31599. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31600. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31601. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31602. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31603. return mesh;
  31604. };
  31605. return VolumetricLightScatteringPostProcess;
  31606. })(BABYLON.PostProcess);
  31607. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31608. })(BABYLON || (BABYLON = {}));
  31609. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31610. var __extends = this.__extends || function (d, b) {
  31611. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31612. function __() { this.constructor = d; }
  31613. __.prototype = b.prototype;
  31614. d.prototype = new __();
  31615. };
  31616. var BABYLON;
  31617. (function (BABYLON) {
  31618. var LensRenderingPipeline = (function (_super) {
  31619. __extends(LensRenderingPipeline, _super);
  31620. /**
  31621. * @constructor
  31622. *
  31623. * Effect parameters are as follow:
  31624. * {
  31625. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31626. * edge_blur: number; // from 0 to x (1 for realism)
  31627. * distortion: number; // from 0 to x (1 for realism)
  31628. * grain_amount: number; // from 0 to 1
  31629. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31630. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31631. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31632. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31633. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31634. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31635. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31636. * }
  31637. * Note: if an effect parameter is unset, effect is disabled
  31638. *
  31639. * @param {string} name - The rendering pipeline name
  31640. * @param {object} parameters - An object containing all parameters (see above)
  31641. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31642. * @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)
  31643. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31644. */
  31645. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31646. var _this = this;
  31647. if (ratio === void 0) { ratio = 1.0; }
  31648. _super.call(this, scene.getEngine(), name);
  31649. // Lens effects can be of the following:
  31650. // - chromatic aberration (slight shift of RGB colors)
  31651. // - blur on the edge of the lens
  31652. // - lens distortion
  31653. // - depth-of-field blur & highlights enhancing
  31654. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31655. // - grain effect (noise or custom texture)
  31656. // Two additional texture samplers are needed:
  31657. // - depth map (for depth-of-field)
  31658. // - grain texture
  31659. /**
  31660. * The chromatic aberration PostProcess id in the pipeline
  31661. * @type {string}
  31662. */
  31663. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31664. /**
  31665. * The highlights enhancing PostProcess id in the pipeline
  31666. * @type {string}
  31667. */
  31668. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31669. /**
  31670. * The depth-of-field PostProcess id in the pipeline
  31671. * @type {string}
  31672. */
  31673. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31674. this._scene = scene;
  31675. // Fetch texture samplers
  31676. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31677. if (parameters.grain_texture) {
  31678. this._grainTexture = parameters.grain_texture;
  31679. }
  31680. else {
  31681. this._createGrainTexture();
  31682. }
  31683. // save parameters
  31684. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31685. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31686. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31687. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31688. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31689. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31690. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31691. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31692. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31693. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31694. // Create effects
  31695. this._createChromaticAberrationPostProcess(ratio);
  31696. this._createHighlightsPostProcess(ratio);
  31697. this._createDepthOfFieldPostProcess(ratio);
  31698. // Set up pipeline
  31699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31700. return _this._chromaticAberrationPostProcess;
  31701. }, true));
  31702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31703. return _this._highlightsPostProcess;
  31704. }, true));
  31705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31706. return _this._depthOfFieldPostProcess;
  31707. }, true));
  31708. if (this._highlightsGain == -1) {
  31709. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31710. }
  31711. // Finish
  31712. scene.postProcessRenderPipelineManager.addPipeline(this);
  31713. if (cameras) {
  31714. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31715. }
  31716. }
  31717. // public methods (self explanatory)
  31718. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31719. this._edgeBlur = amount;
  31720. };
  31721. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31722. this._edgeBlur = 0;
  31723. };
  31724. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31725. this._grainAmount = amount;
  31726. };
  31727. LensRenderingPipeline.prototype.disableGrain = function () {
  31728. this._grainAmount = 0;
  31729. };
  31730. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31731. this._chromaticAberration = amount;
  31732. };
  31733. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31734. this._chromaticAberration = 0;
  31735. };
  31736. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31737. this._distortion = amount;
  31738. };
  31739. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31740. this._distortion = 0;
  31741. };
  31742. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31743. this._dofDepth = amount;
  31744. };
  31745. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31746. this._dofDepth = -1;
  31747. };
  31748. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31749. this._dofAperture = amount;
  31750. };
  31751. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31752. this._dofPentagon = true;
  31753. };
  31754. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31755. this._dofPentagon = false;
  31756. };
  31757. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31758. this._blurNoise = true;
  31759. };
  31760. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31761. this._blurNoise = false;
  31762. };
  31763. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31764. this._highlightsGain = amount;
  31765. };
  31766. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31767. if (this._highlightsGain == -1) {
  31768. this._highlightsGain = 1.0;
  31769. }
  31770. this._highlightsThreshold = amount;
  31771. };
  31772. LensRenderingPipeline.prototype.disableHighlights = function () {
  31773. this._highlightsGain = -1;
  31774. };
  31775. /**
  31776. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31777. */
  31778. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31779. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31780. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31781. this._chromaticAberrationPostProcess = undefined;
  31782. this._highlightsPostProcess = undefined;
  31783. this._depthOfFieldPostProcess = undefined;
  31784. this._grainTexture.dispose();
  31785. if (disableDepthRender)
  31786. this._scene.disableDepthRenderer();
  31787. };
  31788. // colors shifting and distortion
  31789. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31790. var _this = this;
  31791. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31792. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31793. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31794. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31795. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31796. };
  31797. };
  31798. // highlights enhancing
  31799. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31800. var _this = this;
  31801. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31802. this._highlightsPostProcess.onApply = function (effect) {
  31803. effect.setFloat('gain', _this._highlightsGain);
  31804. effect.setFloat('threshold', _this._highlightsThreshold);
  31805. effect.setBool('pentagon', _this._dofPentagon);
  31806. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31807. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31808. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31809. };
  31810. };
  31811. // colors shifting and distortion
  31812. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31813. var _this = this;
  31814. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31815. "focus_depth",
  31816. "aperture",
  31817. "pentagon",
  31818. "maxZ",
  31819. "edge_blur",
  31820. "chromatic_aberration",
  31821. "distortion",
  31822. "blur_noise",
  31823. "grain_amount",
  31824. "screen_width",
  31825. "screen_height",
  31826. "highlights"
  31827. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31828. this._depthOfFieldPostProcess.onApply = function (effect) {
  31829. effect.setBool('blur_noise', _this._blurNoise);
  31830. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31831. effect.setFloat('grain_amount', _this._grainAmount);
  31832. effect.setTexture("depthSampler", _this._depthTexture);
  31833. effect.setTexture("grainSampler", _this._grainTexture);
  31834. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31835. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31836. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31837. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31838. effect.setFloat('distortion', _this._distortion);
  31839. effect.setFloat('focus_depth', _this._dofDepth);
  31840. effect.setFloat('aperture', _this._dofAperture);
  31841. effect.setFloat('edge_blur', _this._edgeBlur);
  31842. effect.setBool('highlights', (_this._highlightsGain != -1));
  31843. };
  31844. };
  31845. // creates a black and white random noise texture, 512x512
  31846. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31847. var size = 512;
  31848. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31849. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31850. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31851. var context = this._grainTexture.getContext();
  31852. var rand = function (min, max) {
  31853. return Math.random() * (max - min) + min;
  31854. };
  31855. var value;
  31856. for (var x = 0; x < size; x++) {
  31857. for (var y = 0; y < size; y++) {
  31858. value = Math.floor(rand(0.42, 0.58) * 255);
  31859. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31860. context.fillRect(x, y, 1, 1);
  31861. }
  31862. }
  31863. this._grainTexture.update(false);
  31864. };
  31865. return LensRenderingPipeline;
  31866. })(BABYLON.PostProcessRenderPipeline);
  31867. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31868. })(BABYLON || (BABYLON = {}));
  31869. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31870. //
  31871. // This post-process allows the modification of rendered colors by using
  31872. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31873. //
  31874. // The object needs to be provided an url to a texture containing the color
  31875. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31876. // Use an image editing software to tweak the LUT to match your needs.
  31877. //
  31878. // For an example of a color LUT, see here:
  31879. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31880. // For explanations on color grading, see here:
  31881. // http://udn.epicgames.com/Three/ColorGrading.html
  31882. //
  31883. var __extends = this.__extends || function (d, b) {
  31884. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31885. function __() { this.constructor = d; }
  31886. __.prototype = b.prototype;
  31887. d.prototype = new __();
  31888. };
  31889. var BABYLON;
  31890. (function (BABYLON) {
  31891. var ColorCorrectionPostProcess = (function (_super) {
  31892. __extends(ColorCorrectionPostProcess, _super);
  31893. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31894. var _this = this;
  31895. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31896. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31897. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31898. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31899. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31900. this.onApply = function (effect) {
  31901. effect.setTexture("colorTable", _this._colorTableTexture);
  31902. };
  31903. }
  31904. return ColorCorrectionPostProcess;
  31905. })(BABYLON.PostProcess);
  31906. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31907. })(BABYLON || (BABYLON = {}));
  31908. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31909. var __extends = this.__extends || function (d, b) {
  31910. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31911. function __() { this.constructor = d; }
  31912. __.prototype = b.prototype;
  31913. d.prototype = new __();
  31914. };
  31915. var BABYLON;
  31916. (function (BABYLON) {
  31917. var StereogramFreeCamera = (function (_super) {
  31918. __extends(StereogramFreeCamera, _super);
  31919. function StereogramFreeCamera(name, position, eyeSpace, isVertical, scene) {
  31920. _super.call(this, name, position, scene);
  31921. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31922. }
  31923. return StereogramFreeCamera;
  31924. })(BABYLON.FreeCamera);
  31925. BABYLON.StereogramFreeCamera = StereogramFreeCamera;
  31926. var StereogramArcRotateCamera = (function (_super) {
  31927. __extends(StereogramArcRotateCamera, _super);
  31928. function StereogramArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  31929. _super.call(this, name, alpha, beta, radius, target, scene);
  31930. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31931. }
  31932. return StereogramArcRotateCamera;
  31933. })(BABYLON.ArcRotateCamera);
  31934. BABYLON.StereogramArcRotateCamera = StereogramArcRotateCamera;
  31935. var StereogramGamepadCamera = (function (_super) {
  31936. __extends(StereogramGamepadCamera, _super);
  31937. function StereogramGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  31938. _super.call(this, name, position, scene);
  31939. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31940. }
  31941. return StereogramGamepadCamera;
  31942. })(BABYLON.GamepadCamera);
  31943. BABYLON.StereogramGamepadCamera = StereogramGamepadCamera;
  31944. })(BABYLON || (BABYLON = {}));
  31945. //# sourceMappingURL=babylon.stereogramCamera.js.map
  31946. 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}","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","stereogramInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOGRAM_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\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","vrDistortionCorrectionPixelShader":"#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}","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}"};
  31947. 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,r){return new t(i/255,o/255,r/255)},t.Lerp=function(i,o,r){var n=i.r+(o.r-i.r)*r,s=i.g+(o.g-i.g)*r,e=i.b+(o.b-i.b)*r;return new t(n,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,r){this.r=t,this.g=i,this.b=o,this.a=r}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,r){var n=new t(0,0,0,0);return t.LerpToRef(i,o,r,n),n},t.LerpToRef=function(t,i,o,r){r.r=t.r+(i.r-t.r)*o,r.g=t.g+(i.g-t.g)*o,r.b=t.b+(i.b-t.b)*o,r.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,r,n){return new t(i/255,o/255,r/255,n/255)},t}();t.Color4=o;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},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},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a);return new i(h,u)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;return s=s>r.y?r.y:s,s=s<o.y?o.y:s,new i(n,s)},i.Hermite=function(t,o,r,n,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m;return new i(f,x)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r;return new i(n,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var r=t.x<o.x?t.x:o.x,n=t.y<o.y?t.y:o.y;return new i(r,n)},i.Maximize=function(t,o){var r=t.x>o.x?t.x:o.x,n=t.y>o.y?t.y:o.y;return new i(r,n)},i.Transform=function(t,o){var r=t.x*o.m[0]+t.y*o.m[4],n=t.x*o.m[1]+t.y*o.m[5];return new i(r,n)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,r=t.y-i.y;return o*o+r*r},i}();t.Vector2=r;var n=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)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=r*a,t.y=-n*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,r){return new i(this.x-t,this.y-o,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r){return r.x=this.x-t,r.y=this.y-i,r.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 i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)&&t.Tools.WithinEpsilon(this.z,i.z)},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,r){return new i(this.x*t,this.y*o,this.z*r)},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,r,n){var s=i.Dot(t,r)-n,e=i.Dot(o,r)-n,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,r){r.x=t,r.y=i,r.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 r=i.Zero();return i.TransformCoordinatesToRef(t,o,r),r},i.TransformCoordinatesToRef=function(t,i,o){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],n=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=r/e,o.y=n/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,r,n){var s=t*r.m[0]+i*r.m[4]+o*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+o*r.m[9]+r.m[13],a=t*r.m[2]+i*r.m[6]+o*r.m[10]+r.m[14],h=t*r.m[3]+i*r.m[7]+o*r.m[11]+r.m[15];n.x=s/h,n.y=e/h,n.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var r=SIMD.float32x4.loadXYZ(t._data,0),n=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(r,0,0,0,0),n),SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,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,r,n){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(r.m,0),u=SIMD.float32x4.load(r.m,4),l=SIMD.float32x4.load(r.m,8),m=SIMD.float32x4.load(r.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,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(n._data,0,f)},i.TransformNormal=function(t,o){var r=i.Zero();return i.TransformNormalToRef(t,o,r),r},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,r,n){n.x=t*r.m[0]+i*r.m[4]+o*r.m[8],n.y=t*r.m[1]+i*r.m[5]+o*r.m[9],n.z=t*r.m[2]+i*r.m[6]+o*r.m[10]},i.CatmullRom=function(t,o,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a),l=.5*(2*o.z+(-t.z+r.z)*s+(2*t.z-5*o.z+4*r.z-n.z)*e+(-t.z+3*o.z-3*r.z+n.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;s=s>r.y?r.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<o.z?o.z:e,new i(n,s,e)},i.Hermite=function(t,o,r,n,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m,y=t.z*h+r.z*u+o.z*l+n.z*m;return new i(f,x,y)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r,e=t.z+(o.z-t.z)*r;return new i(n,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 r=i.Zero();return i.CrossToRef(t,o,r),r},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,r,n){var s=n.width,e=n.height,h=n.x,u=n.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(r).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,r,n,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*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,r,n,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*2-1);var u=i.TransformCoordinates(o,h),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),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,r=t.y-i.y,n=t.z-i.z;return o*o+r*r+n*n},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,r,n){var s,e,a,h=i.Normalize(o),u=(i.Normalize(r),i.Normalize(n)),l=f.X,m=f.Y,x=(f.Z,0),y=0,c=0,p=0,z=0,M=0,w=0,I=-1,d=(Math.PI,0),D=0;0==u.z?M=1:0==u.x?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),a=i.Cross(u,e),s=i.Cross(h,e),i.Dot(u,s)<0&&(I=1),D=i.Dot(h,e),c=Math.acos(D)*I,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),d++);var S,v;return p=0,z=0,M=0,I=-1,0==u.z?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new t.Vector3(p,z,M),v=t.Vector3.Cross(S,e),s=t.Vector3.Cross(u,S),t.Vector3.Dot(e,s)<0&&(I=1),D=t.Vector3.Dot(u,S),y=Math.acos(D)*I,t.Vector3.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),d++),I=-1,s=t.Vector3.Cross(l,e),t.Vector3.Dot(s,m)<0&&(I=1),D=t.Vector3.Dot(e,l),x=-Math.acos(D)*I,0>D&&2>d&&(x=Math.PI+x),new t.Vector3(y,x,c)},i}();t.Vector3=n;var s=function(){function i(t,i,o,r){this.x=t,this.y=i,this.z=o,this.w=r}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,r,n){return new i(this.x-t,this.y-o,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,n.w=this.w-r,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,r){return this.x===t&&this.y===i&&this.z===o&&this.w===r},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,r,n){return new i(this.x*t,this.y*o,this.z*r,this.w*n)},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,r){return this.x=t,this.y=i,this.z=o,this.w=r,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,r,n){n.x=t,n.y=i,n.z=o,n.w=r},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,r=t.y-i.y,n=t.z-i.z,s=t.w-i.w;return o*o+r*r+n*n+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,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=o,this.w=r}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,r){return this.x=t,this.y=i,this.z=o,this.w=r,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){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,n=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,r,n,s),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=n.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,r=this.z,n=this.w,s=i*o,e=i*r,a=n*o,h=n*r,u=n*i,l=o*r,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-r*r)):(t.x=Math.atan2(s-h,.5-f-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,r=this.z*this.z,n=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+r),t.m[1]=2*(n+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(n-s),t.m[5]=1-2*(r+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,r=t.m,n=r[0],s=r[4],e=r[8],a=r[1],h=r[5],u=r[9],l=r[2],m=r[6],f=r[10],x=n+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):n>h&&n>f?(o=2*Math.sqrt(1+n-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-n-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-n-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/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 r=new t,n=Math.sin(o/2);return r.w=Math.cos(o/2),r.x=i.x*n,r.y=i.y*n,r.z=i.z*n,r},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,r){var n=new t;return t.RotationYawPitchRollToRef(i,o,r,n),n},t.RotationYawPitchRollToRef=function(t,i,o,r){var n=.5*o,s=.5*i,e=.5*t,a=Math.sin(n),h=Math.cos(n),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);r.x=f*u*h+m*l*a,r.y=m*l*h-f*u*a,r.z=f*l*a-m*u*h,r.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,r){var n=new t;return t.RotationAlphaBetaGammaToRef(i,o,r,n),n},t.RotationAlphaBetaGammaToRef=function(t,i,o,r){var n=.5*(o+t),s=.5*(o-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(n)*Math.cos(e),r.w=Math.cos(n)*Math.cos(e)},t.Slerp=function(i,o,r){var n,s,e=r,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,n=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,n=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+n*o.x,s*i.y+n*o.y,s*i.z+n*o.z,s*i.w+n*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],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=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]*r+this.m[7]*n)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*n+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],r=this.m[2],n=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,I=u*p-f*x,d=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*I+h*d),g=s*M-e*I+h*D,T=-(s*w-e*d+a*D),R=1/(i*S+o*v+r*g+n*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*m,q=e*f-h*l,V=e*m-a*l,E=s*f-h*u,Z=s*m-a*u,N=s*l-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-r*M+n*w)*R,t.m[5]=(i*z-r*I+n*d)*R,t.m[9]=-(i*M-o*I+n*D)*R,t.m[13]=(i*w-o*d+r*D)*R,t.m[2]=(o*_-r*b+n*A)*R,t.m[6]=-(i*_-r*F+n*P)*R,t.m[10]=(i*b-o*F+n*C)*R,t.m[14]=-(i*A-o*P+r*C)*R,t.m[3]=-(o*L-r*q+n*V)*R,t.m[7]=(i*L-r*E+n*Z)*R,t.m[11]=-(i*q-o*E+n*N)*R,t.m[15]=(i*V-o*Z+r*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,r,n,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,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),n=SIMD.float32x4.shuffle(c,p,2,3,6,7),r=SIMD.float32x4.shuffle(s,n,0,2,4,6),n=SIMD.float32x4.shuffle(n,s,1,3,5,7),s=SIMD.float32x4.mul(r,n),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,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,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(n,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),n),s=SIMD.float32x4.swizzle(s,1,0,3,2),r=SIMD.float32x4.swizzle(r,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,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(r,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(n,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(r,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,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(r,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,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(n,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,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 r=this.m[0],n=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=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],I=t.m[1],d=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]=r*w+n*S+s*R+e*F,i[o+1]=r*I+n*v+s*_+e*P,i[o+2]=r*d+n*g+s*b+e*C,i[o+3]=r*D+n*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+l*F,i[o+5]=a*I+h*v+u*_+l*P,i[o+6]=a*d+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*A+l*L,i[o+8]=m*w+f*S+x*R+y*F,i[o+9]=m*I+f*v+x*_+y*P,i[o+10]=m*d+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*I+p*v+z*_+M*P,i[o+14]=c*d+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 r=this.m,n=t.m,s=SIMD.float32x4.load(n,0),e=SIMD.float32x4.load(n,4),a=SIMD.float32x4.load(n,8),h=SIMD.float32x4.load(n,12),u=SIMD.float32x4.load(r,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 l=SIMD.float32x4.load(r,4);SIMD.float32x4.store(i,o+4,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 m=SIMD.float32x4.load(r,8);SIMD.float32x4.store(i,o+8,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 f=SIMD.float32x4.load(r,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]);\n\n},i.prototype.decompose=function(o,r,n){n.x=this.m[12],n.y=this.m[13],n.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 r.x=0,r.y=0,r.z=0,r.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,r),!0},i.FromArray=function(t,o){var r=new i;return o||(o=0),i.FromArrayToRef(t,o,r),r},i.FromArrayToRef=function(t,i,o){for(var r=0;16>r;r++)o.m[r]=t[r+i]},i.FromValuesToRef=function(t,i,o,r,n,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=r,p.m[4]=n,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,r,n,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=r,z.m[3]=n,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,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,r){var n=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),n=n.multiply(s),n.setTranslation(r),n},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),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,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),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-o,i.m[8]=o,i.m[10]=r,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),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=o,i.m[4]=-o,i.m[5]=r,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 r=Math.sin(-o),n=Math.cos(-o),s=1-n;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+n,e.m[1]=t.x*t.y*s-t.z*r,e.m[2]=t.x*t.z*s+t.y*r,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*r,e.m[5]=t.y*t.y*s+n,e.m[6]=t.y*t.z*s-t.x*r,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*r,e.m[9]=t.z*t.y*s+t.x*r,e.m[10]=t.z*t.z*s+n,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,r){var n=new i;return i.RotationYawPitchRollToRef(t,o,r,n),n},i.RotationYawPitchRollToRef=function(t,i,o,r){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,o,r){var n=i.Zero();return i.ScalingToRef(t,o,r,n),n},i.ScalingToRef=function(t,i,o,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=o,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,o,r){var n=i.Identity();return i.TranslationToRef(t,o,r,n),n},i.TranslationToRef=function(t,o,r,n){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,r,1,n)},i.LookAtLH=function(t,o,r){var n=i.Zero();return i.LookAtLHToRef(t,o,r,n),n},i.LookAtLHToRef=function(t,o,r,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),h=-n.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,r){var n=r.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 l=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(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,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(l,m,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),I=SIMD.float32x4(0,1,0,0),d=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(n,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(n,4,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(n,8,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(n,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,r,n){var s=i.Zero();return i.OrthoLHToRef(t,o,r,n,s),s},i.OrthoLHToRef=function(t,o,r,n,s){var e=2/t,a=2/o,h=1/(n-r),u=r/(r-n);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,r,n,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,r,n,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,r,n,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(n-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+o)/(o-r),e.m[14]=n/(n-s),e.m[15]=1},i.PerspectiveLH=function(t,o,r,n){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-n/(r-n),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n),s},i.PerspectiveFovLH=function(t,o,r,n){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,r,n,s),s},i.PerspectiveFovLHToRef=function(i,o,r,n,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]=-n/(r-n),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n)},i.GetFinalMatrix=function(t,o,r,n,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(r).multiply(n).multiply(m)},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,r=t.normal.y,n=t.normal.z,s=-2*o,e=-2*r,a=-2*n;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=a*r,i.m[7]=0,i.m[8]=s*n,i.m[9]=e*n,i.m[10]=a*n+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=n.Zero(),i._yAxis=n.Zero(),i._zAxis=n.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,r){this.normal=new n(t,i,o),this.d=r}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),r=this.normal.x,n=this.normal.y,s=this.normal.z,e=this.d,h=r*o.m[0]+n*o.m[1]+s*o.m[2]+e*o.m[3],u=r*o.m[4]+n*o.m[5]+s*o.m[6]+e*o.m[7],l=r*o.m[8]+n*o.m[9]+s*o.m[10]+e*o.m[11],m=r*o.m[12]+n*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},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 r,n=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,l=s*u-e*h,m=e*a-n*u,f=n*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return r=0!==x?1/x:0,this.normal.x=l*r,this.normal.y=m*r,this.normal.z=f*r,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=n.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return n.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,r){var n=new t(0,0,0,0);return n.copyFromPoints(i,o,r),n},t.FromPositionAndNormal=function(i,o){var r=new t(0,0,0,0);return o.normalize(),r.normal=o,r.d=-(o.x*i.x+o.y*i.y+o.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return n.Dot(o,i)+r},t}();t.Plane=h;var u=function(){function t(t,i,o,r){this.x=t,this.y=i,this.width=o,this.height=r}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*o,this.y*r,this.width*o,this.height*r)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],r=0;6>r;r++)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=l;var m=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,r=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 n=1/this.direction.x,s=(t.x-this.origin.x)*n,e=(i.x-this.origin.x)*n;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),r=Math.min(e,r),o>r)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(n=1/this.direction.y,s=(t.y-this.origin.y)*n,e=(i.y-this.origin.y)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)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(n=1/this.direction.z,s=(t.z-this.origin.z)*n,e=(i.z-this.origin.z)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)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,r=t.center.z-this.origin.z,n=i*i+o*o+r*r,s=t.radius*t.radius;if(s>=n)return!0;var e=i*this.direction.x+o*this.direction.y+r*this.direction.z;if(0>e)return!1;var a=n-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,r){this._edge1||(this._edge1=n.Zero(),this._edge2=n.Zero(),this._pvec=n.Zero(),this._tvec=n.Zero(),this._qvec=n.Zero()),o.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),n.CrossToRef(this.direction,this._edge2,this._pvec);var s=n.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=n.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;n.CrossToRef(this._tvec,this._edge1,this._qvec);var h=n.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=n.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,r,s,e,a,h){var u=n.Unproject(new n(t,o,0),r,s,e,a,h),l=n.Unproject(new n(t,o,1),r,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,r){void 0===r&&(r=a.Identity());var n=o.subtract(t),s=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z);return n.normalize(),i.Transform(new i(t,n,s),r)},i.Transform=function(t,o){var r=n.TransformCoordinates(t.origin,o),s=n.TransformNormal(t.direction,o);return new i(r,s,t.length)},i}();t.Ray=m,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 n(1,0,0),t.Y=new n(0,1,0),t.Z=new n(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,r,n){for(var s=1-3*r+3*i,e=3*r-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+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)*n+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 r=o.subtract(i),n=Math.atan2(r.y,r.x);return new t(n)},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 n=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,e=(n-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 r((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(),l=y.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?0:1,this.angle=y.FromDegrees(0===this.orientation?h-l:l-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 n(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 r(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var n=new r(i,o),s=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,n,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 r(i,o),u=new r(n,s),l=new c(a,h,u),m=l.angle.radians()/e;0===l.orientation&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var y=Math.cos(f)*l.radius+l.centerPoint.x,p=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(y,p),f+=m}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.\"),r.Zero();for(var o=i*this.length(),n=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),l=u.length()+n;if(o>=n&&l>=o){var m=u.normalize(),f=o-n;return new r(a.x+m.x*f,a.y+m.y*f)}n=l}return t.Tools.Error(\"internal error\"),r.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],r=this._normalVector(this._curve[0],o,t);this._normals[0]=r,this._normals[0].normalize(),this._binormals[0]=n.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,l=1;i>l;l++)s=this._getLastNonNullVector(l),i-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=n.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=n.Cross(a,this._normals[l]),this._binormals[l].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 r;if(void 0===o||null===o){var s;1!==i.y?s=new n(0,-1,0):1!==i.x?s=new n(1,0,0):1!==i.z&&(s=new n(0,0,1)),r=n.Cross(i,s)}else r=n.Cross(i,o),n.CrossToRef(r,i,r);return r.normalize(),r},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,r,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,r){var n=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*r;return n},h=0;s>=h;h++)e.push(new n(a(h/s,t.x,o.x,r.x),a(h/s,t.y,o.y,r.y),a(h/s,t.z,o.z,r.z)));return new i(e)},i.CreateCubicBezier=function(t,o,r,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,r,n){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*r+t*t*t*n;return s},u=0;e>=u;u++)a.push(new n(h(u/e,t.x,o.x,r.x,s.x),h(u/e,t.y,o.y,r.y,s.y),h(u/e,t.z,o.z,r.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,r,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,r,n,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],r=this._points.slice(),n=t.getPoints(),s=1;s<n.length;s++)r.push(n[s].subtract(n[0]).add(o));var e=new i(r);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 I=function(){function t(t,i){void 0===t&&(t=n.Zero()),void 0===i&&(i=n.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var d=function(){function t(t,i,o){void 0===t&&(t=n.Zero()),void 0===i&&(i=n.Up()),void 0===o&&(o=r.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=d;var D=a.prototype.multiplyToArray,S=a.prototype.invertToRef,v=a.LookAtLHToRef,g=n.TransformCoordinatesToRef,T=n.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,n.TransformCoordinatesToRef=g,n.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,n.TransformCoordinatesToRef=n.TransformCoordinatesToRefSIMD,n.TransformCoordinatesFromFloatsToRef=n.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={}));";