babylon.2.1-beta.debug.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963
  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 () { return new Color3(1, 0, 0); };
  106. Color3.Green = function () { return new Color3(0, 1, 0); };
  107. Color3.Blue = function () { return new Color3(0, 0, 1); };
  108. Color3.Black = function () { return new Color3(0, 0, 0); };
  109. Color3.White = function () { return new Color3(1, 1, 1); };
  110. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  111. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  112. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  113. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  114. return Color3;
  115. })();
  116. BABYLON.Color3 = Color3;
  117. var Color4 = (function () {
  118. function Color4(r, g, b, a) {
  119. this.r = r;
  120. this.g = g;
  121. this.b = b;
  122. this.a = a;
  123. }
  124. // Operators
  125. Color4.prototype.addInPlace = function (right) {
  126. this.r += right.r;
  127. this.g += right.g;
  128. this.b += right.b;
  129. this.a += right.a;
  130. return this;
  131. };
  132. Color4.prototype.asArray = function () {
  133. var result = [];
  134. this.toArray(result, 0);
  135. return result;
  136. };
  137. Color4.prototype.toArray = function (array, index) {
  138. if (index === undefined) {
  139. index = 0;
  140. }
  141. array[index] = this.r;
  142. array[index + 1] = this.g;
  143. array[index + 2] = this.b;
  144. array[index + 3] = this.a;
  145. return this;
  146. };
  147. Color4.prototype.add = function (right) {
  148. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  149. };
  150. Color4.prototype.subtract = function (right) {
  151. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  152. };
  153. Color4.prototype.subtractToRef = function (right, result) {
  154. result.r = this.r - right.r;
  155. result.g = this.g - right.g;
  156. result.b = this.b - right.b;
  157. result.a = this.a - right.a;
  158. return this;
  159. };
  160. Color4.prototype.scale = function (scale) {
  161. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  162. };
  163. Color4.prototype.scaleToRef = function (scale, result) {
  164. result.r = this.r * scale;
  165. result.g = this.g * scale;
  166. result.b = this.b * scale;
  167. result.a = this.a * scale;
  168. return this;
  169. };
  170. Color4.prototype.toString = function () {
  171. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  172. };
  173. Color4.prototype.clone = function () {
  174. return new Color4(this.r, this.g, this.b, this.a);
  175. };
  176. Color4.prototype.copyFrom = function (source) {
  177. this.r = source.r;
  178. this.g = source.g;
  179. this.b = source.b;
  180. this.a = source.a;
  181. return this;
  182. };
  183. // Statics
  184. Color4.Lerp = function (left, right, amount) {
  185. var result = new Color4(0, 0, 0, 0);
  186. Color4.LerpToRef(left, right, amount, result);
  187. return result;
  188. };
  189. Color4.LerpToRef = function (left, right, amount, result) {
  190. result.r = left.r + (right.r - left.r) * amount;
  191. result.g = left.g + (right.g - left.g) * amount;
  192. result.b = left.b + (right.b - left.b) * amount;
  193. result.a = left.a + (right.a - left.a) * amount;
  194. };
  195. Color4.FromArray = function (array, offset) {
  196. if (offset === void 0) { offset = 0; }
  197. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  198. };
  199. Color4.FromInts = function (r, g, b, a) {
  200. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  201. };
  202. return Color4;
  203. })();
  204. BABYLON.Color4 = Color4;
  205. var Vector2 = (function () {
  206. function Vector2(x, y) {
  207. this.x = x;
  208. this.y = y;
  209. }
  210. Vector2.prototype.toString = function () {
  211. return "{X: " + this.x + " Y:" + this.y + "}";
  212. };
  213. // Operators
  214. Vector2.prototype.toArray = function (array, index) {
  215. if (index === void 0) { index = 0; }
  216. array[index] = this.x;
  217. array[index + 1] = this.y;
  218. return this;
  219. };
  220. Vector2.prototype.asArray = function () {
  221. var result = [];
  222. this.toArray(result, 0);
  223. return result;
  224. };
  225. Vector2.prototype.copyFrom = function (source) {
  226. this.x = source.x;
  227. this.y = source.y;
  228. return this;
  229. };
  230. Vector2.prototype.copyFromFloats = function (x, y) {
  231. this.x = x;
  232. this.y = y;
  233. return this;
  234. };
  235. Vector2.prototype.add = function (otherVector) {
  236. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  237. };
  238. Vector2.prototype.addVector3 = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.subtract = function (otherVector) {
  242. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  243. };
  244. Vector2.prototype.subtractInPlace = function (otherVector) {
  245. this.x -= otherVector.x;
  246. this.y -= otherVector.y;
  247. return this;
  248. };
  249. Vector2.prototype.multiplyInPlace = function (otherVector) {
  250. this.x *= otherVector.x;
  251. this.y *= otherVector.y;
  252. return this;
  253. };
  254. Vector2.prototype.multiply = function (otherVector) {
  255. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  256. };
  257. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  258. result.x = this.x * otherVector.x;
  259. result.y = this.y * otherVector.y;
  260. return this;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. return this;
  272. };
  273. Vector2.prototype.negate = function () {
  274. return new Vector2(-this.x, -this.y);
  275. };
  276. Vector2.prototype.scaleInPlace = function (scale) {
  277. this.x *= scale;
  278. this.y *= scale;
  279. return this;
  280. };
  281. Vector2.prototype.scale = function (scale) {
  282. return new Vector2(this.x * scale, this.y * scale);
  283. };
  284. Vector2.prototype.equals = function (otherVector) {
  285. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  286. };
  287. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  288. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  289. };
  290. // Properties
  291. Vector2.prototype.length = function () {
  292. return Math.sqrt(this.x * this.x + this.y * this.y);
  293. };
  294. Vector2.prototype.lengthSquared = function () {
  295. return (this.x * this.x + this.y * this.y);
  296. };
  297. // Methods
  298. Vector2.prototype.normalize = function () {
  299. var len = this.length();
  300. if (len === 0)
  301. return this;
  302. var num = 1.0 / len;
  303. this.x *= num;
  304. this.y *= num;
  305. return this;
  306. };
  307. Vector2.prototype.clone = function () {
  308. return new Vector2(this.x, this.y);
  309. };
  310. // Statics
  311. Vector2.Zero = function () {
  312. return new Vector2(0, 0);
  313. };
  314. Vector2.FromArray = function (array, offset) {
  315. if (offset === void 0) { offset = 0; }
  316. return new Vector2(array[offset], array[offset + 1]);
  317. };
  318. Vector2.FromArrayToRef = function (array, offset, result) {
  319. result.x = array[offset];
  320. result.y = array[offset + 1];
  321. };
  322. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  323. var squared = amount * amount;
  324. var cubed = amount * squared;
  325. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  326. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  327. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  328. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  329. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  330. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === void 0) { index = 0; }
  409. array[index] = this.x;
  410. array[index + 1] = this.y;
  411. array[index + 2] = this.z;
  412. return this;
  413. };
  414. Vector3.prototype.toQuaternion = function () {
  415. var result = new Quaternion(0, 0, 0, 1);
  416. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  417. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  418. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  419. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  420. var cosy = Math.cos(this.y * 0.5);
  421. var siny = Math.sin(this.y * 0.5);
  422. result.x = coszMinusx * siny;
  423. result.y = -sinzMinusx * siny;
  424. result.z = sinxPlusz * cosy;
  425. result.w = cosxPlusz * cosy;
  426. return result;
  427. };
  428. Vector3.prototype.addInPlace = function (otherVector) {
  429. this.x += otherVector.x;
  430. this.y += otherVector.y;
  431. this.z += otherVector.z;
  432. return this;
  433. };
  434. Vector3.prototype.add = function (otherVector) {
  435. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  436. };
  437. Vector3.prototype.addToRef = function (otherVector, result) {
  438. result.x = this.x + otherVector.x;
  439. result.y = this.y + otherVector.y;
  440. result.z = this.z + otherVector.z;
  441. return this;
  442. };
  443. Vector3.prototype.subtractInPlace = function (otherVector) {
  444. this.x -= otherVector.x;
  445. this.y -= otherVector.y;
  446. this.z -= otherVector.z;
  447. return this;
  448. };
  449. Vector3.prototype.subtract = function (otherVector) {
  450. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  451. };
  452. Vector3.prototype.subtractToRef = function (otherVector, result) {
  453. result.x = this.x - otherVector.x;
  454. result.y = this.y - otherVector.y;
  455. result.z = this.z - otherVector.z;
  456. return this;
  457. };
  458. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  459. return new Vector3(this.x - x, this.y - y, this.z - z);
  460. };
  461. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  462. result.x = this.x - x;
  463. result.y = this.y - y;
  464. result.z = this.z - z;
  465. return this;
  466. };
  467. Vector3.prototype.negate = function () {
  468. return new Vector3(-this.x, -this.y, -this.z);
  469. };
  470. Vector3.prototype.scaleInPlace = function (scale) {
  471. this.x *= scale;
  472. this.y *= scale;
  473. this.z *= scale;
  474. return this;
  475. };
  476. Vector3.prototype.scale = function (scale) {
  477. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  478. };
  479. Vector3.prototype.scaleToRef = function (scale, result) {
  480. result.x = this.x * scale;
  481. result.y = this.y * scale;
  482. result.z = this.z * scale;
  483. };
  484. Vector3.prototype.equals = function (otherVector) {
  485. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  486. };
  487. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  488. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  489. };
  490. Vector3.prototype.equalsToFloats = function (x, y, z) {
  491. return this.x === x && this.y === y && this.z === z;
  492. };
  493. Vector3.prototype.multiplyInPlace = function (otherVector) {
  494. this.x *= otherVector.x;
  495. this.y *= otherVector.y;
  496. this.z *= otherVector.z;
  497. return this;
  498. };
  499. Vector3.prototype.multiply = function (otherVector) {
  500. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  501. };
  502. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  503. result.x = this.x * otherVector.x;
  504. result.y = this.y * otherVector.y;
  505. result.z = this.z * otherVector.z;
  506. return this;
  507. };
  508. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  509. return new Vector3(this.x * x, this.y * y, this.z * z);
  510. };
  511. Vector3.prototype.divide = function (otherVector) {
  512. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  513. };
  514. Vector3.prototype.divideToRef = function (otherVector, result) {
  515. result.x = this.x / otherVector.x;
  516. result.y = this.y / otherVector.y;
  517. result.z = this.z / otherVector.z;
  518. return this;
  519. };
  520. Vector3.prototype.MinimizeInPlace = function (other) {
  521. if (other.x < this.x)
  522. this.x = other.x;
  523. if (other.y < this.y)
  524. this.y = other.y;
  525. if (other.z < this.z)
  526. this.z = other.z;
  527. return this;
  528. };
  529. Vector3.prototype.MaximizeInPlace = function (other) {
  530. if (other.x > this.x)
  531. this.x = other.x;
  532. if (other.y > this.y)
  533. this.y = other.y;
  534. if (other.z > this.z)
  535. this.z = other.z;
  536. return this;
  537. };
  538. // Properties
  539. Vector3.prototype.length = function () {
  540. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  541. };
  542. Vector3.prototype.lengthSquared = function () {
  543. return (this.x * this.x + this.y * this.y + this.z * this.z);
  544. };
  545. // Methods
  546. Vector3.prototype.normalize = function () {
  547. var len = this.length();
  548. if (len === 0)
  549. return this;
  550. var num = 1.0 / len;
  551. this.x *= num;
  552. this.y *= num;
  553. this.z *= num;
  554. return this;
  555. };
  556. Vector3.prototype.clone = function () {
  557. return new Vector3(this.x, this.y, this.z);
  558. };
  559. Vector3.prototype.copyFrom = function (source) {
  560. this.x = source.x;
  561. this.y = source.y;
  562. this.z = source.z;
  563. return this;
  564. };
  565. Vector3.prototype.copyFromFloats = function (x, y, z) {
  566. this.x = x;
  567. this.y = y;
  568. this.z = z;
  569. return this;
  570. };
  571. // Statics
  572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  573. var d0 = Vector3.Dot(vector0, axis) - size;
  574. var d1 = Vector3.Dot(vector1, axis) - size;
  575. var s = d0 / (d0 - d1);
  576. return s;
  577. };
  578. Vector3.FromArray = function (array, offset) {
  579. if (!offset) {
  580. offset = 0;
  581. }
  582. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  583. };
  584. Vector3.FromArrayToRef = function (array, offset, result) {
  585. result.x = array[offset];
  586. result.y = array[offset + 1];
  587. result.z = array[offset + 2];
  588. };
  589. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  590. result.x = array[offset];
  591. result.y = array[offset + 1];
  592. result.z = array[offset + 2];
  593. };
  594. Vector3.FromFloatsToRef = function (x, y, z, result) {
  595. result.x = x;
  596. result.y = y;
  597. result.z = z;
  598. };
  599. Vector3.Zero = function () {
  600. return new Vector3(0, 0, 0);
  601. };
  602. Vector3.Up = function () {
  603. return new Vector3(0, 1.0, 0);
  604. };
  605. Vector3.TransformCoordinates = function (vector, transformation) {
  606. var result = Vector3.Zero();
  607. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  608. return result;
  609. };
  610. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  611. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  612. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  613. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  614. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  615. result.x = x / w;
  616. result.y = y / w;
  617. result.z = z / w;
  618. };
  619. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  620. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  621. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  622. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  623. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  624. result.x = rx / rw;
  625. result.y = ry / rw;
  626. result.z = rz / rw;
  627. };
  628. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  629. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  630. var m0 = SIMD.float32x4.load(transformation.m, 0);
  631. var m1 = SIMD.float32x4.load(transformation.m, 4);
  632. var m2 = SIMD.float32x4.load(transformation.m, 8);
  633. var m3 = SIMD.float32x4.load(transformation.m, 12);
  634. 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));
  635. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  636. SIMD.float32x4.storeXYZ(result._data, 0, r);
  637. };
  638. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  639. var v0 = SIMD.float32x4.splat(x);
  640. var v1 = SIMD.float32x4.splat(y);
  641. var v2 = SIMD.float32x4.splat(z);
  642. var m0 = SIMD.float32x4.load(transformation.m, 0);
  643. var m1 = SIMD.float32x4.load(transformation.m, 4);
  644. var m2 = SIMD.float32x4.load(transformation.m, 8);
  645. var m3 = SIMD.float32x4.load(transformation.m, 12);
  646. 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));
  647. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  648. SIMD.float32x4.storeXYZ(result._data, 0, r);
  649. };
  650. Vector3.TransformNormal = function (vector, transformation) {
  651. var result = Vector3.Zero();
  652. Vector3.TransformNormalToRef(vector, transformation, result);
  653. return result;
  654. };
  655. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  656. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  657. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  658. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  659. };
  660. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  661. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  662. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  663. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  664. };
  665. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  666. var squared = amount * amount;
  667. var cubed = amount * squared;
  668. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  669. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  670. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  671. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  672. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  673. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  674. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  675. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  676. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  677. return new Vector3(x, y, z);
  678. };
  679. Vector3.Clamp = function (value, min, max) {
  680. var x = value.x;
  681. x = (x > max.x) ? max.x : x;
  682. x = (x < min.x) ? min.x : x;
  683. var y = value.y;
  684. y = (y > max.y) ? max.y : y;
  685. y = (y < min.y) ? min.y : y;
  686. var z = value.z;
  687. z = (z > max.z) ? max.z : z;
  688. z = (z < min.z) ? min.z : z;
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  692. var squared = amount * amount;
  693. var cubed = amount * squared;
  694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  696. var part3 = (cubed - (2.0 * squared)) + amount;
  697. var part4 = cubed - squared;
  698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  701. return new Vector3(x, y, z);
  702. };
  703. Vector3.Lerp = function (start, end, amount) {
  704. var x = start.x + ((end.x - start.x) * amount);
  705. var y = start.y + ((end.y - start.y) * amount);
  706. var z = start.z + ((end.z - start.z) * amount);
  707. return new Vector3(x, y, z);
  708. };
  709. Vector3.Dot = function (left, right) {
  710. return (left.x * right.x + left.y * right.y + left.z * right.z);
  711. };
  712. Vector3.Cross = function (left, right) {
  713. var result = Vector3.Zero();
  714. Vector3.CrossToRef(left, right, result);
  715. return result;
  716. };
  717. Vector3.CrossToRef = function (left, right, result) {
  718. result.x = left.y * right.z - left.z * right.y;
  719. result.y = left.z * right.x - left.x * right.z;
  720. result.z = left.x * right.y - left.y * right.x;
  721. };
  722. Vector3.Normalize = function (vector) {
  723. var result = Vector3.Zero();
  724. Vector3.NormalizeToRef(vector, result);
  725. return result;
  726. };
  727. Vector3.NormalizeToRef = function (vector, result) {
  728. result.copyFrom(vector);
  729. result.normalize();
  730. };
  731. Vector3.Project = function (vector, world, transform, viewport) {
  732. var cw = viewport.width;
  733. var ch = viewport.height;
  734. var cx = viewport.x;
  735. var cy = viewport.y;
  736. 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);
  737. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  738. return Vector3.TransformCoordinates(vector, finalMatrix);
  739. };
  740. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  741. var matrix = world.multiply(transform);
  742. matrix.invert();
  743. source.x = source.x / viewportWidth * 2 - 1;
  744. source.y = -(source.y / viewportHeight * 2 - 1);
  745. var vector = Vector3.TransformCoordinates(source, matrix);
  746. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  747. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  748. vector = vector.scale(1.0 / num);
  749. }
  750. return vector;
  751. };
  752. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  753. var matrix = world.multiply(view).multiply(projection);
  754. matrix.invert();
  755. source.x = source.x / viewportWidth * 2 - 1;
  756. source.y = -(source.y / viewportHeight * 2 - 1);
  757. var vector = Vector3.TransformCoordinates(source, matrix);
  758. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  759. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  760. vector = vector.scale(1.0 / num);
  761. }
  762. return vector;
  763. };
  764. Vector3.Minimize = function (left, right) {
  765. var min = left.clone();
  766. min.MinimizeInPlace(right);
  767. return min;
  768. };
  769. Vector3.Maximize = function (left, right) {
  770. var max = left.clone();
  771. max.MaximizeInPlace(right);
  772. return max;
  773. };
  774. Vector3.Distance = function (value1, value2) {
  775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  776. };
  777. Vector3.DistanceSquared = function (value1, value2) {
  778. var x = value1.x - value2.x;
  779. var y = value1.y - value2.y;
  780. var z = value1.z - value2.z;
  781. return (x * x) + (y * y) + (z * z);
  782. };
  783. Vector3.Center = function (value1, value2) {
  784. var center = value1.add(value2);
  785. center.scaleInPlace(0.5);
  786. return center;
  787. };
  788. /**
  789. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  790. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  791. * to something in order to rotate it from its local system to the given target system.
  792. */
  793. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  794. var u = Vector3.Normalize(axis1);
  795. var v = Vector3.Normalize(axis2);
  796. var w = Vector3.Normalize(axis3);
  797. // world axis
  798. var X = Axis.X;
  799. var Y = Axis.Y;
  800. var Z = Axis.Z;
  801. // equation unknowns and vars
  802. var yaw = 0.0;
  803. var pitch = 0.0;
  804. var roll = 0.0;
  805. var x = 0.0;
  806. var y = 0.0;
  807. var z = 0.0;
  808. var t = 0.0;
  809. var sign = -1.0;
  810. var pi = Math.PI;
  811. var nbRevert = 0;
  812. var cross;
  813. var dot = 0.0;
  814. // step 1 : rotation around w
  815. // Rv3(u) = u1, and u1 belongs to plane xOz
  816. // Rv3(w) = w1 = w invariant
  817. var u1;
  818. var v1;
  819. if (w.z == 0) {
  820. z = 1.0;
  821. }
  822. else if (w.x == 0) {
  823. x = 1.0;
  824. }
  825. else {
  826. t = w.z / w.x;
  827. x = -t * Math.sqrt(1 / (1 + t * t));
  828. z = Math.sqrt(1 / (1 + t * t));
  829. }
  830. u1 = new Vector3(x, y, z);
  831. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  832. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  833. if (Vector3.Dot(w, cross) < 0) {
  834. sign = 1;
  835. }
  836. dot = Vector3.Dot(u, u1);
  837. roll = Math.acos(dot) * sign;
  838. if (Vector3.Dot(u1, X) < 0) {
  839. roll = Math.PI + roll;
  840. u1 = u1.scaleInPlace(-1);
  841. v1 = v1.scaleInPlace(-1);
  842. nbRevert++;
  843. }
  844. // step 2 : rotate around u1
  845. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  846. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  847. var w2;
  848. var v2;
  849. x = 0.0;
  850. y = 0.0;
  851. z = 0.0;
  852. sign = -1;
  853. if (w.z == 0) {
  854. x = 1.0;
  855. }
  856. else {
  857. t = u1.z / u1.x;
  858. x = -t * Math.sqrt(1 / (1 + t * t));
  859. z = Math.sqrt(1 / (1 + t * t));
  860. }
  861. w2 = new BABYLON.Vector3(x, y, z);
  862. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  863. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  864. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  865. sign = 1;
  866. }
  867. dot = BABYLON.Vector3.Dot(w, w2);
  868. pitch = Math.acos(dot) * sign;
  869. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  870. pitch = Math.PI + pitch;
  871. v2 = v2.scaleInPlace(-1);
  872. w2 = w2.scaleInPlace(-1);
  873. nbRevert++;
  874. }
  875. // step 3 : rotate around v2
  876. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  877. sign = -1;
  878. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  879. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  880. sign = 1;
  881. }
  882. dot = BABYLON.Vector3.Dot(u1, X);
  883. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  884. if (dot < 0 && nbRevert < 2) {
  885. yaw = Math.PI + yaw;
  886. }
  887. return new BABYLON.Vector3(pitch, yaw, roll);
  888. };
  889. return Vector3;
  890. })();
  891. BABYLON.Vector3 = Vector3;
  892. //Vector4 class created for EulerAngle class conversion to Quaternion
  893. var Vector4 = (function () {
  894. function Vector4(x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. }
  900. Vector4.prototype.toString = function () {
  901. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  902. };
  903. // Operators
  904. Vector4.prototype.asArray = function () {
  905. var result = [];
  906. this.toArray(result, 0);
  907. return result;
  908. };
  909. Vector4.prototype.toArray = function (array, index) {
  910. if (index === undefined) {
  911. index = 0;
  912. }
  913. array[index] = this.x;
  914. array[index + 1] = this.y;
  915. array[index + 2] = this.z;
  916. array[index + 3] = this.w;
  917. return this;
  918. };
  919. Vector4.prototype.addInPlace = function (otherVector) {
  920. this.x += otherVector.x;
  921. this.y += otherVector.y;
  922. this.z += otherVector.z;
  923. this.w += otherVector.w;
  924. return this;
  925. };
  926. Vector4.prototype.add = function (otherVector) {
  927. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  928. };
  929. Vector4.prototype.addToRef = function (otherVector, result) {
  930. result.x = this.x + otherVector.x;
  931. result.y = this.y + otherVector.y;
  932. result.z = this.z + otherVector.z;
  933. result.w = this.w + otherVector.w;
  934. return this;
  935. };
  936. Vector4.prototype.subtractInPlace = function (otherVector) {
  937. this.x -= otherVector.x;
  938. this.y -= otherVector.y;
  939. this.z -= otherVector.z;
  940. this.w -= otherVector.w;
  941. return this;
  942. };
  943. Vector4.prototype.subtract = function (otherVector) {
  944. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  945. };
  946. Vector4.prototype.subtractToRef = function (otherVector, result) {
  947. result.x = this.x - otherVector.x;
  948. result.y = this.y - otherVector.y;
  949. result.z = this.z - otherVector.z;
  950. result.w = this.w - otherVector.w;
  951. return this;
  952. };
  953. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  954. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  955. };
  956. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  957. result.x = this.x - x;
  958. result.y = this.y - y;
  959. result.z = this.z - z;
  960. result.w = this.w - w;
  961. return this;
  962. };
  963. Vector4.prototype.negate = function () {
  964. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  965. };
  966. Vector4.prototype.scaleInPlace = function (scale) {
  967. this.x *= scale;
  968. this.y *= scale;
  969. this.z *= scale;
  970. this.w *= scale;
  971. return this;
  972. };
  973. Vector4.prototype.scale = function (scale) {
  974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  975. };
  976. Vector4.prototype.scaleToRef = function (scale, result) {
  977. result.x = this.x * scale;
  978. result.y = this.y * scale;
  979. result.z = this.z * scale;
  980. result.w = this.w * scale;
  981. };
  982. Vector4.prototype.equals = function (otherVector) {
  983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  984. };
  985. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  986. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  987. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  988. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  989. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  990. };
  991. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  992. return this.x === x && this.y === y && this.z === z && this.w === w;
  993. };
  994. Vector4.prototype.multiplyInPlace = function (otherVector) {
  995. this.x *= otherVector.x;
  996. this.y *= otherVector.y;
  997. this.z *= otherVector.z;
  998. this.w *= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.multiply = function (otherVector) {
  1002. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1003. };
  1004. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1005. result.x = this.x * otherVector.x;
  1006. result.y = this.y * otherVector.y;
  1007. result.z = this.z * otherVector.z;
  1008. result.w = this.w * otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1013. };
  1014. Vector4.prototype.divide = function (otherVector) {
  1015. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1016. };
  1017. Vector4.prototype.divideToRef = function (otherVector, result) {
  1018. result.x = this.x / otherVector.x;
  1019. result.y = this.y / otherVector.y;
  1020. result.z = this.z / otherVector.z;
  1021. result.w = this.w / otherVector.w;
  1022. return this;
  1023. };
  1024. Vector4.prototype.MinimizeInPlace = function (other) {
  1025. if (other.x < this.x)
  1026. this.x = other.x;
  1027. if (other.y < this.y)
  1028. this.y = other.y;
  1029. if (other.z < this.z)
  1030. this.z = other.z;
  1031. if (other.w < this.w)
  1032. this.w = other.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.MaximizeInPlace = function (other) {
  1036. if (other.x > this.x)
  1037. this.x = other.x;
  1038. if (other.y > this.y)
  1039. this.y = other.y;
  1040. if (other.z > this.z)
  1041. this.z = other.z;
  1042. if (other.w > this.w)
  1043. this.w = other.w;
  1044. return this;
  1045. };
  1046. // Properties
  1047. Vector4.prototype.length = function () {
  1048. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1049. };
  1050. Vector4.prototype.lengthSquared = function () {
  1051. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1052. };
  1053. // Methods
  1054. Vector4.prototype.normalize = function () {
  1055. var len = this.length();
  1056. if (len === 0)
  1057. return this;
  1058. var num = 1.0 / len;
  1059. this.x *= num;
  1060. this.y *= num;
  1061. this.z *= num;
  1062. this.w *= num;
  1063. return this;
  1064. };
  1065. Vector4.prototype.clone = function () {
  1066. return new Vector4(this.x, this.y, this.z, this.w);
  1067. };
  1068. Vector4.prototype.copyFrom = function (source) {
  1069. this.x = source.x;
  1070. this.y = source.y;
  1071. this.z = source.z;
  1072. this.w = source.w;
  1073. return this;
  1074. };
  1075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1076. this.x = x;
  1077. this.y = y;
  1078. this.z = z;
  1079. this.w = w;
  1080. return this;
  1081. };
  1082. // Statics
  1083. Vector4.FromArray = function (array, offset) {
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1088. };
  1089. Vector4.FromArrayToRef = function (array, offset, result) {
  1090. result.x = array[offset];
  1091. result.y = array[offset + 1];
  1092. result.z = array[offset + 2];
  1093. result.w = array[offset + 3];
  1094. };
  1095. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1096. result.x = array[offset];
  1097. result.y = array[offset + 1];
  1098. result.z = array[offset + 2];
  1099. result.w = array[offset + 3];
  1100. };
  1101. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1102. result.x = x;
  1103. result.y = y;
  1104. result.z = z;
  1105. result.w = w;
  1106. };
  1107. Vector4.Zero = function () {
  1108. return new Vector4(0, 0, 0, 0);
  1109. };
  1110. Vector4.Normalize = function (vector) {
  1111. var result = Vector4.Zero();
  1112. Vector4.NormalizeToRef(vector, result);
  1113. return result;
  1114. };
  1115. Vector4.NormalizeToRef = function (vector, result) {
  1116. result.copyFrom(vector);
  1117. result.normalize();
  1118. };
  1119. Vector4.Minimize = function (left, right) {
  1120. var min = left.clone();
  1121. min.MinimizeInPlace(right);
  1122. return min;
  1123. };
  1124. Vector4.Maximize = function (left, right) {
  1125. var max = left.clone();
  1126. max.MaximizeInPlace(right);
  1127. return max;
  1128. };
  1129. Vector4.Distance = function (value1, value2) {
  1130. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1131. };
  1132. Vector4.DistanceSquared = function (value1, value2) {
  1133. var x = value1.x - value2.x;
  1134. var y = value1.y - value2.y;
  1135. var z = value1.z - value2.z;
  1136. var w = value1.w - value2.w;
  1137. return (x * x) + (y * y) + (z * z) + (w * w);
  1138. };
  1139. Vector4.Center = function (value1, value2) {
  1140. var center = value1.add(value2);
  1141. center.scaleInPlace(0.5);
  1142. return center;
  1143. };
  1144. return Vector4;
  1145. })();
  1146. BABYLON.Vector4 = Vector4;
  1147. var Quaternion = (function () {
  1148. function Quaternion(x, y, z, w) {
  1149. if (x === void 0) { x = 0; }
  1150. if (y === void 0) { y = 0; }
  1151. if (z === void 0) { z = 0; }
  1152. if (w === void 0) { w = 1; }
  1153. this.x = x;
  1154. this.y = y;
  1155. this.z = z;
  1156. this.w = w;
  1157. }
  1158. Quaternion.prototype.toString = function () {
  1159. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1160. };
  1161. Quaternion.prototype.asArray = function () {
  1162. return [this.x, this.y, this.z, this.w];
  1163. };
  1164. Quaternion.prototype.equals = function (otherQuaternion) {
  1165. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1166. };
  1167. Quaternion.prototype.clone = function () {
  1168. return new Quaternion(this.x, this.y, this.z, this.w);
  1169. };
  1170. Quaternion.prototype.copyFrom = function (other) {
  1171. this.x = other.x;
  1172. this.y = other.y;
  1173. this.z = other.z;
  1174. this.w = other.w;
  1175. return this;
  1176. };
  1177. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1178. this.x = x;
  1179. this.y = y;
  1180. this.z = z;
  1181. this.w = w;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.add = function (other) {
  1185. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1186. };
  1187. Quaternion.prototype.subtract = function (other) {
  1188. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1189. };
  1190. Quaternion.prototype.scale = function (value) {
  1191. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1192. };
  1193. Quaternion.prototype.multiply = function (q1) {
  1194. var result = new Quaternion(0, 0, 0, 1.0);
  1195. this.multiplyToRef(q1, result);
  1196. return result;
  1197. };
  1198. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1199. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1200. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1201. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1202. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1203. return this;
  1204. };
  1205. Quaternion.prototype.length = function () {
  1206. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1207. };
  1208. Quaternion.prototype.normalize = function () {
  1209. var length = 1.0 / this.length();
  1210. this.x *= length;
  1211. this.y *= length;
  1212. this.z *= length;
  1213. this.w *= length;
  1214. return this;
  1215. };
  1216. Quaternion.prototype.toEulerAngles = function () {
  1217. var result = Vector3.Zero();
  1218. this.toEulerAnglesToRef(result);
  1219. return result;
  1220. };
  1221. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1222. //result is an EulerAngles in the in the z-x-z convention
  1223. var qx = this.x;
  1224. var qy = this.y;
  1225. var qz = this.z;
  1226. var qw = this.w;
  1227. var qxy = qx * qy;
  1228. var qxz = qx * qz;
  1229. var qwy = qw * qy;
  1230. var qwz = qw * qz;
  1231. var qwx = qw * qx;
  1232. var qyz = qy * qz;
  1233. var sqx = qx * qx;
  1234. var sqy = qy * qy;
  1235. var determinant = sqx + sqy;
  1236. if (determinant !== 0.000 && determinant !== 1.000) {
  1237. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1238. result.y = Math.acos(1 - 2 * determinant);
  1239. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1240. }
  1241. else {
  1242. if (determinant === 0.0) {
  1243. result.x = 0.0;
  1244. result.y = 0.0;
  1245. 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)
  1246. }
  1247. else {
  1248. 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)
  1249. result.y = Math.PI;
  1250. result.z = 0.0;
  1251. }
  1252. }
  1253. return this;
  1254. };
  1255. Quaternion.prototype.toRotationMatrix = function (result) {
  1256. var xx = this.x * this.x;
  1257. var yy = this.y * this.y;
  1258. var zz = this.z * this.z;
  1259. var xy = this.x * this.y;
  1260. var zw = this.z * this.w;
  1261. var zx = this.z * this.x;
  1262. var yw = this.y * this.w;
  1263. var yz = this.y * this.z;
  1264. var xw = this.x * this.w;
  1265. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1266. result.m[1] = 2.0 * (xy + zw);
  1267. result.m[2] = 2.0 * (zx - yw);
  1268. result.m[3] = 0;
  1269. result.m[4] = 2.0 * (xy - zw);
  1270. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1271. result.m[6] = 2.0 * (yz + xw);
  1272. result.m[7] = 0;
  1273. result.m[8] = 2.0 * (zx + yw);
  1274. result.m[9] = 2.0 * (yz - xw);
  1275. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1276. result.m[11] = 0;
  1277. result.m[12] = 0;
  1278. result.m[13] = 0;
  1279. result.m[14] = 0;
  1280. result.m[15] = 1.0;
  1281. return this;
  1282. };
  1283. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1284. Quaternion.FromRotationMatrixToRef(matrix, this);
  1285. return this;
  1286. };
  1287. // Statics
  1288. Quaternion.FromRotationMatrix = function (matrix) {
  1289. var result = new Quaternion();
  1290. Quaternion.FromRotationMatrixToRef(matrix, result);
  1291. return result;
  1292. };
  1293. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1294. var data = matrix.m;
  1295. var m11 = data[0], m12 = data[4], m13 = data[8];
  1296. var m21 = data[1], m22 = data[5], m23 = data[9];
  1297. var m31 = data[2], m32 = data[6], m33 = data[10];
  1298. var trace = m11 + m22 + m33;
  1299. var s;
  1300. if (trace > 0) {
  1301. s = 0.5 / Math.sqrt(trace + 1.0);
  1302. result.w = 0.25 / s;
  1303. result.x = (m32 - m23) * s;
  1304. result.y = (m13 - m31) * s;
  1305. result.z = (m21 - m12) * s;
  1306. }
  1307. else if (m11 > m22 && m11 > m33) {
  1308. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1309. result.w = (m32 - m23) / s;
  1310. result.x = 0.25 * s;
  1311. result.y = (m12 + m21) / s;
  1312. result.z = (m13 + m31) / s;
  1313. }
  1314. else if (m22 > m33) {
  1315. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1316. result.w = (m13 - m31) / s;
  1317. result.x = (m12 + m21) / s;
  1318. result.y = 0.25 * s;
  1319. result.z = (m23 + m32) / s;
  1320. }
  1321. else {
  1322. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1323. result.w = (m21 - m12) / s;
  1324. result.x = (m13 + m31) / s;
  1325. result.y = (m23 + m32) / s;
  1326. result.z = 0.25 * s;
  1327. }
  1328. };
  1329. Quaternion.Inverse = function (q) {
  1330. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1331. };
  1332. Quaternion.Identity = function () {
  1333. return new Quaternion(0, 0, 0, 1);
  1334. };
  1335. Quaternion.RotationAxis = function (axis, angle) {
  1336. var result = new Quaternion();
  1337. var sin = Math.sin(angle / 2);
  1338. result.w = Math.cos(angle / 2);
  1339. result.x = axis.x * sin;
  1340. result.y = axis.y * sin;
  1341. result.z = axis.z * sin;
  1342. return result;
  1343. };
  1344. Quaternion.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1349. };
  1350. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1351. var result = new Quaternion();
  1352. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1353. return result;
  1354. };
  1355. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1356. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1357. var halfRoll = roll * 0.5;
  1358. var halfPitch = pitch * 0.5;
  1359. var halfYaw = yaw * 0.5;
  1360. var sinRoll = Math.sin(halfRoll);
  1361. var cosRoll = Math.cos(halfRoll);
  1362. var sinPitch = Math.sin(halfPitch);
  1363. var cosPitch = Math.cos(halfPitch);
  1364. var sinYaw = Math.sin(halfYaw);
  1365. var cosYaw = Math.cos(halfYaw);
  1366. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1367. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1368. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1369. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1370. };
  1371. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1372. var result = new Quaternion();
  1373. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1374. return result;
  1375. };
  1376. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1377. // Produces a quaternion from Euler angles in the z-x-z orientation
  1378. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1379. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1380. var halfBeta = beta * 0.5;
  1381. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1382. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1383. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1384. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1385. };
  1386. Quaternion.Slerp = function (left, right, amount) {
  1387. var num2;
  1388. var num3;
  1389. var num = amount;
  1390. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1391. var flag = false;
  1392. if (num4 < 0) {
  1393. flag = true;
  1394. num4 = -num4;
  1395. }
  1396. if (num4 > 0.999999) {
  1397. num3 = 1 - num;
  1398. num2 = flag ? -num : num;
  1399. }
  1400. else {
  1401. var num5 = Math.acos(num4);
  1402. var num6 = (1.0 / Math.sin(num5));
  1403. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1404. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1405. }
  1406. 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));
  1407. };
  1408. return Quaternion;
  1409. })();
  1410. BABYLON.Quaternion = Quaternion;
  1411. var Matrix = (function () {
  1412. function Matrix() {
  1413. this.m = new Float32Array(16);
  1414. }
  1415. // Properties
  1416. Matrix.prototype.isIdentity = function () {
  1417. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1418. return false;
  1419. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1420. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1421. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1422. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1423. return false;
  1424. return true;
  1425. };
  1426. Matrix.prototype.determinant = function () {
  1427. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1428. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1429. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1430. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1431. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1432. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1433. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1434. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1435. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1436. };
  1437. // Methods
  1438. Matrix.prototype.toArray = function () {
  1439. return this.m;
  1440. };
  1441. Matrix.prototype.asArray = function () {
  1442. return this.toArray();
  1443. };
  1444. Matrix.prototype.invert = function () {
  1445. this.invertToRef(this);
  1446. return this;
  1447. };
  1448. Matrix.prototype.invertToRef = function (other) {
  1449. var l1 = this.m[0];
  1450. var l2 = this.m[1];
  1451. var l3 = this.m[2];
  1452. var l4 = this.m[3];
  1453. var l5 = this.m[4];
  1454. var l6 = this.m[5];
  1455. var l7 = this.m[6];
  1456. var l8 = this.m[7];
  1457. var l9 = this.m[8];
  1458. var l10 = this.m[9];
  1459. var l11 = this.m[10];
  1460. var l12 = this.m[11];
  1461. var l13 = this.m[12];
  1462. var l14 = this.m[13];
  1463. var l15 = this.m[14];
  1464. var l16 = this.m[15];
  1465. var l17 = (l11 * l16) - (l12 * l15);
  1466. var l18 = (l10 * l16) - (l12 * l14);
  1467. var l19 = (l10 * l15) - (l11 * l14);
  1468. var l20 = (l9 * l16) - (l12 * l13);
  1469. var l21 = (l9 * l15) - (l11 * l13);
  1470. var l22 = (l9 * l14) - (l10 * l13);
  1471. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1472. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1473. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1474. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1475. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1476. var l28 = (l7 * l16) - (l8 * l15);
  1477. var l29 = (l6 * l16) - (l8 * l14);
  1478. var l30 = (l6 * l15) - (l7 * l14);
  1479. var l31 = (l5 * l16) - (l8 * l13);
  1480. var l32 = (l5 * l15) - (l7 * l13);
  1481. var l33 = (l5 * l14) - (l6 * l13);
  1482. var l34 = (l7 * l12) - (l8 * l11);
  1483. var l35 = (l6 * l12) - (l8 * l10);
  1484. var l36 = (l6 * l11) - (l7 * l10);
  1485. var l37 = (l5 * l12) - (l8 * l9);
  1486. var l38 = (l5 * l11) - (l7 * l9);
  1487. var l39 = (l5 * l10) - (l6 * l9);
  1488. other.m[0] = l23 * l27;
  1489. other.m[4] = l24 * l27;
  1490. other.m[8] = l25 * l27;
  1491. other.m[12] = l26 * l27;
  1492. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1493. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1494. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1495. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1496. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1497. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1498. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1499. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1500. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1501. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1502. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1503. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1504. return this;
  1505. };
  1506. Matrix.prototype.invertToRefSIMD = function (other) {
  1507. var src = this.m;
  1508. var dest = other.m;
  1509. var row0, row1, row2, row3;
  1510. var tmp1;
  1511. var minor0, minor1, minor2, minor3;
  1512. var det;
  1513. // Load the 4 rows
  1514. var src0 = SIMD.float32x4.load(src, 0);
  1515. var src1 = SIMD.float32x4.load(src, 4);
  1516. var src2 = SIMD.float32x4.load(src, 8);
  1517. var src3 = SIMD.float32x4.load(src, 12);
  1518. // Transpose the source matrix. Sort of. Not a true transpose operation
  1519. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1520. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1521. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1522. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1523. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1524. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1525. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1526. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1527. // This is a true transposition, but it will lead to an incorrect result
  1528. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1529. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1530. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1531. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1532. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1533. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1534. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1535. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1536. // ----
  1537. tmp1 = SIMD.float32x4.mul(row2, row3);
  1538. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1539. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1540. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1541. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1542. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1543. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1544. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1545. // ----
  1546. tmp1 = SIMD.float32x4.mul(row1, row2);
  1547. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1548. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1549. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1550. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1551. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1552. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1553. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1554. // ----
  1555. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1556. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1557. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1558. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1559. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1560. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1561. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1562. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1563. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1564. // ----
  1565. tmp1 = SIMD.float32x4.mul(row0, row1);
  1566. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1567. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1568. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1569. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1570. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1571. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1572. // ----
  1573. tmp1 = SIMD.float32x4.mul(row0, row3);
  1574. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1575. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1576. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1577. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1578. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1579. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1580. // ----
  1581. tmp1 = SIMD.float32x4.mul(row0, row2);
  1582. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1583. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1584. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1585. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1586. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1587. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1588. // Compute determinant
  1589. det = SIMD.float32x4.mul(row0, minor0);
  1590. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1591. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1592. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1593. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1594. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1595. // These shuffles aren't necessary if the faulty transposition is done
  1596. // up at the top of this function.
  1597. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1598. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1599. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1600. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1601. // Compute final values by multiplying with 1/det
  1602. minor0 = SIMD.float32x4.mul(det, minor0);
  1603. minor1 = SIMD.float32x4.mul(det, minor1);
  1604. minor2 = SIMD.float32x4.mul(det, minor2);
  1605. minor3 = SIMD.float32x4.mul(det, minor3);
  1606. SIMD.float32x4.store(dest, 0, minor0);
  1607. SIMD.float32x4.store(dest, 4, minor1);
  1608. SIMD.float32x4.store(dest, 8, minor2);
  1609. SIMD.float32x4.store(dest, 12, minor3);
  1610. return this;
  1611. };
  1612. Matrix.prototype.setTranslation = function (vector3) {
  1613. this.m[12] = vector3.x;
  1614. this.m[13] = vector3.y;
  1615. this.m[14] = vector3.z;
  1616. return this;
  1617. };
  1618. Matrix.prototype.multiply = function (other) {
  1619. var result = new Matrix();
  1620. this.multiplyToRef(other, result);
  1621. return result;
  1622. };
  1623. Matrix.prototype.copyFrom = function (other) {
  1624. for (var index = 0; index < 16; index++) {
  1625. this.m[index] = other.m[index];
  1626. }
  1627. return this;
  1628. };
  1629. Matrix.prototype.copyToArray = function (array, offset) {
  1630. if (offset === void 0) { offset = 0; }
  1631. for (var index = 0; index < 16; index++) {
  1632. array[offset + index] = this.m[index];
  1633. }
  1634. return this;
  1635. };
  1636. Matrix.prototype.multiplyToRef = function (other, result) {
  1637. this.multiplyToArray(other, result.m, 0);
  1638. return this;
  1639. };
  1640. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1641. var tm0 = this.m[0];
  1642. var tm1 = this.m[1];
  1643. var tm2 = this.m[2];
  1644. var tm3 = this.m[3];
  1645. var tm4 = this.m[4];
  1646. var tm5 = this.m[5];
  1647. var tm6 = this.m[6];
  1648. var tm7 = this.m[7];
  1649. var tm8 = this.m[8];
  1650. var tm9 = this.m[9];
  1651. var tm10 = this.m[10];
  1652. var tm11 = this.m[11];
  1653. var tm12 = this.m[12];
  1654. var tm13 = this.m[13];
  1655. var tm14 = this.m[14];
  1656. var tm15 = this.m[15];
  1657. var om0 = other.m[0];
  1658. var om1 = other.m[1];
  1659. var om2 = other.m[2];
  1660. var om3 = other.m[3];
  1661. var om4 = other.m[4];
  1662. var om5 = other.m[5];
  1663. var om6 = other.m[6];
  1664. var om7 = other.m[7];
  1665. var om8 = other.m[8];
  1666. var om9 = other.m[9];
  1667. var om10 = other.m[10];
  1668. var om11 = other.m[11];
  1669. var om12 = other.m[12];
  1670. var om13 = other.m[13];
  1671. var om14 = other.m[14];
  1672. var om15 = other.m[15];
  1673. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1674. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1675. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1676. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1677. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1678. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1679. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1680. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1681. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1682. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1683. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1684. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1685. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1686. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1687. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1688. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1689. return this;
  1690. };
  1691. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1692. if (offset === void 0) { offset = 0; }
  1693. var tm = this.m;
  1694. var om = other.m;
  1695. var om0 = SIMD.float32x4.load(om, 0);
  1696. var om1 = SIMD.float32x4.load(om, 4);
  1697. var om2 = SIMD.float32x4.load(om, 8);
  1698. var om3 = SIMD.float32x4.load(om, 12);
  1699. var tm0 = SIMD.float32x4.load(tm, 0);
  1700. 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)))));
  1701. var tm1 = SIMD.float32x4.load(tm, 4);
  1702. 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)))));
  1703. var tm2 = SIMD.float32x4.load(tm, 8);
  1704. 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)))));
  1705. var tm3 = SIMD.float32x4.load(tm, 12);
  1706. 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)))));
  1707. };
  1708. Matrix.prototype.equals = function (value) {
  1709. return value &&
  1710. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1711. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1712. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1713. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1714. };
  1715. Matrix.prototype.clone = function () {
  1716. 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]);
  1717. };
  1718. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1719. translation.x = this.m[12];
  1720. translation.y = this.m[13];
  1721. translation.z = this.m[14];
  1722. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1723. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1724. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1725. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1726. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1727. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1728. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1729. rotation.x = 0;
  1730. rotation.y = 0;
  1731. rotation.z = 0;
  1732. rotation.w = 1;
  1733. return false;
  1734. }
  1735. 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);
  1736. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1737. return true;
  1738. };
  1739. // Statics
  1740. Matrix.FromArray = function (array, offset) {
  1741. var result = new Matrix();
  1742. if (!offset) {
  1743. offset = 0;
  1744. }
  1745. Matrix.FromArrayToRef(array, offset, result);
  1746. return result;
  1747. };
  1748. Matrix.FromArrayToRef = function (array, offset, result) {
  1749. for (var index = 0; index < 16; index++) {
  1750. result.m[index] = array[index + offset];
  1751. }
  1752. };
  1753. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1754. result.m[0] = initialM11;
  1755. result.m[1] = initialM12;
  1756. result.m[2] = initialM13;
  1757. result.m[3] = initialM14;
  1758. result.m[4] = initialM21;
  1759. result.m[5] = initialM22;
  1760. result.m[6] = initialM23;
  1761. result.m[7] = initialM24;
  1762. result.m[8] = initialM31;
  1763. result.m[9] = initialM32;
  1764. result.m[10] = initialM33;
  1765. result.m[11] = initialM34;
  1766. result.m[12] = initialM41;
  1767. result.m[13] = initialM42;
  1768. result.m[14] = initialM43;
  1769. result.m[15] = initialM44;
  1770. };
  1771. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1772. var result = new Matrix();
  1773. result.m[0] = initialM11;
  1774. result.m[1] = initialM12;
  1775. result.m[2] = initialM13;
  1776. result.m[3] = initialM14;
  1777. result.m[4] = initialM21;
  1778. result.m[5] = initialM22;
  1779. result.m[6] = initialM23;
  1780. result.m[7] = initialM24;
  1781. result.m[8] = initialM31;
  1782. result.m[9] = initialM32;
  1783. result.m[10] = initialM33;
  1784. result.m[11] = initialM34;
  1785. result.m[12] = initialM41;
  1786. result.m[13] = initialM42;
  1787. result.m[14] = initialM43;
  1788. result.m[15] = initialM44;
  1789. return result;
  1790. };
  1791. Matrix.Compose = function (scale, rotation, translation) {
  1792. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1793. var rotationMatrix = Matrix.Identity();
  1794. rotation.toRotationMatrix(rotationMatrix);
  1795. result = result.multiply(rotationMatrix);
  1796. result.setTranslation(translation);
  1797. return result;
  1798. };
  1799. Matrix.Identity = function () {
  1800. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1801. };
  1802. Matrix.IdentityToRef = function (result) {
  1803. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1804. };
  1805. Matrix.Zero = function () {
  1806. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1807. };
  1808. Matrix.RotationX = function (angle) {
  1809. var result = new Matrix();
  1810. Matrix.RotationXToRef(angle, result);
  1811. return result;
  1812. };
  1813. Matrix.Invert = function (source) {
  1814. var result = new Matrix();
  1815. source.invertToRef(result);
  1816. return result;
  1817. };
  1818. Matrix.RotationXToRef = function (angle, result) {
  1819. var s = Math.sin(angle);
  1820. var c = Math.cos(angle);
  1821. result.m[0] = 1.0;
  1822. result.m[15] = 1.0;
  1823. result.m[5] = c;
  1824. result.m[10] = c;
  1825. result.m[9] = -s;
  1826. result.m[6] = s;
  1827. result.m[1] = 0;
  1828. result.m[2] = 0;
  1829. result.m[3] = 0;
  1830. result.m[4] = 0;
  1831. result.m[7] = 0;
  1832. result.m[8] = 0;
  1833. result.m[11] = 0;
  1834. result.m[12] = 0;
  1835. result.m[13] = 0;
  1836. result.m[14] = 0;
  1837. };
  1838. Matrix.RotationY = function (angle) {
  1839. var result = new Matrix();
  1840. Matrix.RotationYToRef(angle, result);
  1841. return result;
  1842. };
  1843. Matrix.RotationYToRef = function (angle, result) {
  1844. var s = Math.sin(angle);
  1845. var c = Math.cos(angle);
  1846. result.m[5] = 1.0;
  1847. result.m[15] = 1.0;
  1848. result.m[0] = c;
  1849. result.m[2] = -s;
  1850. result.m[8] = s;
  1851. result.m[10] = c;
  1852. result.m[1] = 0;
  1853. result.m[3] = 0;
  1854. result.m[4] = 0;
  1855. result.m[6] = 0;
  1856. result.m[7] = 0;
  1857. result.m[9] = 0;
  1858. result.m[11] = 0;
  1859. result.m[12] = 0;
  1860. result.m[13] = 0;
  1861. result.m[14] = 0;
  1862. };
  1863. Matrix.RotationZ = function (angle) {
  1864. var result = new Matrix();
  1865. Matrix.RotationZToRef(angle, result);
  1866. return result;
  1867. };
  1868. Matrix.RotationZToRef = function (angle, result) {
  1869. var s = Math.sin(angle);
  1870. var c = Math.cos(angle);
  1871. result.m[10] = 1.0;
  1872. result.m[15] = 1.0;
  1873. result.m[0] = c;
  1874. result.m[1] = s;
  1875. result.m[4] = -s;
  1876. result.m[5] = c;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[6] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[9] = 0;
  1883. result.m[11] = 0;
  1884. result.m[12] = 0;
  1885. result.m[13] = 0;
  1886. result.m[14] = 0;
  1887. };
  1888. Matrix.RotationAxis = function (axis, angle) {
  1889. var s = Math.sin(-angle);
  1890. var c = Math.cos(-angle);
  1891. var c1 = 1 - c;
  1892. axis.normalize();
  1893. var result = Matrix.Zero();
  1894. result.m[0] = (axis.x * axis.x) * c1 + c;
  1895. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1896. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1897. result.m[3] = 0.0;
  1898. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1899. result.m[5] = (axis.y * axis.y) * c1 + c;
  1900. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1901. result.m[7] = 0.0;
  1902. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1903. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1904. result.m[10] = (axis.z * axis.z) * c1 + c;
  1905. result.m[11] = 0.0;
  1906. result.m[15] = 1.0;
  1907. return result;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.LookAtLH = function (eye, target, up) {
  1950. var result = Matrix.Zero();
  1951. Matrix.LookAtLHToRef(eye, target, up, result);
  1952. return result;
  1953. };
  1954. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1955. // Z axis
  1956. target.subtractToRef(eye, this._zAxis);
  1957. this._zAxis.normalize();
  1958. // X axis
  1959. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1960. this._xAxis.normalize();
  1961. // Y axis
  1962. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1963. this._yAxis.normalize();
  1964. // Eye angles
  1965. var ex = -Vector3.Dot(this._xAxis, eye);
  1966. var ey = -Vector3.Dot(this._yAxis, eye);
  1967. var ez = -Vector3.Dot(this._zAxis, eye);
  1968. 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);
  1969. };
  1970. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1971. var out = result.m;
  1972. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1973. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1974. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1975. // cc.kmVec3Subtract(f, pCenter, pEye);
  1976. var f = SIMD.float32x4.sub(center, eye);
  1977. // cc.kmVec3Normalize(f, f);
  1978. var tmp = SIMD.float32x4.mul(f, f);
  1979. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1980. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1981. // cc.kmVec3Assign(up, pUp);
  1982. // cc.kmVec3Normalize(up, up);
  1983. tmp = SIMD.float32x4.mul(up, up);
  1984. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1985. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1986. // cc.kmVec3Cross(s, f, up);
  1987. 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)));
  1988. // cc.kmVec3Normalize(s, s);
  1989. tmp = SIMD.float32x4.mul(s, s);
  1990. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1991. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1992. // cc.kmVec3Cross(u, s, f);
  1993. 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)));
  1994. // cc.kmVec3Normalize(s, s);
  1995. tmp = SIMD.float32x4.mul(s, s);
  1996. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1997. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1998. var zero = SIMD.float32x4.splat(0.0);
  1999. s = SIMD.float32x4.neg(s);
  2000. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2001. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2002. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2003. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2004. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2005. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2006. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2007. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2008. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2009. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2010. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2011. var b3 = SIMD.float32x4.neg(eye);
  2012. b3 = SIMD.float32x4.withW(b3, 1.0);
  2013. 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)))));
  2014. 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)))));
  2015. 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)))));
  2016. 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)))));
  2017. };
  2018. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2021. return matrix;
  2022. };
  2023. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2024. var hw = 2.0 / width;
  2025. var hh = 2.0 / height;
  2026. var id = 1.0 / (zfar - znear);
  2027. var nid = znear / (znear - zfar);
  2028. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2029. };
  2030. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2031. var matrix = Matrix.Zero();
  2032. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2033. return matrix;
  2034. };
  2035. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2036. result.m[0] = 2.0 / (right - left);
  2037. result.m[1] = result.m[2] = result.m[3] = 0;
  2038. result.m[5] = 2.0 / (top - bottom);
  2039. result.m[4] = result.m[6] = result.m[7] = 0;
  2040. result.m[10] = -1.0 / (znear - zfar);
  2041. result.m[8] = result.m[9] = result.m[11] = 0;
  2042. result.m[12] = (left + right) / (left - right);
  2043. result.m[13] = (top + bottom) / (bottom - top);
  2044. result.m[14] = znear / (znear - zfar);
  2045. result.m[15] = 1.0;
  2046. };
  2047. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2048. var matrix = Matrix.Zero();
  2049. matrix.m[0] = (2.0 * znear) / width;
  2050. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2051. matrix.m[5] = (2.0 * znear) / height;
  2052. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2053. matrix.m[10] = -zfar / (znear - zfar);
  2054. matrix.m[8] = matrix.m[9] = 0.0;
  2055. matrix.m[11] = 1.0;
  2056. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2057. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2058. return matrix;
  2059. };
  2060. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2061. var matrix = Matrix.Zero();
  2062. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2063. return matrix;
  2064. };
  2065. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2066. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2067. var tan = 1.0 / (Math.tan(fov * 0.5));
  2068. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2069. if (v_fixed) {
  2070. result.m[0] = tan / aspect;
  2071. }
  2072. else {
  2073. result.m[0] = tan;
  2074. }
  2075. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2076. if (v_fixed) {
  2077. result.m[5] = tan;
  2078. }
  2079. else {
  2080. result.m[5] = tan * aspect;
  2081. }
  2082. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2083. result.m[8] = result.m[9] = 0.0;
  2084. result.m[10] = -zfar / (znear - zfar);
  2085. result.m[11] = 1.0;
  2086. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2087. result.m[14] = (znear * zfar) / (znear - zfar);
  2088. };
  2089. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2090. var cw = viewport.width;
  2091. var ch = viewport.height;
  2092. var cx = viewport.x;
  2093. var cy = viewport.y;
  2094. 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);
  2095. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2096. };
  2097. Matrix.Transpose = function (matrix) {
  2098. var result = new Matrix();
  2099. result.m[0] = matrix.m[0];
  2100. result.m[1] = matrix.m[4];
  2101. result.m[2] = matrix.m[8];
  2102. result.m[3] = matrix.m[12];
  2103. result.m[4] = matrix.m[1];
  2104. result.m[5] = matrix.m[5];
  2105. result.m[6] = matrix.m[9];
  2106. result.m[7] = matrix.m[13];
  2107. result.m[8] = matrix.m[2];
  2108. result.m[9] = matrix.m[6];
  2109. result.m[10] = matrix.m[10];
  2110. result.m[11] = matrix.m[14];
  2111. result.m[12] = matrix.m[3];
  2112. result.m[13] = matrix.m[7];
  2113. result.m[14] = matrix.m[11];
  2114. result.m[15] = matrix.m[15];
  2115. return result;
  2116. };
  2117. Matrix.Reflection = function (plane) {
  2118. var matrix = new Matrix();
  2119. Matrix.ReflectionToRef(plane, matrix);
  2120. return matrix;
  2121. };
  2122. Matrix.ReflectionToRef = function (plane, result) {
  2123. plane.normalize();
  2124. var x = plane.normal.x;
  2125. var y = plane.normal.y;
  2126. var z = plane.normal.z;
  2127. var temp = -2 * x;
  2128. var temp2 = -2 * y;
  2129. var temp3 = -2 * z;
  2130. result.m[0] = (temp * x) + 1;
  2131. result.m[1] = temp2 * x;
  2132. result.m[2] = temp3 * x;
  2133. result.m[3] = 0.0;
  2134. result.m[4] = temp * y;
  2135. result.m[5] = (temp2 * y) + 1;
  2136. result.m[6] = temp3 * y;
  2137. result.m[7] = 0.0;
  2138. result.m[8] = temp * z;
  2139. result.m[9] = temp2 * z;
  2140. result.m[10] = (temp3 * z) + 1;
  2141. result.m[11] = 0.0;
  2142. result.m[12] = temp * plane.d;
  2143. result.m[13] = temp2 * plane.d;
  2144. result.m[14] = temp3 * plane.d;
  2145. result.m[15] = 1.0;
  2146. };
  2147. Matrix._tempQuaternion = new Quaternion();
  2148. Matrix._xAxis = Vector3.Zero();
  2149. Matrix._yAxis = Vector3.Zero();
  2150. Matrix._zAxis = Vector3.Zero();
  2151. return Matrix;
  2152. })();
  2153. BABYLON.Matrix = Matrix;
  2154. var Plane = (function () {
  2155. function Plane(a, b, c, d) {
  2156. this.normal = new Vector3(a, b, c);
  2157. this.d = d;
  2158. }
  2159. Plane.prototype.asArray = function () {
  2160. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2161. };
  2162. // Methods
  2163. Plane.prototype.clone = function () {
  2164. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2165. };
  2166. Plane.prototype.normalize = function () {
  2167. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2168. var magnitude = 0;
  2169. if (norm !== 0) {
  2170. magnitude = 1.0 / norm;
  2171. }
  2172. this.normal.x *= magnitude;
  2173. this.normal.y *= magnitude;
  2174. this.normal.z *= magnitude;
  2175. this.d *= magnitude;
  2176. return this;
  2177. };
  2178. Plane.prototype.transform = function (transformation) {
  2179. var transposedMatrix = Matrix.Transpose(transformation);
  2180. var x = this.normal.x;
  2181. var y = this.normal.y;
  2182. var z = this.normal.z;
  2183. var d = this.d;
  2184. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2185. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2186. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2187. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2188. return new Plane(normalX, normalY, normalZ, finalD);
  2189. };
  2190. Plane.prototype.dotCoordinate = function (point) {
  2191. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2192. };
  2193. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2194. var x1 = point2.x - point1.x;
  2195. var y1 = point2.y - point1.y;
  2196. var z1 = point2.z - point1.z;
  2197. var x2 = point3.x - point1.x;
  2198. var y2 = point3.y - point1.y;
  2199. var z2 = point3.z - point1.z;
  2200. var yz = (y1 * z2) - (z1 * y2);
  2201. var xz = (z1 * x2) - (x1 * z2);
  2202. var xy = (x1 * y2) - (y1 * x2);
  2203. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2204. var invPyth;
  2205. if (pyth !== 0) {
  2206. invPyth = 1.0 / pyth;
  2207. }
  2208. else {
  2209. invPyth = 0;
  2210. }
  2211. this.normal.x = yz * invPyth;
  2212. this.normal.y = xz * invPyth;
  2213. this.normal.z = xy * invPyth;
  2214. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2215. return this;
  2216. };
  2217. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2218. var dot = Vector3.Dot(this.normal, direction);
  2219. return (dot <= epsilon);
  2220. };
  2221. Plane.prototype.signedDistanceTo = function (point) {
  2222. return Vector3.Dot(point, this.normal) + this.d;
  2223. };
  2224. // Statics
  2225. Plane.FromArray = function (array) {
  2226. return new Plane(array[0], array[1], array[2], array[3]);
  2227. };
  2228. Plane.FromPoints = function (point1, point2, point3) {
  2229. var result = new Plane(0, 0, 0, 0);
  2230. result.copyFromPoints(point1, point2, point3);
  2231. return result;
  2232. };
  2233. Plane.FromPositionAndNormal = function (origin, normal) {
  2234. var result = new Plane(0, 0, 0, 0);
  2235. normal.normalize();
  2236. result.normal = normal;
  2237. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2238. return result;
  2239. };
  2240. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2241. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2242. return Vector3.Dot(point, normal) + d;
  2243. };
  2244. return Plane;
  2245. })();
  2246. BABYLON.Plane = Plane;
  2247. var Viewport = (function () {
  2248. function Viewport(x, y, width, height) {
  2249. this.x = x;
  2250. this.y = y;
  2251. this.width = width;
  2252. this.height = height;
  2253. }
  2254. Viewport.prototype.toGlobal = function (engine) {
  2255. var width = engine.getRenderWidth();
  2256. var height = engine.getRenderHeight();
  2257. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2258. };
  2259. return Viewport;
  2260. })();
  2261. BABYLON.Viewport = Viewport;
  2262. var Frustum = (function () {
  2263. function Frustum() {
  2264. }
  2265. Frustum.GetPlanes = function (transform) {
  2266. var frustumPlanes = [];
  2267. for (var index = 0; index < 6; index++) {
  2268. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2269. }
  2270. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2271. return frustumPlanes;
  2272. };
  2273. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2274. // Near
  2275. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2276. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2277. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2278. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2279. frustumPlanes[0].normalize();
  2280. // Far
  2281. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2282. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2283. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2284. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2285. frustumPlanes[1].normalize();
  2286. // Left
  2287. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2288. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2289. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2290. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2291. frustumPlanes[2].normalize();
  2292. // Right
  2293. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2294. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2295. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2296. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2297. frustumPlanes[3].normalize();
  2298. // Top
  2299. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2300. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2301. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2302. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2303. frustumPlanes[4].normalize();
  2304. // Bottom
  2305. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2306. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2307. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2308. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2309. frustumPlanes[5].normalize();
  2310. };
  2311. return Frustum;
  2312. })();
  2313. BABYLON.Frustum = Frustum;
  2314. var Ray = (function () {
  2315. function Ray(origin, direction, length) {
  2316. if (length === void 0) { length = Number.MAX_VALUE; }
  2317. this.origin = origin;
  2318. this.direction = direction;
  2319. this.length = length;
  2320. }
  2321. // Methods
  2322. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2323. var d = 0.0;
  2324. var maxValue = Number.MAX_VALUE;
  2325. if (Math.abs(this.direction.x) < 0.0000001) {
  2326. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2327. return false;
  2328. }
  2329. }
  2330. else {
  2331. var inv = 1.0 / this.direction.x;
  2332. var min = (minimum.x - this.origin.x) * inv;
  2333. var max = (maximum.x - this.origin.x) * inv;
  2334. if (max === -Infinity) {
  2335. max = Infinity;
  2336. }
  2337. if (min > max) {
  2338. var temp = min;
  2339. min = max;
  2340. max = temp;
  2341. }
  2342. d = Math.max(min, d);
  2343. maxValue = Math.min(max, maxValue);
  2344. if (d > maxValue) {
  2345. return false;
  2346. }
  2347. }
  2348. if (Math.abs(this.direction.y) < 0.0000001) {
  2349. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2350. return false;
  2351. }
  2352. }
  2353. else {
  2354. inv = 1.0 / this.direction.y;
  2355. min = (minimum.y - this.origin.y) * inv;
  2356. max = (maximum.y - this.origin.y) * inv;
  2357. if (max === -Infinity) {
  2358. max = Infinity;
  2359. }
  2360. if (min > max) {
  2361. temp = min;
  2362. min = max;
  2363. max = temp;
  2364. }
  2365. d = Math.max(min, d);
  2366. maxValue = Math.min(max, maxValue);
  2367. if (d > maxValue) {
  2368. return false;
  2369. }
  2370. }
  2371. if (Math.abs(this.direction.z) < 0.0000001) {
  2372. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2373. return false;
  2374. }
  2375. }
  2376. else {
  2377. inv = 1.0 / this.direction.z;
  2378. min = (minimum.z - this.origin.z) * inv;
  2379. max = (maximum.z - this.origin.z) * inv;
  2380. if (max === -Infinity) {
  2381. max = Infinity;
  2382. }
  2383. if (min > max) {
  2384. temp = min;
  2385. min = max;
  2386. max = temp;
  2387. }
  2388. d = Math.max(min, d);
  2389. maxValue = Math.min(max, maxValue);
  2390. if (d > maxValue) {
  2391. return false;
  2392. }
  2393. }
  2394. return true;
  2395. };
  2396. Ray.prototype.intersectsBox = function (box) {
  2397. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2398. };
  2399. Ray.prototype.intersectsSphere = function (sphere) {
  2400. var x = sphere.center.x - this.origin.x;
  2401. var y = sphere.center.y - this.origin.y;
  2402. var z = sphere.center.z - this.origin.z;
  2403. var pyth = (x * x) + (y * y) + (z * z);
  2404. var rr = sphere.radius * sphere.radius;
  2405. if (pyth <= rr) {
  2406. return true;
  2407. }
  2408. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2409. if (dot < 0.0) {
  2410. return false;
  2411. }
  2412. var temp = pyth - (dot * dot);
  2413. return temp <= rr;
  2414. };
  2415. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2416. if (!this._edge1) {
  2417. this._edge1 = Vector3.Zero();
  2418. this._edge2 = Vector3.Zero();
  2419. this._pvec = Vector3.Zero();
  2420. this._tvec = Vector3.Zero();
  2421. this._qvec = Vector3.Zero();
  2422. }
  2423. vertex1.subtractToRef(vertex0, this._edge1);
  2424. vertex2.subtractToRef(vertex0, this._edge2);
  2425. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2426. var det = Vector3.Dot(this._edge1, this._pvec);
  2427. if (det === 0) {
  2428. return null;
  2429. }
  2430. var invdet = 1 / det;
  2431. this.origin.subtractToRef(vertex0, this._tvec);
  2432. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2433. if (bu < 0 || bu > 1.0) {
  2434. return null;
  2435. }
  2436. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2437. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2438. if (bv < 0 || bu + bv > 1.0) {
  2439. return null;
  2440. }
  2441. //check if the distance is longer than the predefined length.
  2442. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2443. if (distance > this.length) {
  2444. return null;
  2445. }
  2446. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2447. };
  2448. // Statics
  2449. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2450. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2451. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2452. var direction = end.subtract(start);
  2453. direction.normalize();
  2454. return new Ray(start, direction);
  2455. };
  2456. /**
  2457. * 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
  2458. * transformed to the given world matrix.
  2459. * @param origin The origin point
  2460. * @param end The end point
  2461. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2462. */
  2463. Ray.CreateNewFromTo = function (origin, end, world) {
  2464. if (world === void 0) { world = Matrix.Identity(); }
  2465. var direction = end.subtract(origin);
  2466. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2467. direction.normalize();
  2468. return Ray.Transform(new Ray(origin, direction, length), world);
  2469. };
  2470. Ray.Transform = function (ray, matrix) {
  2471. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2472. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2473. return new Ray(newOrigin, newDirection, ray.length);
  2474. };
  2475. return Ray;
  2476. })();
  2477. BABYLON.Ray = Ray;
  2478. (function (Space) {
  2479. Space[Space["LOCAL"] = 0] = "LOCAL";
  2480. Space[Space["WORLD"] = 1] = "WORLD";
  2481. })(BABYLON.Space || (BABYLON.Space = {}));
  2482. var Space = BABYLON.Space;
  2483. var Axis = (function () {
  2484. function Axis() {
  2485. }
  2486. Axis.X = new Vector3(1, 0, 0);
  2487. Axis.Y = new Vector3(0, 1, 0);
  2488. Axis.Z = new Vector3(0, 0, 1);
  2489. return Axis;
  2490. })();
  2491. BABYLON.Axis = Axis;
  2492. ;
  2493. var BezierCurve = (function () {
  2494. function BezierCurve() {
  2495. }
  2496. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2497. // Extract X (which is equal to time here)
  2498. var f0 = 1 - 3 * x2 + 3 * x1;
  2499. var f1 = 3 * x2 - 6 * x1;
  2500. var f2 = 3 * x1;
  2501. var refinedT = t;
  2502. for (var i = 0; i < 5; i++) {
  2503. var refinedT2 = refinedT * refinedT;
  2504. var refinedT3 = refinedT2 * refinedT;
  2505. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2506. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2507. refinedT -= (x - t) * slope;
  2508. refinedT = Math.min(1, Math.max(0, refinedT));
  2509. }
  2510. // Resolve cubic bezier for the given x
  2511. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2512. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2513. Math.pow(refinedT, 3);
  2514. };
  2515. return BezierCurve;
  2516. })();
  2517. BABYLON.BezierCurve = BezierCurve;
  2518. (function (Orientation) {
  2519. Orientation[Orientation["CW"] = 0] = "CW";
  2520. Orientation[Orientation["CCW"] = 1] = "CCW";
  2521. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2522. var Orientation = BABYLON.Orientation;
  2523. var Angle = (function () {
  2524. function Angle(radians) {
  2525. var _this = this;
  2526. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2527. this.radians = function () { return _this._radians; };
  2528. this._radians = radians;
  2529. if (this._radians < 0)
  2530. this._radians += (2 * Math.PI);
  2531. }
  2532. Angle.BetweenTwoPoints = function (a, b) {
  2533. var delta = b.subtract(a);
  2534. var theta = Math.atan2(delta.y, delta.x);
  2535. return new Angle(theta);
  2536. };
  2537. Angle.FromRadians = function (radians) {
  2538. return new Angle(radians);
  2539. };
  2540. Angle.FromDegrees = function (degrees) {
  2541. return new Angle(degrees * Math.PI / 180);
  2542. };
  2543. return Angle;
  2544. })();
  2545. BABYLON.Angle = Angle;
  2546. var Arc2 = (function () {
  2547. function Arc2(startPoint, midPoint, endPoint) {
  2548. this.startPoint = startPoint;
  2549. this.midPoint = midPoint;
  2550. this.endPoint = endPoint;
  2551. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2552. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2553. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2554. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2555. 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);
  2556. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2557. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2558. var a1 = this.startAngle.degrees();
  2559. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2560. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2561. // angles correction
  2562. if (a2 - a1 > +180.0)
  2563. a2 -= 360.0;
  2564. if (a2 - a1 < -180.0)
  2565. a2 += 360.0;
  2566. if (a3 - a2 > +180.0)
  2567. a3 -= 360.0;
  2568. if (a3 - a2 < -180.0)
  2569. a3 += 360.0;
  2570. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2571. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2572. }
  2573. return Arc2;
  2574. })();
  2575. BABYLON.Arc2 = Arc2;
  2576. var PathCursor = (function () {
  2577. function PathCursor(path) {
  2578. this.path = path;
  2579. this._onchange = new Array();
  2580. this.value = 0;
  2581. this.animations = new Array();
  2582. }
  2583. PathCursor.prototype.getPoint = function () {
  2584. var point = this.path.getPointAtLengthPosition(this.value);
  2585. return new Vector3(point.x, 0, point.y);
  2586. };
  2587. PathCursor.prototype.moveAhead = function (step) {
  2588. if (step === void 0) { step = 0.002; }
  2589. this.move(step);
  2590. return this;
  2591. };
  2592. PathCursor.prototype.moveBack = function (step) {
  2593. if (step === void 0) { step = 0.002; }
  2594. this.move(-step);
  2595. return this;
  2596. };
  2597. PathCursor.prototype.move = function (step) {
  2598. if (Math.abs(step) > 1) {
  2599. throw "step size should be less than 1.";
  2600. }
  2601. this.value += step;
  2602. this.ensureLimits();
  2603. this.raiseOnChange();
  2604. return this;
  2605. };
  2606. PathCursor.prototype.ensureLimits = function () {
  2607. while (this.value > 1) {
  2608. this.value -= 1;
  2609. }
  2610. while (this.value < 0) {
  2611. this.value += 1;
  2612. }
  2613. return this;
  2614. };
  2615. // used by animation engine
  2616. PathCursor.prototype.markAsDirty = function (propertyName) {
  2617. this.ensureLimits();
  2618. this.raiseOnChange();
  2619. return this;
  2620. };
  2621. PathCursor.prototype.raiseOnChange = function () {
  2622. var _this = this;
  2623. this._onchange.forEach(function (f) { return f(_this); });
  2624. return this;
  2625. };
  2626. PathCursor.prototype.onchange = function (f) {
  2627. this._onchange.push(f);
  2628. return this;
  2629. };
  2630. return PathCursor;
  2631. })();
  2632. BABYLON.PathCursor = PathCursor;
  2633. var Path2 = (function () {
  2634. function Path2(x, y) {
  2635. this._points = new Array();
  2636. this._length = 0;
  2637. this.closed = false;
  2638. this._points.push(new Vector2(x, y));
  2639. }
  2640. Path2.prototype.addLineTo = function (x, y) {
  2641. if (closed) {
  2642. BABYLON.Tools.Error("cannot add lines to closed paths");
  2643. return this;
  2644. }
  2645. var newPoint = new Vector2(x, y);
  2646. var previousPoint = this._points[this._points.length - 1];
  2647. this._points.push(newPoint);
  2648. this._length += newPoint.subtract(previousPoint).length();
  2649. return this;
  2650. };
  2651. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2652. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2653. if (closed) {
  2654. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2655. return this;
  2656. }
  2657. var startPoint = this._points[this._points.length - 1];
  2658. var midPoint = new Vector2(midX, midY);
  2659. var endPoint = new Vector2(endX, endY);
  2660. var arc = new Arc2(startPoint, midPoint, endPoint);
  2661. var increment = arc.angle.radians() / numberOfSegments;
  2662. if (arc.orientation === Orientation.CW)
  2663. increment *= -1;
  2664. var currentAngle = arc.startAngle.radians() + increment;
  2665. for (var i = 0; i < numberOfSegments; i++) {
  2666. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2667. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2668. this.addLineTo(x, y);
  2669. currentAngle += increment;
  2670. }
  2671. return this;
  2672. };
  2673. Path2.prototype.close = function () {
  2674. this.closed = true;
  2675. return this;
  2676. };
  2677. Path2.prototype.length = function () {
  2678. var result = this._length;
  2679. if (!this.closed) {
  2680. var lastPoint = this._points[this._points.length - 1];
  2681. var firstPoint = this._points[0];
  2682. result += (firstPoint.subtract(lastPoint).length());
  2683. }
  2684. return result;
  2685. };
  2686. Path2.prototype.getPoints = function () {
  2687. return this._points;
  2688. };
  2689. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2690. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2691. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2692. return Vector2.Zero();
  2693. }
  2694. var lengthPosition = normalizedLengthPosition * this.length();
  2695. var previousOffset = 0;
  2696. for (var i = 0; i < this._points.length; i++) {
  2697. var j = (i + 1) % this._points.length;
  2698. var a = this._points[i];
  2699. var b = this._points[j];
  2700. var bToA = b.subtract(a);
  2701. var nextOffset = (bToA.length() + previousOffset);
  2702. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2703. var dir = bToA.normalize();
  2704. var localOffset = lengthPosition - previousOffset;
  2705. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2706. }
  2707. previousOffset = nextOffset;
  2708. }
  2709. BABYLON.Tools.Error("internal error");
  2710. return Vector2.Zero();
  2711. };
  2712. Path2.StartingAt = function (x, y) {
  2713. return new Path2(x, y);
  2714. };
  2715. return Path2;
  2716. })();
  2717. BABYLON.Path2 = Path2;
  2718. var Path3D = (function () {
  2719. function Path3D(path, firstNormal) {
  2720. this.path = path;
  2721. this._curve = new Array();
  2722. this._distances = new Array();
  2723. this._tangents = new Array();
  2724. this._normals = new Array();
  2725. this._binormals = new Array();
  2726. for (var p = 0; p < path.length; p++) {
  2727. this._curve[p] = path[p].clone(); // hard copy
  2728. }
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. this._tangents[0].normalize();
  2761. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2762. this._tangents[l - 1].normalize();
  2763. // normals and binormals at first point : arbitrary vector with _normalVector()
  2764. var tg0 = this._tangents[0];
  2765. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2766. this._normals[0] = pp0;
  2767. this._normals[0].normalize();
  2768. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2769. this._binormals[0].normalize();
  2770. this._distances[0] = 0;
  2771. // normals and binormals : next points
  2772. var prev; // previous vector (segment)
  2773. var cur; // current vector (segment)
  2774. var curTang; // current tangent
  2775. var prevNorm; // previous normal
  2776. var prevBinor; // previous binormal
  2777. for (var i = 1; i < l; i++) {
  2778. // tangents
  2779. prev = this._getLastNonNullVector(i);
  2780. if (i < l - 1) {
  2781. cur = this._getFirstNonNullVector(i);
  2782. this._tangents[i] = prev.add(cur);
  2783. this._tangents[i].normalize();
  2784. }
  2785. this._distances[i] = this._distances[i - 1] + prev.length();
  2786. // normals and binormals
  2787. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2788. curTang = this._tangents[i];
  2789. prevNorm = this._normals[i - 1];
  2790. prevBinor = this._binormals[i - 1];
  2791. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2792. this._normals[i].normalize();
  2793. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2794. this._binormals[i].normalize();
  2795. }
  2796. };
  2797. // private function getFirstNonNullVector(index)
  2798. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2799. Path3D.prototype._getFirstNonNullVector = function (index) {
  2800. var i = 1;
  2801. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2802. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2803. i++;
  2804. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2805. }
  2806. return nNVector;
  2807. };
  2808. // private function getLastNonNullVector(index)
  2809. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2810. Path3D.prototype._getLastNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2813. while (nLVector.length() == 0 && index > i + 1) {
  2814. i++;
  2815. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2816. }
  2817. return nLVector;
  2818. };
  2819. // private function normalVector(v0, vt, va) :
  2820. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2821. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2822. Path3D.prototype._normalVector = function (v0, vt, va) {
  2823. var normal0;
  2824. if (va === undefined || va === null) {
  2825. var point;
  2826. if (vt.y !== 1) {
  2827. point = new Vector3(0, -1, 0);
  2828. }
  2829. else if (vt.x !== 1) {
  2830. point = new Vector3(1, 0, 0);
  2831. }
  2832. else if (vt.z !== 1) {
  2833. point = new Vector3(0, 0, 1);
  2834. }
  2835. normal0 = Vector3.Cross(vt, point);
  2836. }
  2837. else {
  2838. normal0 = Vector3.Cross(vt, va);
  2839. Vector3.CrossToRef(normal0, vt, normal0);
  2840. }
  2841. normal0.normalize();
  2842. return normal0;
  2843. };
  2844. return Path3D;
  2845. })();
  2846. BABYLON.Path3D = Path3D;
  2847. var Curve3 = (function () {
  2848. function Curve3(points) {
  2849. this._length = 0;
  2850. this._points = points;
  2851. this._length = this._computeLength(points);
  2852. }
  2853. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2854. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2855. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2856. var bez = new Array();
  2857. var equation = function (t, val0, val1, val2) {
  2858. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2859. return res;
  2860. };
  2861. for (var i = 0; i <= nbPoints; i++) {
  2862. 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)));
  2863. }
  2864. return new Curve3(bez);
  2865. };
  2866. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2867. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2868. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2869. var bez = new Array();
  2870. var equation = function (t, val0, val1, val2, val3) {
  2871. 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;
  2872. return res;
  2873. };
  2874. for (var i = 0; i <= nbPoints; i++) {
  2875. 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)));
  2876. }
  2877. return new Curve3(bez);
  2878. };
  2879. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2880. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2881. var hermite = new Array();
  2882. var step = 1 / nbPoints;
  2883. for (var i = 0; i <= nbPoints; i++) {
  2884. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2885. }
  2886. return new Curve3(hermite);
  2887. };
  2888. Curve3.prototype.getPoints = function () {
  2889. return this._points;
  2890. };
  2891. Curve3.prototype.length = function () {
  2892. return this._length;
  2893. };
  2894. Curve3.prototype.continue = function (curve) {
  2895. var lastPoint = this._points[this._points.length - 1];
  2896. var continuedPoints = this._points.slice();
  2897. var curvePoints = curve.getPoints();
  2898. for (var i = 1; i < curvePoints.length; i++) {
  2899. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2900. }
  2901. var continuedCurve = new Curve3(continuedPoints);
  2902. return continuedCurve;
  2903. };
  2904. Curve3.prototype._computeLength = function (path) {
  2905. var l = 0;
  2906. for (var i = 1; i < path.length; i++) {
  2907. l += (path[i].subtract(path[i - 1])).length();
  2908. }
  2909. return l;
  2910. };
  2911. return Curve3;
  2912. })();
  2913. BABYLON.Curve3 = Curve3;
  2914. // Vertex formats
  2915. var PositionNormalVertex = (function () {
  2916. function PositionNormalVertex(position, normal) {
  2917. if (position === void 0) { position = Vector3.Zero(); }
  2918. if (normal === void 0) { normal = Vector3.Up(); }
  2919. this.position = position;
  2920. this.normal = normal;
  2921. }
  2922. PositionNormalVertex.prototype.clone = function () {
  2923. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2924. };
  2925. return PositionNormalVertex;
  2926. })();
  2927. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2928. var PositionNormalTextureVertex = (function () {
  2929. function PositionNormalTextureVertex(position, normal, uv) {
  2930. if (position === void 0) { position = Vector3.Zero(); }
  2931. if (normal === void 0) { normal = Vector3.Up(); }
  2932. if (uv === void 0) { uv = Vector2.Zero(); }
  2933. this.position = position;
  2934. this.normal = normal;
  2935. this.uv = uv;
  2936. }
  2937. PositionNormalTextureVertex.prototype.clone = function () {
  2938. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2939. };
  2940. return PositionNormalTextureVertex;
  2941. })();
  2942. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2943. // SIMD
  2944. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2945. var previousInvertToRef = Matrix.prototype.invertToRef;
  2946. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2947. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2948. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2949. var SIMDHelper = (function () {
  2950. function SIMDHelper() {
  2951. }
  2952. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2953. get: function () {
  2954. return SIMDHelper._isEnabled;
  2955. },
  2956. enumerable: true,
  2957. configurable: true
  2958. });
  2959. SIMDHelper.DisableSIMD = function () {
  2960. // Replace functions
  2961. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2962. Matrix.prototype.invertToRef = previousInvertToRef;
  2963. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2964. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2965. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2966. SIMDHelper._isEnabled = false;
  2967. };
  2968. SIMDHelper.EnableSIMD = function () {
  2969. if (window.SIMD === undefined) {
  2970. return;
  2971. }
  2972. // Replace functions
  2973. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2974. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2975. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2976. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2977. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2978. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2979. get: function () { return this._data[0]; },
  2980. set: function (value) {
  2981. if (!this._data) {
  2982. this._data = new Float32Array(3);
  2983. }
  2984. this._data[0] = value;
  2985. }
  2986. });
  2987. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2988. get: function () { return this._data[1]; },
  2989. set: function (value) {
  2990. this._data[1] = value;
  2991. }
  2992. });
  2993. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2994. get: function () { return this._data[2]; },
  2995. set: function (value) {
  2996. this._data[2] = value;
  2997. }
  2998. });
  2999. SIMDHelper._isEnabled = true;
  3000. };
  3001. SIMDHelper._isEnabled = false;
  3002. return SIMDHelper;
  3003. })();
  3004. BABYLON.SIMDHelper = SIMDHelper;
  3005. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3006. SIMDHelper.EnableSIMD();
  3007. }
  3008. })(BABYLON || (BABYLON = {}));
  3009. //# sourceMappingURL=babylon.math.js.map
  3010. var BABYLON;
  3011. (function (BABYLON) {
  3012. var Database = (function () {
  3013. function Database(urlToScene, callbackManifestChecked) {
  3014. // Handling various flavors of prefixed version of IndexedDB
  3015. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3016. this.callbackManifestChecked = callbackManifestChecked;
  3017. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  3018. this.db = null;
  3019. this.enableSceneOffline = false;
  3020. this.enableTexturesOffline = false;
  3021. this.manifestVersionFound = 0;
  3022. this.mustUpdateRessources = false;
  3023. this.hasReachedQuota = false;
  3024. this.checkManifestFile();
  3025. }
  3026. Database.prototype.checkManifestFile = function () {
  3027. var _this = this;
  3028. function noManifestFile() {
  3029. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  3030. that.enableSceneOffline = false;
  3031. that.enableTexturesOffline = false;
  3032. that.callbackManifestChecked(false);
  3033. }
  3034. var that = this;
  3035. var manifestURL = this.currentSceneUrl + ".manifest";
  3036. var xhr = new XMLHttpRequest();
  3037. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3038. xhr.open("GET", manifestURLTimeStamped, true);
  3039. xhr.addEventListener("load", function () {
  3040. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3041. try {
  3042. var manifestFile = JSON.parse(xhr.response);
  3043. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3044. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3045. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3046. _this.manifestVersionFound = manifestFile.version;
  3047. }
  3048. if (_this.callbackManifestChecked) {
  3049. _this.callbackManifestChecked(true);
  3050. }
  3051. }
  3052. catch (ex) {
  3053. noManifestFile();
  3054. }
  3055. }
  3056. else {
  3057. noManifestFile();
  3058. }
  3059. }, false);
  3060. xhr.addEventListener("error", function (event) {
  3061. noManifestFile();
  3062. }, false);
  3063. try {
  3064. xhr.send();
  3065. }
  3066. catch (ex) {
  3067. BABYLON.Tools.Error("Error on XHR send request.");
  3068. that.callbackManifestChecked(false);
  3069. }
  3070. };
  3071. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3072. var _this = this;
  3073. function handleError() {
  3074. that.isSupported = false;
  3075. if (errorCallback)
  3076. errorCallback();
  3077. }
  3078. var that = this;
  3079. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3080. // Your browser doesn't support IndexedDB
  3081. this.isSupported = false;
  3082. if (errorCallback)
  3083. errorCallback();
  3084. }
  3085. else {
  3086. // If the DB hasn't been opened or created yet
  3087. if (!this.db) {
  3088. this.hasReachedQuota = false;
  3089. this.isSupported = true;
  3090. var request = this.idbFactory.open("babylonjs", 1);
  3091. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3092. request.onerror = function (event) {
  3093. handleError();
  3094. };
  3095. // executes when a version change transaction cannot complete due to other active transactions
  3096. request.onblocked = function (event) {
  3097. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3098. handleError();
  3099. };
  3100. // DB has been opened successfully
  3101. request.onsuccess = function (event) {
  3102. _this.db = request.result;
  3103. successCallback();
  3104. };
  3105. // Initialization of the DB. Creating Scenes & Textures stores
  3106. request.onupgradeneeded = function (event) {
  3107. _this.db = (event.target).result;
  3108. try {
  3109. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3110. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3111. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3112. }
  3113. catch (ex) {
  3114. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3115. handleError();
  3116. }
  3117. };
  3118. }
  3119. else {
  3120. if (successCallback)
  3121. successCallback();
  3122. }
  3123. }
  3124. };
  3125. Database.prototype.loadImageFromDB = function (url, image) {
  3126. var _this = this;
  3127. var completeURL = Database.ReturnFullUrlLocation(url);
  3128. var saveAndLoadImage = function () {
  3129. if (!_this.hasReachedQuota && _this.db !== null) {
  3130. // the texture is not yet in the DB, let's try to save it
  3131. _this._saveImageIntoDBAsync(completeURL, image);
  3132. }
  3133. else {
  3134. image.src = url;
  3135. }
  3136. };
  3137. if (!this.mustUpdateRessources) {
  3138. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3139. }
  3140. else {
  3141. saveAndLoadImage();
  3142. }
  3143. };
  3144. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3145. if (this.isSupported && this.db !== null) {
  3146. var texture;
  3147. var transaction = this.db.transaction(["textures"]);
  3148. transaction.onabort = function (event) {
  3149. image.src = url;
  3150. };
  3151. transaction.oncomplete = function (event) {
  3152. var blobTextureURL;
  3153. if (texture) {
  3154. var URL = window.URL || window.webkitURL;
  3155. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3156. image.onerror = function () {
  3157. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3158. image.src = url;
  3159. };
  3160. image.src = blobTextureURL;
  3161. }
  3162. else {
  3163. notInDBCallback();
  3164. }
  3165. };
  3166. var getRequest = transaction.objectStore("textures").get(url);
  3167. getRequest.onsuccess = function (event) {
  3168. texture = (event.target).result;
  3169. };
  3170. getRequest.onerror = function (event) {
  3171. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3172. image.src = url;
  3173. };
  3174. }
  3175. else {
  3176. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3177. image.src = url;
  3178. }
  3179. };
  3180. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3181. var _this = this;
  3182. if (this.isSupported) {
  3183. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3184. var generateBlobUrl = function () {
  3185. var blobTextureURL;
  3186. if (blob) {
  3187. var URL = window.URL || window.webkitURL;
  3188. try {
  3189. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3190. }
  3191. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  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. generateBlobUrl();
  3217. };
  3218. transaction.oncomplete = function (event) {
  3219. generateBlobUrl();
  3220. };
  3221. var newTexture = { textureUrl: url, data: blob };
  3222. try {
  3223. // Put the blob into the dabase
  3224. var addRequest = transaction.objectStore("textures").put(newTexture);
  3225. addRequest.onsuccess = function (event) {
  3226. };
  3227. addRequest.onerror = function (event) {
  3228. generateBlobUrl();
  3229. };
  3230. }
  3231. catch (ex) {
  3232. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3233. if (ex.code === 25) {
  3234. Database.isUASupportingBlobStorage = false;
  3235. }
  3236. image.src = url;
  3237. }
  3238. }
  3239. else {
  3240. image.src = url;
  3241. }
  3242. }, false);
  3243. xhr.addEventListener("error", function (event) {
  3244. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3245. image.src = url;
  3246. }, false);
  3247. xhr.send();
  3248. }
  3249. else {
  3250. image.src = url;
  3251. }
  3252. }
  3253. else {
  3254. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3255. image.src = url;
  3256. }
  3257. };
  3258. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3259. var _this = this;
  3260. var updateVersion = function (event) {
  3261. // the version is not yet in the DB or we need to update it
  3262. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3263. };
  3264. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3265. };
  3266. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3267. var _this = this;
  3268. if (this.isSupported) {
  3269. var version;
  3270. try {
  3271. var transaction = this.db.transaction(["versions"]);
  3272. transaction.oncomplete = function (event) {
  3273. if (version) {
  3274. // If the version in the JSON file is > than the version in DB
  3275. if (_this.manifestVersionFound > version.data) {
  3276. _this.mustUpdateRessources = true;
  3277. updateInDBCallback();
  3278. }
  3279. else {
  3280. callback(version.data);
  3281. }
  3282. }
  3283. else {
  3284. _this.mustUpdateRessources = true;
  3285. updateInDBCallback();
  3286. }
  3287. };
  3288. transaction.onabort = function (event) {
  3289. callback(-1);
  3290. };
  3291. var getRequest = transaction.objectStore("versions").get(url);
  3292. getRequest.onsuccess = function (event) {
  3293. version = (event.target).result;
  3294. };
  3295. getRequest.onerror = function (event) {
  3296. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3297. callback(-1);
  3298. };
  3299. }
  3300. catch (ex) {
  3301. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3302. callback(-1);
  3303. }
  3304. }
  3305. else {
  3306. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3307. callback(-1);
  3308. }
  3309. };
  3310. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3311. var _this = this;
  3312. if (this.isSupported && !this.hasReachedQuota) {
  3313. try {
  3314. // Open a transaction to the database
  3315. var transaction = this.db.transaction(["versions"], "readwrite");
  3316. // the transaction could abort because of a QuotaExceededError error
  3317. transaction.onabort = function (event) {
  3318. try {
  3319. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3320. _this.hasReachedQuota = true;
  3321. }
  3322. }
  3323. catch (ex) { }
  3324. callback(-1);
  3325. };
  3326. transaction.oncomplete = function (event) {
  3327. callback(_this.manifestVersionFound);
  3328. };
  3329. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3330. // Put the scene into the database
  3331. var addRequest = transaction.objectStore("versions").put(newVersion);
  3332. addRequest.onsuccess = function (event) {
  3333. };
  3334. addRequest.onerror = function (event) {
  3335. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3336. };
  3337. }
  3338. catch (ex) {
  3339. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3340. callback(-1);
  3341. }
  3342. }
  3343. else {
  3344. callback(-1);
  3345. }
  3346. };
  3347. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3348. var _this = this;
  3349. var completeUrl = Database.ReturnFullUrlLocation(url);
  3350. var saveAndLoadFile = function (event) {
  3351. // the scene is not yet in the DB, let's try to save it
  3352. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3353. };
  3354. this._checkVersionFromDB(completeUrl, function (version) {
  3355. if (version !== -1) {
  3356. if (!_this.mustUpdateRessources) {
  3357. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3358. }
  3359. else {
  3360. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3361. }
  3362. }
  3363. else {
  3364. errorCallback();
  3365. }
  3366. });
  3367. };
  3368. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3369. if (this.isSupported) {
  3370. var targetStore;
  3371. if (url.indexOf(".babylon") !== -1) {
  3372. targetStore = "scenes";
  3373. }
  3374. else {
  3375. targetStore = "textures";
  3376. }
  3377. var file;
  3378. var transaction = this.db.transaction([targetStore]);
  3379. transaction.oncomplete = function (event) {
  3380. if (file) {
  3381. callback(file.data);
  3382. }
  3383. else {
  3384. notInDBCallback();
  3385. }
  3386. };
  3387. transaction.onabort = function (event) {
  3388. notInDBCallback();
  3389. };
  3390. var getRequest = transaction.objectStore(targetStore).get(url);
  3391. getRequest.onsuccess = function (event) {
  3392. file = (event.target).result;
  3393. };
  3394. getRequest.onerror = function (event) {
  3395. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3396. notInDBCallback();
  3397. };
  3398. }
  3399. else {
  3400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3401. callback();
  3402. }
  3403. };
  3404. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3405. var _this = this;
  3406. if (this.isSupported) {
  3407. var targetStore;
  3408. if (url.indexOf(".babylon") !== -1) {
  3409. targetStore = "scenes";
  3410. }
  3411. else {
  3412. targetStore = "textures";
  3413. }
  3414. // Create XHR
  3415. var xhr = new XMLHttpRequest(), fileData;
  3416. xhr.open("GET", url, true);
  3417. if (useArrayBuffer) {
  3418. xhr.responseType = "arraybuffer";
  3419. }
  3420. xhr.onprogress = progressCallback;
  3421. xhr.addEventListener("load", function () {
  3422. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3423. // Blob as response (XHR2)
  3424. //fileData = xhr.responseText;
  3425. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3426. if (!_this.hasReachedQuota) {
  3427. // Open a transaction to the database
  3428. var transaction = _this.db.transaction([targetStore], "readwrite");
  3429. // the transaction could abort because of a QuotaExceededError error
  3430. transaction.onabort = function (event) {
  3431. try {
  3432. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3433. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3434. this.hasReachedQuota = true;
  3435. }
  3436. }
  3437. catch (ex) { }
  3438. callback(fileData);
  3439. };
  3440. transaction.oncomplete = function (event) {
  3441. callback(fileData);
  3442. };
  3443. var newFile;
  3444. if (targetStore === "scenes") {
  3445. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3446. }
  3447. else {
  3448. newFile = { textureUrl: url, data: fileData };
  3449. }
  3450. try {
  3451. // Put the scene into the database
  3452. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3453. addRequest.onsuccess = function (event) {
  3454. };
  3455. addRequest.onerror = function (event) {
  3456. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3457. };
  3458. }
  3459. catch (ex) {
  3460. callback(fileData);
  3461. }
  3462. }
  3463. else {
  3464. callback(fileData);
  3465. }
  3466. }
  3467. else {
  3468. callback();
  3469. }
  3470. }, false);
  3471. xhr.addEventListener("error", function (event) {
  3472. BABYLON.Tools.Error("error on XHR request.");
  3473. callback();
  3474. }, false);
  3475. xhr.send();
  3476. }
  3477. else {
  3478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3479. callback();
  3480. }
  3481. };
  3482. Database.isUASupportingBlobStorage = true;
  3483. Database.parseURL = function (url) {
  3484. var a = document.createElement('a');
  3485. a.href = url;
  3486. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3487. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3488. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3489. return absLocation;
  3490. };
  3491. Database.ReturnFullUrlLocation = function (url) {
  3492. if (url.indexOf("http:/") === -1) {
  3493. return (BABYLON.Database.parseURL(window.location.href) + url);
  3494. }
  3495. else {
  3496. return url;
  3497. }
  3498. };
  3499. return Database;
  3500. })();
  3501. BABYLON.Database = Database;
  3502. })(BABYLON || (BABYLON = {}));
  3503. //# sourceMappingURL=babylon.database.js.map
  3504. var BABYLON;
  3505. (function (BABYLON) {
  3506. var Internals;
  3507. (function (Internals) {
  3508. /*
  3509. * Based on jsTGALoader - Javascript loader for TGA file
  3510. * By Vincent Thibault
  3511. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3512. */
  3513. var TGATools = (function () {
  3514. function TGATools() {
  3515. }
  3516. TGATools.GetTGAHeader = function (data) {
  3517. var offset = 0;
  3518. var header = {
  3519. id_length: data[offset++],
  3520. colormap_type: data[offset++],
  3521. image_type: data[offset++],
  3522. colormap_index: data[offset++] | data[offset++] << 8,
  3523. colormap_length: data[offset++] | data[offset++] << 8,
  3524. colormap_size: data[offset++],
  3525. origin: [
  3526. data[offset++] | data[offset++] << 8,
  3527. data[offset++] | data[offset++] << 8
  3528. ],
  3529. width: data[offset++] | data[offset++] << 8,
  3530. height: data[offset++] | data[offset++] << 8,
  3531. pixel_size: data[offset++],
  3532. flags: data[offset++]
  3533. };
  3534. return header;
  3535. };
  3536. TGATools.UploadContent = function (gl, data) {
  3537. // Not enough data to contain header ?
  3538. if (data.length < 19) {
  3539. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3540. return;
  3541. }
  3542. // Read Header
  3543. var offset = 18;
  3544. var header = TGATools.GetTGAHeader(data);
  3545. // Assume it's a valid Targa file.
  3546. if (header.id_length + offset > data.length) {
  3547. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3548. return;
  3549. }
  3550. // Skip not needed data
  3551. offset += header.id_length;
  3552. var use_rle = false;
  3553. var use_pal = false;
  3554. var use_rgb = false;
  3555. var use_grey = false;
  3556. // Get some informations.
  3557. switch (header.image_type) {
  3558. case TGATools._TYPE_RLE_INDEXED:
  3559. use_rle = true;
  3560. case TGATools._TYPE_INDEXED:
  3561. use_pal = true;
  3562. break;
  3563. case TGATools._TYPE_RLE_RGB:
  3564. use_rle = true;
  3565. case TGATools._TYPE_RGB:
  3566. use_rgb = true;
  3567. break;
  3568. case TGATools._TYPE_RLE_GREY:
  3569. use_rle = true;
  3570. case TGATools._TYPE_GREY:
  3571. use_grey = true;
  3572. break;
  3573. }
  3574. var pixel_data;
  3575. var numAlphaBits = header.flags & 0xf;
  3576. var pixel_size = header.pixel_size >> 3;
  3577. var pixel_total = header.width * header.height * pixel_size;
  3578. // Read palettes
  3579. var palettes;
  3580. if (use_pal) {
  3581. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3582. }
  3583. // Read LRE
  3584. if (use_rle) {
  3585. pixel_data = new Uint8Array(pixel_total);
  3586. var c, count, i;
  3587. var localOffset = 0;
  3588. var pixels = new Uint8Array(pixel_size);
  3589. while (offset < pixel_total && localOffset < pixel_total) {
  3590. c = data[offset++];
  3591. count = (c & 0x7f) + 1;
  3592. // RLE pixels
  3593. if (c & 0x80) {
  3594. // Bind pixel tmp array
  3595. for (i = 0; i < pixel_size; ++i) {
  3596. pixels[i] = data[offset++];
  3597. }
  3598. // Copy pixel array
  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) +
  3784. (value.charCodeAt(1) << 8) +
  3785. (value.charCodeAt(2) << 16) +
  3786. (value.charCodeAt(3) << 24);
  3787. }
  3788. function Int32ToFourCC(value) {
  3789. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3790. }
  3791. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3792. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3793. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3794. var headerLengthInt = 31; // The header length in 32 bit ints
  3795. // Offsets into the header array
  3796. var off_magic = 0;
  3797. var off_size = 1;
  3798. var off_flags = 2;
  3799. var off_height = 3;
  3800. var off_width = 4;
  3801. var off_mipmapCount = 7;
  3802. var off_pfFlags = 20;
  3803. var off_pfFourCC = 21;
  3804. var off_RGBbpp = 22;
  3805. var off_RMask = 23;
  3806. var off_GMask = 24;
  3807. var off_BMask = 25;
  3808. var off_AMask = 26;
  3809. var off_caps1 = 27;
  3810. var off_caps2 = 28;
  3811. ;
  3812. var DDSTools = (function () {
  3813. function DDSTools() {
  3814. }
  3815. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3816. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3817. var mipmapCount = 1;
  3818. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3819. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3820. }
  3821. return {
  3822. width: header[off_width],
  3823. height: header[off_height],
  3824. mipmapCount: mipmapCount,
  3825. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3826. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3827. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3828. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3829. };
  3830. };
  3831. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3832. var byteArray = new Uint8Array(dataLength);
  3833. var srcData = new Uint8Array(arrayBuffer);
  3834. var index = 0;
  3835. for (var y = height - 1; y >= 0; y--) {
  3836. for (var x = 0; x < width; x++) {
  3837. var srcPos = dataOffset + (x + y * width) * 4;
  3838. byteArray[index + 2] = srcData[srcPos];
  3839. byteArray[index + 1] = srcData[srcPos + 1];
  3840. byteArray[index] = srcData[srcPos + 2];
  3841. byteArray[index + 3] = srcData[srcPos + 3];
  3842. index += 4;
  3843. }
  3844. }
  3845. return byteArray;
  3846. };
  3847. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3848. var byteArray = new Uint8Array(dataLength);
  3849. var srcData = new Uint8Array(arrayBuffer);
  3850. var index = 0;
  3851. for (var y = height - 1; y >= 0; y--) {
  3852. for (var x = 0; x < width; x++) {
  3853. var srcPos = dataOffset + (x + y * width) * 3;
  3854. byteArray[index + 2] = srcData[srcPos];
  3855. byteArray[index + 1] = srcData[srcPos + 1];
  3856. byteArray[index] = srcData[srcPos + 2];
  3857. index += 3;
  3858. }
  3859. }
  3860. return byteArray;
  3861. };
  3862. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3863. var byteArray = new Uint8Array(dataLength);
  3864. var srcData = new Uint8Array(arrayBuffer);
  3865. var index = 0;
  3866. for (var y = height - 1; y >= 0; y--) {
  3867. for (var x = 0; x < width; x++) {
  3868. var srcPos = dataOffset + (x + y * width);
  3869. byteArray[index] = srcData[srcPos];
  3870. index++;
  3871. }
  3872. }
  3873. return byteArray;
  3874. };
  3875. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3876. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3877. if (header[off_magic] != DDS_MAGIC) {
  3878. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3879. return;
  3880. }
  3881. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3882. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3883. return;
  3884. }
  3885. if (info.isFourCC) {
  3886. fourCC = header[off_pfFourCC];
  3887. switch (fourCC) {
  3888. case FOURCC_DXT1:
  3889. blockBytes = 8;
  3890. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3891. break;
  3892. case FOURCC_DXT3:
  3893. blockBytes = 16;
  3894. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3895. break;
  3896. case FOURCC_DXT5:
  3897. blockBytes = 16;
  3898. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3899. break;
  3900. default:
  3901. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3902. return;
  3903. }
  3904. }
  3905. mipmapCount = 1;
  3906. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3907. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3908. }
  3909. var bpp = header[off_RGBbpp];
  3910. for (var face = 0; face < faces; face++) {
  3911. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3912. width = header[off_width];
  3913. height = header[off_height];
  3914. dataOffset = header[off_size] + 4;
  3915. for (i = 0; i < mipmapCount; ++i) {
  3916. if (info.isRGB) {
  3917. if (bpp == 24) {
  3918. dataLength = width * height * 3;
  3919. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3920. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3921. }
  3922. else {
  3923. dataLength = width * height * 4;
  3924. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3925. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3926. }
  3927. }
  3928. else if (info.isLuminance) {
  3929. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3930. var unpaddedRowSize = width;
  3931. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3932. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3933. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3934. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3935. }
  3936. else {
  3937. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3938. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3939. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3940. }
  3941. dataOffset += dataLength;
  3942. width *= 0.5;
  3943. height *= 0.5;
  3944. width = Math.max(1.0, width);
  3945. height = Math.max(1.0, height);
  3946. }
  3947. }
  3948. };
  3949. return DDSTools;
  3950. })();
  3951. Internals.DDSTools = DDSTools;
  3952. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3953. })(BABYLON || (BABYLON = {}));
  3954. //# sourceMappingURL=babylon.tools.dds.js.map
  3955. var BABYLON;
  3956. (function (BABYLON) {
  3957. var SmartArray = (function () {
  3958. function SmartArray(capacity) {
  3959. this.length = 0;
  3960. this._duplicateId = 0;
  3961. this.data = new Array(capacity);
  3962. this._id = SmartArray._GlobalId++;
  3963. }
  3964. SmartArray.prototype.push = function (value) {
  3965. this.data[this.length++] = value;
  3966. if (this.length > this.data.length) {
  3967. this.data.length *= 2;
  3968. }
  3969. if (!value.__smartArrayFlags) {
  3970. value.__smartArrayFlags = {};
  3971. }
  3972. value.__smartArrayFlags[this._id] = this._duplicateId;
  3973. };
  3974. SmartArray.prototype.pushNoDuplicate = function (value) {
  3975. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3976. return;
  3977. }
  3978. this.push(value);
  3979. };
  3980. SmartArray.prototype.sort = function (compareFn) {
  3981. this.data.sort(compareFn);
  3982. };
  3983. SmartArray.prototype.reset = function () {
  3984. this.length = 0;
  3985. this._duplicateId++;
  3986. };
  3987. SmartArray.prototype.concat = function (array) {
  3988. if (array.length === 0) {
  3989. return;
  3990. }
  3991. if (this.length + array.length > this.data.length) {
  3992. this.data.length = (this.length + array.length) * 2;
  3993. }
  3994. for (var index = 0; index < array.length; index++) {
  3995. this.data[this.length++] = (array.data || array)[index];
  3996. }
  3997. };
  3998. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3999. if (array.length === 0) {
  4000. return;
  4001. }
  4002. if (this.length + array.length > this.data.length) {
  4003. this.data.length = (this.length + array.length) * 2;
  4004. }
  4005. for (var index = 0; index < array.length; index++) {
  4006. var item = (array.data || array)[index];
  4007. this.pushNoDuplicate(item);
  4008. }
  4009. };
  4010. SmartArray.prototype.indexOf = function (value) {
  4011. var position = this.data.indexOf(value);
  4012. if (position >= this.length) {
  4013. return -1;
  4014. }
  4015. return position;
  4016. };
  4017. // Statics
  4018. SmartArray._GlobalId = 0;
  4019. return SmartArray;
  4020. })();
  4021. BABYLON.SmartArray = SmartArray;
  4022. })(BABYLON || (BABYLON = {}));
  4023. //# sourceMappingURL=babylon.smartArray.js.map
  4024. var BABYLON;
  4025. (function (BABYLON) {
  4026. var SmartCollection = (function () {
  4027. function SmartCollection(capacity) {
  4028. if (capacity === void 0) { capacity = 10; }
  4029. this.count = 0;
  4030. this._initialCapacity = capacity;
  4031. this.items = {};
  4032. this._keys = new Array(this._initialCapacity);
  4033. }
  4034. SmartCollection.prototype.add = function (key, item) {
  4035. if (this.items[key] != undefined) {
  4036. return -1;
  4037. }
  4038. this.items[key] = item;
  4039. //literal keys are always strings, but we keep source type of key in _keys array
  4040. this._keys[this.count++] = key;
  4041. if (this.count > this._keys.length) {
  4042. this._keys.length *= 2;
  4043. }
  4044. return this.count;
  4045. };
  4046. SmartCollection.prototype.remove = function (key) {
  4047. if (this.items[key] == undefined) {
  4048. return -1;
  4049. }
  4050. return this.removeItemOfIndex(this.indexOf(key));
  4051. };
  4052. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4053. if (index < this.count && index > -1) {
  4054. delete this.items[this._keys[index]];
  4055. //here, shifting by hand is better optimised than .splice
  4056. while (index < this.count) {
  4057. this._keys[index] = this._keys[index + 1];
  4058. index++;
  4059. }
  4060. }
  4061. else {
  4062. return -1;
  4063. }
  4064. return --this.count;
  4065. };
  4066. SmartCollection.prototype.indexOf = function (key) {
  4067. for (var i = 0; i !== this.count; i++) {
  4068. if (this._keys[i] === key) {
  4069. return i;
  4070. }
  4071. }
  4072. return -1;
  4073. };
  4074. SmartCollection.prototype.item = function (key) {
  4075. return this.items[key];
  4076. };
  4077. SmartCollection.prototype.getAllKeys = function () {
  4078. if (this.count > 0) {
  4079. var keys = new Array(this.count);
  4080. for (var i = 0; i < this.count; i++) {
  4081. keys[i] = this._keys[i];
  4082. }
  4083. return keys;
  4084. }
  4085. else {
  4086. return undefined;
  4087. }
  4088. };
  4089. SmartCollection.prototype.getKeyByIndex = function (index) {
  4090. if (index < this.count && index > -1) {
  4091. return this._keys[index];
  4092. }
  4093. else {
  4094. return undefined;
  4095. }
  4096. };
  4097. SmartCollection.prototype.getItemByIndex = function (index) {
  4098. if (index < this.count && index > -1) {
  4099. return this.items[this._keys[index]];
  4100. }
  4101. else {
  4102. return undefined;
  4103. }
  4104. };
  4105. SmartCollection.prototype.empty = function () {
  4106. if (this.count > 0) {
  4107. this.count = 0;
  4108. this.items = {};
  4109. this._keys = new Array(this._initialCapacity);
  4110. }
  4111. };
  4112. SmartCollection.prototype.forEach = function (block) {
  4113. var key;
  4114. for (key in this.items) {
  4115. if (this.items.hasOwnProperty(key)) {
  4116. block(this.items[key]);
  4117. }
  4118. }
  4119. };
  4120. return SmartCollection;
  4121. })();
  4122. BABYLON.SmartCollection = SmartCollection;
  4123. })(BABYLON || (BABYLON = {}));
  4124. //# sourceMappingURL=babylon.smartCollection.js.map
  4125. var BABYLON;
  4126. (function (BABYLON) {
  4127. // Screenshots
  4128. var screenshotCanvas;
  4129. var cloneValue = function (source, destinationObject) {
  4130. if (!source)
  4131. return null;
  4132. if (source instanceof BABYLON.Mesh) {
  4133. return null;
  4134. }
  4135. if (source instanceof BABYLON.SubMesh) {
  4136. return source.clone(destinationObject);
  4137. }
  4138. else if (source.clone) {
  4139. return source.clone();
  4140. }
  4141. return null;
  4142. };
  4143. var Tools = (function () {
  4144. function Tools() {
  4145. }
  4146. Tools.SetImmediate = function (action) {
  4147. if (window.setImmediate) {
  4148. window.setImmediate(action);
  4149. }
  4150. else {
  4151. setTimeout(action, 1);
  4152. }
  4153. };
  4154. Tools.IsExponantOfTwo = function (value) {
  4155. var count = 1;
  4156. do {
  4157. count *= 2;
  4158. } while (count < value);
  4159. return count === value;
  4160. };
  4161. ;
  4162. Tools.GetExponantOfTwo = function (value, max) {
  4163. var count = 1;
  4164. do {
  4165. count *= 2;
  4166. } while (count < value);
  4167. if (count > max)
  4168. count = max;
  4169. return count;
  4170. };
  4171. ;
  4172. Tools.GetFilename = function (path) {
  4173. var index = path.lastIndexOf("/");
  4174. if (index < 0)
  4175. return path;
  4176. return path.substring(index + 1);
  4177. };
  4178. Tools.GetDOMTextContent = function (element) {
  4179. var result = "";
  4180. var child = element.firstChild;
  4181. while (child) {
  4182. if (child.nodeType === 3) {
  4183. result += child.textContent;
  4184. }
  4185. child = child.nextSibling;
  4186. }
  4187. return result;
  4188. };
  4189. Tools.ToDegrees = function (angle) {
  4190. return angle * 180 / Math.PI;
  4191. };
  4192. Tools.ToRadians = function (angle) {
  4193. return angle * Math.PI / 180;
  4194. };
  4195. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4196. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4197. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4198. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4199. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4200. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4201. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4202. }
  4203. return {
  4204. minimum: minimum,
  4205. maximum: maximum
  4206. };
  4207. };
  4208. Tools.ExtractMinAndMax = function (positions, start, count) {
  4209. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4210. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4211. for (var index = start; index < start + count; index++) {
  4212. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4213. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4214. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4215. }
  4216. return {
  4217. minimum: minimum,
  4218. maximum: maximum
  4219. };
  4220. };
  4221. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4222. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4223. return undefined;
  4224. return Array.isArray(obj) ? obj : [obj];
  4225. };
  4226. // Misc.
  4227. Tools.GetPointerPrefix = function () {
  4228. var eventPrefix = "pointer";
  4229. // Check if hand.js is referenced or if the browser natively supports pointer events
  4230. if (!navigator.pointerEnabled) {
  4231. eventPrefix = "mouse";
  4232. }
  4233. return eventPrefix;
  4234. };
  4235. Tools.QueueNewFrame = function (func) {
  4236. if (window.requestAnimationFrame)
  4237. window.requestAnimationFrame(func);
  4238. else if (window.msRequestAnimationFrame)
  4239. window.msRequestAnimationFrame(func);
  4240. else if (window.webkitRequestAnimationFrame)
  4241. window.webkitRequestAnimationFrame(func);
  4242. else if (window.mozRequestAnimationFrame)
  4243. window.mozRequestAnimationFrame(func);
  4244. else if (window.oRequestAnimationFrame)
  4245. window.oRequestAnimationFrame(func);
  4246. else {
  4247. window.setTimeout(func, 16);
  4248. }
  4249. };
  4250. Tools.RequestFullscreen = function (element) {
  4251. if (element.requestFullscreen)
  4252. element.requestFullscreen();
  4253. else if (element.msRequestFullscreen)
  4254. element.msRequestFullscreen();
  4255. else if (element.webkitRequestFullscreen)
  4256. element.webkitRequestFullscreen();
  4257. else if (element.mozRequestFullScreen)
  4258. element.mozRequestFullScreen();
  4259. };
  4260. Tools.ExitFullscreen = function () {
  4261. if (document.exitFullscreen) {
  4262. document.exitFullscreen();
  4263. }
  4264. else if (document.mozCancelFullScreen) {
  4265. document.mozCancelFullScreen();
  4266. }
  4267. else if (document.webkitCancelFullScreen) {
  4268. document.webkitCancelFullScreen();
  4269. }
  4270. else if (document.msCancelFullScreen) {
  4271. document.msCancelFullScreen();
  4272. }
  4273. };
  4274. // External files
  4275. Tools.CleanUrl = function (url) {
  4276. url = url.replace(/#/mg, "%23");
  4277. return url;
  4278. };
  4279. Tools.LoadImage = function (url, onload, onerror, database) {
  4280. url = Tools.CleanUrl(url);
  4281. var img = new Image();
  4282. if (url.substr(0, 5) !== "data:")
  4283. img.crossOrigin = 'anonymous';
  4284. img.onload = function () {
  4285. onload(img);
  4286. };
  4287. img.onerror = function (err) {
  4288. onerror(img, err);
  4289. };
  4290. var noIndexedDB = function () {
  4291. img.src = url;
  4292. };
  4293. var loadFromIndexedDB = function () {
  4294. database.loadImageFromDB(url, img);
  4295. };
  4296. //ANY database to do!
  4297. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4298. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4299. }
  4300. else {
  4301. if (url.indexOf("file:") === -1) {
  4302. noIndexedDB();
  4303. }
  4304. else {
  4305. try {
  4306. var textureName = url.substring(5);
  4307. var blobURL;
  4308. try {
  4309. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4310. }
  4311. catch (ex) {
  4312. // Chrome doesn't support oneTimeOnly parameter
  4313. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4314. }
  4315. img.src = blobURL;
  4316. }
  4317. catch (e) {
  4318. Tools.Log("Error while trying to load texture: " + textureName);
  4319. img.src = null;
  4320. }
  4321. }
  4322. }
  4323. return img;
  4324. };
  4325. //ANY
  4326. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4327. url = Tools.CleanUrl(url);
  4328. var noIndexedDB = function () {
  4329. var request = new XMLHttpRequest();
  4330. var loadUrl = Tools.BaseUrl + url;
  4331. request.open('GET', loadUrl, true);
  4332. if (useArrayBuffer) {
  4333. request.responseType = "arraybuffer";
  4334. }
  4335. request.onprogress = progressCallBack;
  4336. request.onreadystatechange = function () {
  4337. if (request.readyState === 4) {
  4338. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4339. callback(!useArrayBuffer ? request.responseText : request.response);
  4340. }
  4341. else {
  4342. if (onError) {
  4343. onError();
  4344. }
  4345. else {
  4346. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4347. }
  4348. }
  4349. }
  4350. };
  4351. request.send(null);
  4352. };
  4353. var loadFromIndexedDB = function () {
  4354. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4355. };
  4356. if (url.indexOf("file:") !== -1) {
  4357. var fileName = url.substring(5);
  4358. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4359. }
  4360. else {
  4361. // Caching all files
  4362. if (database && database.enableSceneOffline) {
  4363. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4364. }
  4365. else {
  4366. noIndexedDB();
  4367. }
  4368. }
  4369. };
  4370. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4371. var reader = new FileReader();
  4372. reader.onload = function (e) {
  4373. //target doesn't have result from ts 1.3
  4374. callback(e.target['result']);
  4375. };
  4376. reader.onprogress = progressCallback;
  4377. reader.readAsDataURL(fileToLoad);
  4378. };
  4379. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4380. var reader = new FileReader();
  4381. reader.onerror = function (e) {
  4382. Tools.Log("Error while reading file: " + fileToLoad.name);
  4383. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4384. };
  4385. reader.onload = function (e) {
  4386. //target doesn't have result from ts 1.3
  4387. callback(e.target['result']);
  4388. };
  4389. reader.onprogress = progressCallBack;
  4390. if (!useArrayBuffer) {
  4391. // Asynchronous read
  4392. reader.readAsText(fileToLoad);
  4393. }
  4394. else {
  4395. reader.readAsArrayBuffer(fileToLoad);
  4396. }
  4397. };
  4398. // Misc.
  4399. Tools.Clamp = function (value, min, max) {
  4400. if (min === void 0) { min = 0; }
  4401. if (max === void 0) { max = 1; }
  4402. return Math.min(max, Math.max(min, value));
  4403. };
  4404. // Returns -1 when value is a negative number and
  4405. // +1 when value is a positive number.
  4406. Tools.Sign = function (value) {
  4407. value = +value; // convert to a number
  4408. if (value === 0 || isNaN(value))
  4409. return value;
  4410. return value > 0 ? 1 : -1;
  4411. };
  4412. Tools.Format = function (value, decimals) {
  4413. if (decimals === void 0) { decimals = 2; }
  4414. return value.toFixed(decimals);
  4415. };
  4416. Tools.CheckExtends = function (v, min, max) {
  4417. if (v.x < min.x)
  4418. min.x = v.x;
  4419. if (v.y < min.y)
  4420. min.y = v.y;
  4421. if (v.z < min.z)
  4422. min.z = v.z;
  4423. if (v.x > max.x)
  4424. max.x = v.x;
  4425. if (v.y > max.y)
  4426. max.y = v.y;
  4427. if (v.z > max.z)
  4428. max.z = v.z;
  4429. };
  4430. Tools.WithinEpsilon = function (a, b, epsilon) {
  4431. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4432. var num = a - b;
  4433. return -epsilon <= num && num <= epsilon;
  4434. };
  4435. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4436. for (var prop in source) {
  4437. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4438. continue;
  4439. }
  4440. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4441. continue;
  4442. }
  4443. var sourceValue = source[prop];
  4444. var typeOfSourceValue = typeof sourceValue;
  4445. if (typeOfSourceValue === "function") {
  4446. continue;
  4447. }
  4448. if (typeOfSourceValue === "object") {
  4449. if (sourceValue instanceof Array) {
  4450. destination[prop] = [];
  4451. if (sourceValue.length > 0) {
  4452. if (typeof sourceValue[0] == "object") {
  4453. for (var index = 0; index < sourceValue.length; index++) {
  4454. var clonedValue = cloneValue(sourceValue[index], destination);
  4455. if (destination[prop].indexOf(clonedValue) === -1) {
  4456. destination[prop].push(clonedValue);
  4457. }
  4458. }
  4459. }
  4460. else {
  4461. destination[prop] = sourceValue.slice(0);
  4462. }
  4463. }
  4464. }
  4465. else {
  4466. destination[prop] = cloneValue(sourceValue, destination);
  4467. }
  4468. }
  4469. else {
  4470. destination[prop] = sourceValue;
  4471. }
  4472. }
  4473. };
  4474. Tools.IsEmpty = function (obj) {
  4475. for (var i in obj) {
  4476. return false;
  4477. }
  4478. return true;
  4479. };
  4480. Tools.RegisterTopRootEvents = function (events) {
  4481. for (var index = 0; index < events.length; index++) {
  4482. var event = events[index];
  4483. window.addEventListener(event.name, event.handler, false);
  4484. try {
  4485. if (window.parent) {
  4486. window.parent.addEventListener(event.name, event.handler, false);
  4487. }
  4488. }
  4489. catch (e) {
  4490. }
  4491. }
  4492. };
  4493. Tools.UnregisterTopRootEvents = function (events) {
  4494. for (var index = 0; index < events.length; index++) {
  4495. var event = events[index];
  4496. window.removeEventListener(event.name, event.handler);
  4497. try {
  4498. if (window.parent) {
  4499. window.parent.removeEventListener(event.name, event.handler);
  4500. }
  4501. }
  4502. catch (e) {
  4503. }
  4504. }
  4505. };
  4506. Tools.DumpFramebuffer = function (width, height, engine) {
  4507. // Read the contents of the framebuffer
  4508. var numberOfChannelsByLine = width * 4;
  4509. var halfHeight = height / 2;
  4510. //Reading datas from WebGL
  4511. var data = engine.readPixels(0, 0, width, height);
  4512. //To flip image on Y axis.
  4513. for (var i = 0; i < halfHeight; i++) {
  4514. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4515. var currentCell = j + i * numberOfChannelsByLine;
  4516. var targetLine = height - i - 1;
  4517. var targetCell = j + targetLine * numberOfChannelsByLine;
  4518. var temp = data[currentCell];
  4519. data[currentCell] = data[targetCell];
  4520. data[targetCell] = temp;
  4521. }
  4522. }
  4523. // Create a 2D canvas to store the result
  4524. if (!screenshotCanvas) {
  4525. screenshotCanvas = document.createElement('canvas');
  4526. }
  4527. screenshotCanvas.width = width;
  4528. screenshotCanvas.height = height;
  4529. var context = screenshotCanvas.getContext('2d');
  4530. // Copy the pixels to a 2D canvas
  4531. var imageData = context.createImageData(width, height);
  4532. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4533. var castData = imageData.data;
  4534. castData.set(data);
  4535. context.putImageData(imageData, 0, 0);
  4536. var base64Image = screenshotCanvas.toDataURL();
  4537. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4538. if (("download" in document.createElement("a"))) {
  4539. var a = window.document.createElement("a");
  4540. a.href = base64Image;
  4541. var date = new Date();
  4542. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4543. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4544. window.document.body.appendChild(a);
  4545. a.addEventListener("click", function () {
  4546. a.parentElement.removeChild(a);
  4547. });
  4548. a.click();
  4549. }
  4550. else {
  4551. var newWindow = window.open("");
  4552. var img = newWindow.document.createElement("img");
  4553. img.src = base64Image;
  4554. newWindow.document.body.appendChild(img);
  4555. }
  4556. };
  4557. Tools.CreateScreenshot = function (engine, camera, size) {
  4558. var width;
  4559. var height;
  4560. var scene = camera.getScene();
  4561. var previousCamera = null;
  4562. if (scene.activeCamera !== camera) {
  4563. previousCamera = scene.activeCamera;
  4564. scene.activeCamera = camera;
  4565. }
  4566. //If a precision value is specified
  4567. if (size.precision) {
  4568. width = Math.round(engine.getRenderWidth() * size.precision);
  4569. height = Math.round(width / engine.getAspectRatio(camera));
  4570. size = { width: width, height: height };
  4571. }
  4572. else if (size.width && size.height) {
  4573. width = size.width;
  4574. height = size.height;
  4575. }
  4576. else if (size.width && !size.height) {
  4577. width = size.width;
  4578. height = Math.round(width / engine.getAspectRatio(camera));
  4579. size = { width: width, height: height };
  4580. }
  4581. else if (size.height && !size.width) {
  4582. height = size.height;
  4583. width = Math.round(height * engine.getAspectRatio(camera));
  4584. size = { width: width, height: height };
  4585. }
  4586. else if (!isNaN(size)) {
  4587. height = size;
  4588. width = size;
  4589. }
  4590. else {
  4591. Tools.Error("Invalid 'size' parameter !");
  4592. return;
  4593. }
  4594. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4595. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4596. texture.renderList = scene.meshes;
  4597. texture.onAfterRender = function () {
  4598. Tools.DumpFramebuffer(width, height, engine);
  4599. };
  4600. scene.incrementRenderId();
  4601. texture.render(true);
  4602. texture.dispose();
  4603. if (previousCamera) {
  4604. scene.activeCamera = previousCamera;
  4605. }
  4606. };
  4607. // XHR response validator for local file scenario
  4608. Tools.ValidateXHRData = function (xhr, dataType) {
  4609. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4610. if (dataType === void 0) { dataType = 7; }
  4611. try {
  4612. if (dataType & 1) {
  4613. if (xhr.responseText && xhr.responseText.length > 0) {
  4614. return true;
  4615. }
  4616. else if (dataType === 1) {
  4617. return false;
  4618. }
  4619. }
  4620. if (dataType & 2) {
  4621. // Check header width and height since there is no "TGA" magic number
  4622. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4623. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4624. return true;
  4625. }
  4626. else if (dataType === 2) {
  4627. return false;
  4628. }
  4629. }
  4630. if (dataType & 4) {
  4631. // Check for the "DDS" magic number
  4632. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4633. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4634. return true;
  4635. }
  4636. else {
  4637. return false;
  4638. }
  4639. }
  4640. }
  4641. catch (e) {
  4642. }
  4643. return false;
  4644. };
  4645. Object.defineProperty(Tools, "NoneLogLevel", {
  4646. get: function () {
  4647. return Tools._NoneLogLevel;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Object.defineProperty(Tools, "MessageLogLevel", {
  4653. get: function () {
  4654. return Tools._MessageLogLevel;
  4655. },
  4656. enumerable: true,
  4657. configurable: true
  4658. });
  4659. Object.defineProperty(Tools, "WarningLogLevel", {
  4660. get: function () {
  4661. return Tools._WarningLogLevel;
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(Tools, "ErrorLogLevel", {
  4667. get: function () {
  4668. return Tools._ErrorLogLevel;
  4669. },
  4670. enumerable: true,
  4671. configurable: true
  4672. });
  4673. Object.defineProperty(Tools, "AllLogLevel", {
  4674. get: function () {
  4675. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Tools._AddLogEntry = function (entry) {
  4681. Tools._LogCache = entry + Tools._LogCache;
  4682. if (Tools.OnNewCacheEntry) {
  4683. Tools.OnNewCacheEntry(entry);
  4684. }
  4685. };
  4686. Tools._FormatMessage = function (message) {
  4687. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4688. var date = new Date();
  4689. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4690. };
  4691. Tools._LogDisabled = function (message) {
  4692. // nothing to do
  4693. };
  4694. Tools._LogEnabled = function (message) {
  4695. var formattedMessage = Tools._FormatMessage(message);
  4696. console.log("BJS - " + formattedMessage);
  4697. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4698. Tools._AddLogEntry(entry);
  4699. };
  4700. Tools._WarnDisabled = function (message) {
  4701. // nothing to do
  4702. };
  4703. Tools._WarnEnabled = function (message) {
  4704. var formattedMessage = Tools._FormatMessage(message);
  4705. console.warn("BJS - " + formattedMessage);
  4706. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4707. Tools._AddLogEntry(entry);
  4708. };
  4709. Tools._ErrorDisabled = function (message) {
  4710. // nothing to do
  4711. };
  4712. Tools._ErrorEnabled = function (message) {
  4713. var formattedMessage = Tools._FormatMessage(message);
  4714. console.error("BJS - " + formattedMessage);
  4715. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4716. Tools._AddLogEntry(entry);
  4717. };
  4718. Object.defineProperty(Tools, "LogCache", {
  4719. get: function () {
  4720. return Tools._LogCache;
  4721. },
  4722. enumerable: true,
  4723. configurable: true
  4724. });
  4725. Object.defineProperty(Tools, "LogLevels", {
  4726. set: function (level) {
  4727. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4728. Tools.Log = Tools._LogEnabled;
  4729. }
  4730. else {
  4731. Tools.Log = Tools._LogDisabled;
  4732. }
  4733. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4734. Tools.Warn = Tools._WarnEnabled;
  4735. }
  4736. else {
  4737. Tools.Warn = Tools._WarnDisabled;
  4738. }
  4739. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4740. Tools.Error = Tools._ErrorEnabled;
  4741. }
  4742. else {
  4743. Tools.Error = Tools._ErrorDisabled;
  4744. }
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4750. get: function () {
  4751. return Tools._PerformanceNoneLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4757. get: function () {
  4758. return Tools._PerformanceUserMarkLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4764. get: function () {
  4765. return Tools._PerformanceConsoleLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4771. set: function (level) {
  4772. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4773. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4774. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4775. return;
  4776. }
  4777. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4778. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4779. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4780. return;
  4781. }
  4782. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4783. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4784. },
  4785. enumerable: true,
  4786. configurable: true
  4787. });
  4788. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4789. };
  4790. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4791. };
  4792. Tools._StartUserMark = function (counterName, condition) {
  4793. if (condition === void 0) { condition = true; }
  4794. if (!condition || !Tools._performance.mark) {
  4795. return;
  4796. }
  4797. Tools._performance.mark(counterName + "-Begin");
  4798. };
  4799. Tools._EndUserMark = function (counterName, condition) {
  4800. if (condition === void 0) { condition = true; }
  4801. if (!condition || !Tools._performance.mark) {
  4802. return;
  4803. }
  4804. Tools._performance.mark(counterName + "-End");
  4805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4806. };
  4807. Tools._StartPerformanceConsole = function (counterName, condition) {
  4808. if (condition === void 0) { condition = true; }
  4809. if (!condition) {
  4810. return;
  4811. }
  4812. Tools._StartUserMark(counterName, condition);
  4813. if (console.time) {
  4814. console.time(counterName);
  4815. }
  4816. };
  4817. Tools._EndPerformanceConsole = function (counterName, condition) {
  4818. if (condition === void 0) { condition = true; }
  4819. if (!condition) {
  4820. return;
  4821. }
  4822. Tools._EndUserMark(counterName, condition);
  4823. if (console.time) {
  4824. console.timeEnd(counterName);
  4825. }
  4826. };
  4827. Object.defineProperty(Tools, "Now", {
  4828. get: function () {
  4829. if (window.performance && window.performance.now) {
  4830. return window.performance.now();
  4831. }
  4832. return new Date().getTime();
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. // Deprecated
  4838. Tools.GetFps = function () {
  4839. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4840. return 0;
  4841. };
  4842. Tools.BaseUrl = "";
  4843. // Logs
  4844. Tools._NoneLogLevel = 0;
  4845. Tools._MessageLogLevel = 1;
  4846. Tools._WarningLogLevel = 2;
  4847. Tools._ErrorLogLevel = 4;
  4848. Tools._LogCache = "";
  4849. Tools.Log = Tools._LogEnabled;
  4850. Tools.Warn = Tools._WarnEnabled;
  4851. Tools.Error = Tools._ErrorEnabled;
  4852. // Performances
  4853. Tools._PerformanceNoneLogLevel = 0;
  4854. Tools._PerformanceUserMarkLogLevel = 1;
  4855. Tools._PerformanceConsoleLogLevel = 2;
  4856. Tools._performance = window.performance;
  4857. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4858. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4859. return Tools;
  4860. })();
  4861. BABYLON.Tools = Tools;
  4862. /**
  4863. * An implementation of a loop for asynchronous functions.
  4864. */
  4865. var AsyncLoop = (function () {
  4866. /**
  4867. * Constroctor.
  4868. * @param iterations the number of iterations.
  4869. * @param _fn the function to run each iteration
  4870. * @param _successCallback the callback that will be called upon succesful execution
  4871. * @param offset starting offset.
  4872. */
  4873. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4874. if (offset === void 0) { offset = 0; }
  4875. this.iterations = iterations;
  4876. this._fn = _fn;
  4877. this._successCallback = _successCallback;
  4878. this.index = offset - 1;
  4879. this._done = false;
  4880. }
  4881. /**
  4882. * Execute the next iteration. Must be called after the last iteration was finished.
  4883. */
  4884. AsyncLoop.prototype.executeNext = function () {
  4885. if (!this._done) {
  4886. if (this.index + 1 < this.iterations) {
  4887. ++this.index;
  4888. this._fn(this);
  4889. }
  4890. else {
  4891. this.breakLoop();
  4892. }
  4893. }
  4894. };
  4895. /**
  4896. * Break the loop and run the success callback.
  4897. */
  4898. AsyncLoop.prototype.breakLoop = function () {
  4899. this._done = true;
  4900. this._successCallback();
  4901. };
  4902. /**
  4903. * Helper function
  4904. */
  4905. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4906. if (offset === void 0) { offset = 0; }
  4907. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4908. loop.executeNext();
  4909. return loop;
  4910. };
  4911. /**
  4912. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4913. * @param iterations total number of iterations
  4914. * @param syncedIterations number of synchronous iterations in each async iteration.
  4915. * @param fn the function to call each iteration.
  4916. * @param callback a success call back that will be called when iterating stops.
  4917. * @param breakFunction a break condition (optional)
  4918. * @param timeout timeout settings for the setTimeout function. default - 0.
  4919. * @constructor
  4920. */
  4921. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4922. if (timeout === void 0) { timeout = 0; }
  4923. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4924. if (breakFunction && breakFunction())
  4925. loop.breakLoop();
  4926. else {
  4927. setTimeout(function () {
  4928. for (var i = 0; i < syncedIterations; ++i) {
  4929. var iteration = (loop.index * syncedIterations) + i;
  4930. if (iteration >= iterations)
  4931. break;
  4932. fn(iteration);
  4933. if (breakFunction && breakFunction()) {
  4934. loop.breakLoop();
  4935. break;
  4936. }
  4937. }
  4938. loop.executeNext();
  4939. }, timeout);
  4940. }
  4941. }, callback);
  4942. };
  4943. return AsyncLoop;
  4944. })();
  4945. BABYLON.AsyncLoop = AsyncLoop;
  4946. })(BABYLON || (BABYLON = {}));
  4947. //# sourceMappingURL=babylon.tools.js.map
  4948. var BABYLON;
  4949. (function (BABYLON) {
  4950. var _DepthCullingState = (function () {
  4951. function _DepthCullingState() {
  4952. this._isDepthTestDirty = false;
  4953. this._isDepthMaskDirty = false;
  4954. this._isDepthFuncDirty = false;
  4955. this._isCullFaceDirty = false;
  4956. this._isCullDirty = false;
  4957. this._isZOffsetDirty = false;
  4958. }
  4959. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4960. get: function () {
  4961. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4967. get: function () {
  4968. return this._zOffset;
  4969. },
  4970. set: function (value) {
  4971. if (this._zOffset === value) {
  4972. return;
  4973. }
  4974. this._zOffset = value;
  4975. this._isZOffsetDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4981. get: function () {
  4982. return this._cullFace;
  4983. },
  4984. set: function (value) {
  4985. if (this._cullFace === value) {
  4986. return;
  4987. }
  4988. this._cullFace = value;
  4989. this._isCullFaceDirty = true;
  4990. },
  4991. enumerable: true,
  4992. configurable: true
  4993. });
  4994. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4995. get: function () {
  4996. return this._cull;
  4997. },
  4998. set: function (value) {
  4999. if (this._cull === value) {
  5000. return;
  5001. }
  5002. this._cull = value;
  5003. this._isCullDirty = true;
  5004. },
  5005. enumerable: true,
  5006. configurable: true
  5007. });
  5008. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5009. get: function () {
  5010. return this._depthFunc;
  5011. },
  5012. set: function (value) {
  5013. if (this._depthFunc === value) {
  5014. return;
  5015. }
  5016. this._depthFunc = value;
  5017. this._isDepthFuncDirty = true;
  5018. },
  5019. enumerable: true,
  5020. configurable: true
  5021. });
  5022. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5023. get: function () {
  5024. return this._depthMask;
  5025. },
  5026. set: function (value) {
  5027. if (this._depthMask === value) {
  5028. return;
  5029. }
  5030. this._depthMask = value;
  5031. this._isDepthMaskDirty = true;
  5032. },
  5033. enumerable: true,
  5034. configurable: true
  5035. });
  5036. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5037. get: function () {
  5038. return this._depthTest;
  5039. },
  5040. set: function (value) {
  5041. if (this._depthTest === value) {
  5042. return;
  5043. }
  5044. this._depthTest = value;
  5045. this._isDepthTestDirty = true;
  5046. },
  5047. enumerable: true,
  5048. configurable: true
  5049. });
  5050. _DepthCullingState.prototype.reset = function () {
  5051. this._depthMask = true;
  5052. this._depthTest = true;
  5053. this._depthFunc = null;
  5054. this._cull = null;
  5055. this._cullFace = null;
  5056. this._zOffset = 0;
  5057. this._isDepthTestDirty = true;
  5058. this._isDepthMaskDirty = true;
  5059. this._isDepthFuncDirty = false;
  5060. this._isCullFaceDirty = false;
  5061. this._isCullDirty = false;
  5062. this._isZOffsetDirty = false;
  5063. };
  5064. _DepthCullingState.prototype.apply = function (gl) {
  5065. if (!this.isDirty) {
  5066. return;
  5067. }
  5068. // Cull
  5069. if (this._isCullDirty) {
  5070. if (this.cull) {
  5071. gl.enable(gl.CULL_FACE);
  5072. }
  5073. else {
  5074. gl.disable(gl.CULL_FACE);
  5075. }
  5076. this._isCullDirty = false;
  5077. }
  5078. // Cull face
  5079. if (this._isCullFaceDirty) {
  5080. gl.cullFace(this.cullFace);
  5081. this._isCullFaceDirty = false;
  5082. }
  5083. // Depth mask
  5084. if (this._isDepthMaskDirty) {
  5085. gl.depthMask(this.depthMask);
  5086. this._isDepthMaskDirty = false;
  5087. }
  5088. // Depth test
  5089. if (this._isDepthTestDirty) {
  5090. if (this.depthTest) {
  5091. gl.enable(gl.DEPTH_TEST);
  5092. }
  5093. else {
  5094. gl.disable(gl.DEPTH_TEST);
  5095. }
  5096. this._isDepthTestDirty = false;
  5097. }
  5098. // Depth func
  5099. if (this._isDepthFuncDirty) {
  5100. gl.depthFunc(this.depthFunc);
  5101. this._isDepthFuncDirty = false;
  5102. }
  5103. // zOffset
  5104. if (this._isZOffsetDirty) {
  5105. if (this.zOffset) {
  5106. gl.enable(gl.POLYGON_OFFSET_FILL);
  5107. gl.polygonOffset(this.zOffset, 0);
  5108. }
  5109. else {
  5110. gl.disable(gl.POLYGON_OFFSET_FILL);
  5111. }
  5112. this._isZOffsetDirty = false;
  5113. }
  5114. };
  5115. return _DepthCullingState;
  5116. })();
  5117. BABYLON._DepthCullingState = _DepthCullingState;
  5118. var _AlphaState = (function () {
  5119. function _AlphaState() {
  5120. this._isAlphaBlendDirty = false;
  5121. this._isBlendFunctionParametersDirty = false;
  5122. this._alphaBlend = false;
  5123. this._blendFunctionParameters = new Array(4);
  5124. }
  5125. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5126. get: function () {
  5127. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5133. get: function () {
  5134. return this._alphaBlend;
  5135. },
  5136. set: function (value) {
  5137. if (this._alphaBlend === value) {
  5138. return;
  5139. }
  5140. this._alphaBlend = value;
  5141. this._isAlphaBlendDirty = true;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5147. if (this._blendFunctionParameters[0] === value0 &&
  5148. this._blendFunctionParameters[1] === value1 &&
  5149. this._blendFunctionParameters[2] === value2 &&
  5150. this._blendFunctionParameters[3] === value3) {
  5151. return;
  5152. }
  5153. this._blendFunctionParameters[0] = value0;
  5154. this._blendFunctionParameters[1] = value1;
  5155. this._blendFunctionParameters[2] = value2;
  5156. this._blendFunctionParameters[3] = value3;
  5157. this._isBlendFunctionParametersDirty = true;
  5158. };
  5159. _AlphaState.prototype.reset = function () {
  5160. this._alphaBlend = false;
  5161. this._blendFunctionParameters[0] = null;
  5162. this._blendFunctionParameters[1] = null;
  5163. this._blendFunctionParameters[2] = null;
  5164. this._blendFunctionParameters[3] = null;
  5165. this._isAlphaBlendDirty = true;
  5166. this._isBlendFunctionParametersDirty = false;
  5167. };
  5168. _AlphaState.prototype.apply = function (gl) {
  5169. if (!this.isDirty) {
  5170. return;
  5171. }
  5172. // Alpha blend
  5173. if (this._isAlphaBlendDirty) {
  5174. if (this._alphaBlend) {
  5175. gl.enable(gl.BLEND);
  5176. }
  5177. else {
  5178. gl.disable(gl.BLEND);
  5179. }
  5180. this._isAlphaBlendDirty = false;
  5181. }
  5182. // Alpha function
  5183. if (this._isBlendFunctionParametersDirty) {
  5184. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5185. this._isBlendFunctionParametersDirty = false;
  5186. }
  5187. };
  5188. return _AlphaState;
  5189. })();
  5190. BABYLON._AlphaState = _AlphaState;
  5191. var compileShader = function (gl, source, type, defines) {
  5192. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5193. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5194. gl.compileShader(shader);
  5195. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5196. throw new Error(gl.getShaderInfoLog(shader));
  5197. }
  5198. return shader;
  5199. };
  5200. var getWebGLTextureType = function (gl, type) {
  5201. var textureType = gl.UNSIGNED_BYTE;
  5202. if (type === Engine.TEXTURETYPE_FLOAT)
  5203. textureType = gl.FLOAT;
  5204. return textureType;
  5205. };
  5206. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5207. var magFilter = gl.NEAREST;
  5208. var minFilter = gl.NEAREST;
  5209. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5210. magFilter = gl.LINEAR;
  5211. if (generateMipMaps) {
  5212. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5213. }
  5214. else {
  5215. minFilter = gl.LINEAR;
  5216. }
  5217. }
  5218. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5219. magFilter = gl.LINEAR;
  5220. if (generateMipMaps) {
  5221. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5222. }
  5223. else {
  5224. minFilter = gl.LINEAR;
  5225. }
  5226. }
  5227. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5228. magFilter = gl.NEAREST;
  5229. if (generateMipMaps) {
  5230. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5231. }
  5232. else {
  5233. minFilter = gl.NEAREST;
  5234. }
  5235. }
  5236. return {
  5237. min: minFilter,
  5238. mag: magFilter
  5239. };
  5240. };
  5241. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5243. var engine = scene.getEngine();
  5244. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5245. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5246. gl.bindTexture(gl.TEXTURE_2D, texture);
  5247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5248. texture._baseWidth = width;
  5249. texture._baseHeight = height;
  5250. texture._width = potWidth;
  5251. texture._height = potHeight;
  5252. texture.isReady = true;
  5253. processFunction(potWidth, potHeight);
  5254. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5257. if (!noMipmap && !isCompressed) {
  5258. gl.generateMipmap(gl.TEXTURE_2D);
  5259. }
  5260. gl.bindTexture(gl.TEXTURE_2D, null);
  5261. engine._activeTexturesCache = [];
  5262. scene._removePendingData(texture);
  5263. };
  5264. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5265. var onload = function () {
  5266. loadedImages[index] = img;
  5267. loadedImages._internalCount++;
  5268. scene._removePendingData(img);
  5269. if (loadedImages._internalCount === 6) {
  5270. onfinish(loadedImages);
  5271. }
  5272. };
  5273. var onerror = function () {
  5274. scene._removePendingData(img);
  5275. };
  5276. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5277. scene._addPendingData(img);
  5278. };
  5279. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5280. var loadedImages = [];
  5281. loadedImages._internalCount = 0;
  5282. for (var index = 0; index < 6; index++) {
  5283. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5284. }
  5285. };
  5286. var EngineCapabilities = (function () {
  5287. function EngineCapabilities() {
  5288. }
  5289. return EngineCapabilities;
  5290. })();
  5291. BABYLON.EngineCapabilities = EngineCapabilities;
  5292. /**
  5293. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5294. */
  5295. var Engine = (function () {
  5296. /**
  5297. * @constructor
  5298. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5299. * @param {boolean} [antialias] - enable antialias
  5300. * @param options - further options to be sent to the getContext function
  5301. */
  5302. function Engine(canvas, antialias, options) {
  5303. var _this = this;
  5304. // Public members
  5305. this.isFullscreen = false;
  5306. this.isPointerLock = false;
  5307. this.cullBackFaces = true;
  5308. this.renderEvenInBackground = true;
  5309. this.scenes = new Array();
  5310. this._windowIsBackground = false;
  5311. this._loadingDivBackgroundColor = "black";
  5312. this._drawCalls = 0;
  5313. this._renderingQueueLaunched = false;
  5314. this._activeRenderLoops = [];
  5315. // FPS
  5316. this.fpsRange = 60;
  5317. this.previousFramesDuration = [];
  5318. this.fps = 60;
  5319. this.deltaTime = 0;
  5320. // States
  5321. this._depthCullingState = new _DepthCullingState();
  5322. this._alphaState = new _AlphaState();
  5323. this._alphaMode = Engine.ALPHA_DISABLE;
  5324. // Cache
  5325. this._loadedTexturesCache = new Array();
  5326. this._activeTexturesCache = new Array();
  5327. this._compiledEffects = {};
  5328. this._uintIndicesCurrentlySet = false;
  5329. this._renderingCanvas = canvas;
  5330. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5331. options = options || {};
  5332. options.antialias = antialias;
  5333. // GL
  5334. try {
  5335. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5336. }
  5337. catch (e) {
  5338. throw new Error("WebGL not supported");
  5339. }
  5340. if (!this._gl) {
  5341. throw new Error("WebGL not supported");
  5342. }
  5343. this._onBlur = function () {
  5344. _this._windowIsBackground = true;
  5345. };
  5346. this._onFocus = function () {
  5347. _this._windowIsBackground = false;
  5348. };
  5349. window.addEventListener("blur", this._onBlur);
  5350. window.addEventListener("focus", this._onFocus);
  5351. // Viewport
  5352. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5353. this.resize();
  5354. // Caps
  5355. this._caps = new EngineCapabilities();
  5356. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5357. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5358. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5359. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5360. // Infos
  5361. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5362. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5363. if (rendererInfo != null) {
  5364. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5365. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5366. }
  5367. if (!this._glVendor) {
  5368. this._glVendor = "Unknown vendor";
  5369. }
  5370. if (!this._glRenderer) {
  5371. this._glRenderer = "Unknown renderer";
  5372. }
  5373. // Extensions
  5374. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5375. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5376. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5377. 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');
  5378. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5379. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5380. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5381. this._caps.highPrecisionShaderSupported = true;
  5382. if (this._gl.getShaderPrecisionFormat) {
  5383. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5384. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5385. }
  5386. // Depth buffer
  5387. this.setDepthBuffer(true);
  5388. this.setDepthFunctionToLessOrEqual();
  5389. this.setDepthWrite(true);
  5390. // Fullscreen
  5391. this._onFullscreenChange = function () {
  5392. if (document.fullscreen !== undefined) {
  5393. _this.isFullscreen = document.fullscreen;
  5394. }
  5395. else if (document.mozFullScreen !== undefined) {
  5396. _this.isFullscreen = document.mozFullScreen;
  5397. }
  5398. else if (document.webkitIsFullScreen !== undefined) {
  5399. _this.isFullscreen = document.webkitIsFullScreen;
  5400. }
  5401. else if (document.msIsFullScreen !== undefined) {
  5402. _this.isFullscreen = document.msIsFullScreen;
  5403. }
  5404. // Pointer lock
  5405. if (_this.isFullscreen && _this._pointerLockRequested) {
  5406. canvas.requestPointerLock = canvas.requestPointerLock ||
  5407. canvas.msRequestPointerLock ||
  5408. canvas.mozRequestPointerLock ||
  5409. canvas.webkitRequestPointerLock;
  5410. if (canvas.requestPointerLock) {
  5411. canvas.requestPointerLock();
  5412. }
  5413. }
  5414. };
  5415. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5416. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5417. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5418. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5419. // Pointer lock
  5420. this._onPointerLockChange = function () {
  5421. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5422. document.webkitPointerLockElement === canvas ||
  5423. document.msPointerLockElement === canvas ||
  5424. document.pointerLockElement === canvas);
  5425. };
  5426. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5427. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5428. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5429. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5430. if (!Engine.audioEngine) {
  5431. Engine.audioEngine = new BABYLON.AudioEngine();
  5432. }
  5433. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5434. }
  5435. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5436. get: function () {
  5437. return Engine._ALPHA_DISABLE;
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Object.defineProperty(Engine, "ALPHA_ADD", {
  5443. get: function () {
  5444. return Engine._ALPHA_ADD;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5450. get: function () {
  5451. return Engine._ALPHA_COMBINE;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5457. get: function () {
  5458. return Engine._DELAYLOADSTATE_NONE;
  5459. },
  5460. enumerable: true,
  5461. configurable: true
  5462. });
  5463. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5464. get: function () {
  5465. return Engine._DELAYLOADSTATE_LOADED;
  5466. },
  5467. enumerable: true,
  5468. configurable: true
  5469. });
  5470. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5471. get: function () {
  5472. return Engine._DELAYLOADSTATE_LOADING;
  5473. },
  5474. enumerable: true,
  5475. configurable: true
  5476. });
  5477. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5478. get: function () {
  5479. return Engine._DELAYLOADSTATE_NOTLOADED;
  5480. },
  5481. enumerable: true,
  5482. configurable: true
  5483. });
  5484. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5485. get: function () {
  5486. return Engine._TEXTUREFORMAT_ALPHA;
  5487. },
  5488. enumerable: true,
  5489. configurable: true
  5490. });
  5491. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5492. get: function () {
  5493. return Engine._TEXTUREFORMAT_LUMINANCE;
  5494. },
  5495. enumerable: true,
  5496. configurable: true
  5497. });
  5498. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5499. get: function () {
  5500. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5501. },
  5502. enumerable: true,
  5503. configurable: true
  5504. });
  5505. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5506. get: function () {
  5507. return Engine._TEXTUREFORMAT_RGB;
  5508. },
  5509. enumerable: true,
  5510. configurable: true
  5511. });
  5512. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5513. get: function () {
  5514. return Engine._TEXTUREFORMAT_RGBA;
  5515. },
  5516. enumerable: true,
  5517. configurable: true
  5518. });
  5519. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5520. get: function () {
  5521. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5522. },
  5523. enumerable: true,
  5524. configurable: true
  5525. });
  5526. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5527. get: function () {
  5528. return Engine._TEXTURETYPE_FLOAT;
  5529. },
  5530. enumerable: true,
  5531. configurable: true
  5532. });
  5533. Object.defineProperty(Engine, "Version", {
  5534. get: function () {
  5535. return "2.1.0 beta";
  5536. },
  5537. enumerable: true,
  5538. configurable: true
  5539. });
  5540. Engine.prototype._prepareWorkingCanvas = function () {
  5541. if (this._workingCanvas) {
  5542. return;
  5543. }
  5544. this._workingCanvas = document.createElement("canvas");
  5545. this._workingContext = this._workingCanvas.getContext("2d");
  5546. };
  5547. Engine.prototype.getGlInfo = function () {
  5548. return {
  5549. vendor: this._glVendor,
  5550. renderer: this._glRenderer,
  5551. version: this._glVersion
  5552. };
  5553. };
  5554. Engine.prototype.getAspectRatio = function (camera) {
  5555. var viewport = camera.viewport;
  5556. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5557. };
  5558. Engine.prototype.getRenderWidth = function () {
  5559. if (this._currentRenderTarget) {
  5560. return this._currentRenderTarget._width;
  5561. }
  5562. return this._renderingCanvas.width;
  5563. };
  5564. Engine.prototype.getRenderHeight = function () {
  5565. if (this._currentRenderTarget) {
  5566. return this._currentRenderTarget._height;
  5567. }
  5568. return this._renderingCanvas.height;
  5569. };
  5570. Engine.prototype.getRenderingCanvas = function () {
  5571. return this._renderingCanvas;
  5572. };
  5573. Engine.prototype.getRenderingCanvasClientRect = function () {
  5574. return this._renderingCanvas.getBoundingClientRect();
  5575. };
  5576. Engine.prototype.setHardwareScalingLevel = function (level) {
  5577. this._hardwareScalingLevel = level;
  5578. this.resize();
  5579. };
  5580. Engine.prototype.getHardwareScalingLevel = function () {
  5581. return this._hardwareScalingLevel;
  5582. };
  5583. Engine.prototype.getLoadedTexturesCache = function () {
  5584. return this._loadedTexturesCache;
  5585. };
  5586. Engine.prototype.getCaps = function () {
  5587. return this._caps;
  5588. };
  5589. Object.defineProperty(Engine.prototype, "drawCalls", {
  5590. get: function () {
  5591. return this._drawCalls;
  5592. },
  5593. enumerable: true,
  5594. configurable: true
  5595. });
  5596. // Methods
  5597. Engine.prototype.resetDrawCalls = function () {
  5598. this._drawCalls = 0;
  5599. };
  5600. Engine.prototype.setDepthFunctionToGreater = function () {
  5601. this._depthCullingState.depthFunc = this._gl.GREATER;
  5602. };
  5603. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5604. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5605. };
  5606. Engine.prototype.setDepthFunctionToLess = function () {
  5607. this._depthCullingState.depthFunc = this._gl.LESS;
  5608. };
  5609. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5610. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5611. };
  5612. /**
  5613. * stop executing a render loop function and remove it from the execution array
  5614. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5615. */
  5616. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5617. if (!renderFunction) {
  5618. this._activeRenderLoops = [];
  5619. return;
  5620. }
  5621. var index = this._activeRenderLoops.indexOf(renderFunction);
  5622. if (index >= 0) {
  5623. this._activeRenderLoops.splice(index, 1);
  5624. }
  5625. };
  5626. Engine.prototype._renderLoop = function () {
  5627. var _this = this;
  5628. var shouldRender = true;
  5629. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5630. shouldRender = false;
  5631. }
  5632. if (shouldRender) {
  5633. // Start new frame
  5634. this.beginFrame();
  5635. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5636. var renderFunction = this._activeRenderLoops[index];
  5637. renderFunction();
  5638. }
  5639. // Present
  5640. this.endFrame();
  5641. }
  5642. if (this._activeRenderLoops.length > 0) {
  5643. // Register new frame
  5644. BABYLON.Tools.QueueNewFrame(function () {
  5645. _this._renderLoop();
  5646. });
  5647. }
  5648. else {
  5649. this._renderingQueueLaunched = false;
  5650. }
  5651. };
  5652. /**
  5653. * Register and execute a render loop. The engine can have more than one render function.
  5654. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5655. * @example
  5656. * engine.runRenderLoop(function () {
  5657. * scene.render()
  5658. * })
  5659. */
  5660. Engine.prototype.runRenderLoop = function (renderFunction) {
  5661. var _this = this;
  5662. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5663. return;
  5664. }
  5665. this._activeRenderLoops.push(renderFunction);
  5666. if (!this._renderingQueueLaunched) {
  5667. this._renderingQueueLaunched = true;
  5668. BABYLON.Tools.QueueNewFrame(function () {
  5669. _this._renderLoop();
  5670. });
  5671. }
  5672. };
  5673. /**
  5674. * Toggle full screen mode.
  5675. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5676. */
  5677. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5678. if (this.isFullscreen) {
  5679. BABYLON.Tools.ExitFullscreen();
  5680. }
  5681. else {
  5682. this._pointerLockRequested = requestPointerLock;
  5683. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5684. }
  5685. };
  5686. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5687. this.applyStates();
  5688. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5689. if (this._depthCullingState.depthMask) {
  5690. this._gl.clearDepth(1.0);
  5691. }
  5692. var mode = 0;
  5693. if (backBuffer)
  5694. mode |= this._gl.COLOR_BUFFER_BIT;
  5695. if (depthStencil && this._depthCullingState.depthMask)
  5696. mode |= this._gl.DEPTH_BUFFER_BIT;
  5697. this._gl.clear(mode);
  5698. };
  5699. /**
  5700. * Set the WebGL's viewport
  5701. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5702. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5703. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5704. */
  5705. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5706. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5707. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5708. var x = viewport.x || 0;
  5709. var y = viewport.y || 0;
  5710. this._cachedViewport = viewport;
  5711. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5712. };
  5713. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5714. this._cachedViewport = null;
  5715. this._gl.viewport(x, y, width, height);
  5716. };
  5717. Engine.prototype.beginFrame = function () {
  5718. this._measureFps();
  5719. };
  5720. Engine.prototype.endFrame = function () {
  5721. //this.flushFramebuffer();
  5722. };
  5723. /**
  5724. * resize the view according to the canvas' size.
  5725. * @example
  5726. * window.addEventListener("resize", function () {
  5727. * engine.resize();
  5728. * });
  5729. */
  5730. Engine.prototype.resize = function () {
  5731. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5732. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5733. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5734. };
  5735. /**
  5736. * force a specific size of the canvas
  5737. * @param {number} width - the new canvas' width
  5738. * @param {number} height - the new canvas' height
  5739. */
  5740. Engine.prototype.setSize = function (width, height) {
  5741. this._renderingCanvas.width = width;
  5742. this._renderingCanvas.height = height;
  5743. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5744. for (var index = 0; index < this.scenes.length; index++) {
  5745. var scene = this.scenes[index];
  5746. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5747. var cam = scene.cameras[camIndex];
  5748. cam._currentRenderId = 0;
  5749. }
  5750. }
  5751. };
  5752. Engine.prototype.bindFramebuffer = function (texture) {
  5753. this._currentRenderTarget = texture;
  5754. var gl = this._gl;
  5755. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5756. this._gl.viewport(0, 0, texture._width, texture._height);
  5757. this.wipeCaches();
  5758. };
  5759. Engine.prototype.unBindFramebuffer = function (texture) {
  5760. this._currentRenderTarget = null;
  5761. if (texture.generateMipMaps) {
  5762. var gl = this._gl;
  5763. gl.bindTexture(gl.TEXTURE_2D, texture);
  5764. gl.generateMipmap(gl.TEXTURE_2D);
  5765. gl.bindTexture(gl.TEXTURE_2D, null);
  5766. }
  5767. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5768. };
  5769. Engine.prototype.flushFramebuffer = function () {
  5770. this._gl.flush();
  5771. };
  5772. Engine.prototype.restoreDefaultFramebuffer = function () {
  5773. this._currentRenderTarget = null;
  5774. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5775. this.setViewport(this._cachedViewport);
  5776. this.wipeCaches();
  5777. };
  5778. // VBOs
  5779. Engine.prototype._resetVertexBufferBinding = function () {
  5780. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5781. this._cachedVertexBuffers = null;
  5782. };
  5783. Engine.prototype.createVertexBuffer = function (vertices) {
  5784. var vbo = this._gl.createBuffer();
  5785. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5786. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5787. this._resetVertexBufferBinding();
  5788. vbo.references = 1;
  5789. return vbo;
  5790. };
  5791. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5792. var vbo = this._gl.createBuffer();
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5794. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5795. this._resetVertexBufferBinding();
  5796. vbo.references = 1;
  5797. return vbo;
  5798. };
  5799. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5800. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5801. if (offset === undefined) {
  5802. offset = 0;
  5803. }
  5804. if (vertices instanceof Float32Array) {
  5805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5806. }
  5807. else {
  5808. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5809. }
  5810. this._resetVertexBufferBinding();
  5811. };
  5812. Engine.prototype._resetIndexBufferBinding = function () {
  5813. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5814. this._cachedIndexBuffer = null;
  5815. };
  5816. Engine.prototype.createIndexBuffer = function (indices) {
  5817. var vbo = this._gl.createBuffer();
  5818. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5819. // Check for 32 bits indices
  5820. var arrayBuffer;
  5821. var need32Bits = false;
  5822. if (this._caps.uintIndices) {
  5823. for (var index = 0; index < indices.length; index++) {
  5824. if (indices[index] > 65535) {
  5825. need32Bits = true;
  5826. break;
  5827. }
  5828. }
  5829. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5830. }
  5831. else {
  5832. arrayBuffer = new Uint16Array(indices);
  5833. }
  5834. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5835. this._resetIndexBufferBinding();
  5836. vbo.references = 1;
  5837. vbo.is32Bits = need32Bits;
  5838. return vbo;
  5839. };
  5840. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5841. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5842. this._cachedVertexBuffers = vertexBuffer;
  5843. this._cachedEffectForVertexBuffers = effect;
  5844. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5845. var offset = 0;
  5846. for (var index = 0; index < vertexDeclaration.length; index++) {
  5847. var order = effect.getAttributeLocation(index);
  5848. if (order >= 0) {
  5849. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5850. }
  5851. offset += vertexDeclaration[index] * 4;
  5852. }
  5853. }
  5854. if (this._cachedIndexBuffer !== indexBuffer) {
  5855. this._cachedIndexBuffer = indexBuffer;
  5856. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5857. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5858. }
  5859. };
  5860. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5861. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5862. this._cachedVertexBuffers = vertexBuffers;
  5863. this._cachedEffectForVertexBuffers = effect;
  5864. var attributes = effect.getAttributesNames();
  5865. for (var index = 0; index < attributes.length; index++) {
  5866. var order = effect.getAttributeLocation(index);
  5867. if (order >= 0) {
  5868. var vertexBuffer = vertexBuffers[attributes[index]];
  5869. if (!vertexBuffer) {
  5870. continue;
  5871. }
  5872. var stride = vertexBuffer.getStrideSize();
  5873. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5874. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5875. }
  5876. }
  5877. }
  5878. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5879. this._cachedIndexBuffer = indexBuffer;
  5880. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5881. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5882. }
  5883. };
  5884. Engine.prototype._releaseBuffer = function (buffer) {
  5885. buffer.references--;
  5886. if (buffer.references === 0) {
  5887. this._gl.deleteBuffer(buffer);
  5888. return true;
  5889. }
  5890. return false;
  5891. };
  5892. Engine.prototype.createInstancesBuffer = function (capacity) {
  5893. var buffer = this._gl.createBuffer();
  5894. buffer.capacity = capacity;
  5895. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5896. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5897. return buffer;
  5898. };
  5899. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5900. this._gl.deleteBuffer(buffer);
  5901. };
  5902. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5903. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5904. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5905. for (var index = 0; index < 4; index++) {
  5906. var offsetLocation = offsetLocations[index];
  5907. this._gl.enableVertexAttribArray(offsetLocation);
  5908. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5909. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5910. }
  5911. };
  5912. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5914. for (var index = 0; index < 4; index++) {
  5915. var offsetLocation = offsetLocations[index];
  5916. this._gl.disableVertexAttribArray(offsetLocation);
  5917. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5918. }
  5919. };
  5920. Engine.prototype.applyStates = function () {
  5921. this._depthCullingState.apply(this._gl);
  5922. this._alphaState.apply(this._gl);
  5923. };
  5924. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5925. // Apply states
  5926. this.applyStates();
  5927. this._drawCalls++;
  5928. // Render
  5929. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5930. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5931. if (instancesCount) {
  5932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5933. return;
  5934. }
  5935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5936. };
  5937. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5938. // Apply states
  5939. this.applyStates();
  5940. this._drawCalls++;
  5941. if (instancesCount) {
  5942. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5943. return;
  5944. }
  5945. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5946. };
  5947. // Shaders
  5948. Engine.prototype._releaseEffect = function (effect) {
  5949. if (this._compiledEffects[effect._key]) {
  5950. delete this._compiledEffects[effect._key];
  5951. if (effect.getProgram()) {
  5952. this._gl.deleteProgram(effect.getProgram());
  5953. }
  5954. }
  5955. };
  5956. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5957. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5958. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5959. var name = vertex + "+" + fragment + "@" + defines;
  5960. if (this._compiledEffects[name]) {
  5961. return this._compiledEffects[name];
  5962. }
  5963. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5964. effect._key = name;
  5965. this._compiledEffects[name] = effect;
  5966. return effect;
  5967. };
  5968. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5969. if (uniformsNames === void 0) { uniformsNames = []; }
  5970. if (samplers === void 0) { samplers = []; }
  5971. if (defines === void 0) { defines = ""; }
  5972. return this.createEffect({
  5973. vertex: "particles",
  5974. fragmentElement: fragmentName
  5975. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5976. };
  5977. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5978. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5979. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5980. var shaderProgram = this._gl.createProgram();
  5981. this._gl.attachShader(shaderProgram, vertexShader);
  5982. this._gl.attachShader(shaderProgram, fragmentShader);
  5983. this._gl.linkProgram(shaderProgram);
  5984. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5985. if (!linked) {
  5986. var error = this._gl.getProgramInfoLog(shaderProgram);
  5987. if (error) {
  5988. throw new Error(error);
  5989. }
  5990. }
  5991. this._gl.deleteShader(vertexShader);
  5992. this._gl.deleteShader(fragmentShader);
  5993. return shaderProgram;
  5994. };
  5995. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5996. var results = [];
  5997. for (var index = 0; index < uniformsNames.length; index++) {
  5998. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5999. }
  6000. return results;
  6001. };
  6002. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6003. var results = [];
  6004. for (var index = 0; index < attributesNames.length; index++) {
  6005. try {
  6006. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6007. }
  6008. catch (e) {
  6009. results.push(-1);
  6010. }
  6011. }
  6012. return results;
  6013. };
  6014. Engine.prototype.enableEffect = function (effect) {
  6015. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6016. if (effect && effect.onBind) {
  6017. effect.onBind(effect);
  6018. }
  6019. return;
  6020. }
  6021. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6022. // Use program
  6023. this._gl.useProgram(effect.getProgram());
  6024. for (var i in this._vertexAttribArrays) {
  6025. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6026. continue;
  6027. }
  6028. this._vertexAttribArrays[i] = false;
  6029. this._gl.disableVertexAttribArray(i);
  6030. }
  6031. var attributesCount = effect.getAttributesCount();
  6032. for (var index = 0; index < attributesCount; index++) {
  6033. // Attributes
  6034. var order = effect.getAttributeLocation(index);
  6035. if (order >= 0) {
  6036. this._vertexAttribArrays[order] = true;
  6037. this._gl.enableVertexAttribArray(order);
  6038. }
  6039. }
  6040. this._currentEffect = effect;
  6041. if (effect.onBind) {
  6042. effect.onBind(effect);
  6043. }
  6044. };
  6045. Engine.prototype.setArray = function (uniform, array) {
  6046. if (!uniform)
  6047. return;
  6048. this._gl.uniform1fv(uniform, array);
  6049. };
  6050. Engine.prototype.setArray2 = function (uniform, array) {
  6051. if (!uniform || array.length % 2 !== 0)
  6052. return;
  6053. this._gl.uniform2fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray3 = function (uniform, array) {
  6056. if (!uniform || array.length % 3 !== 0)
  6057. return;
  6058. this._gl.uniform3fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray4 = function (uniform, array) {
  6061. if (!uniform || array.length % 4 !== 0)
  6062. return;
  6063. this._gl.uniform4fv(uniform, array);
  6064. };
  6065. Engine.prototype.setMatrices = function (uniform, matrices) {
  6066. if (!uniform)
  6067. return;
  6068. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6069. };
  6070. Engine.prototype.setMatrix = function (uniform, matrix) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6074. };
  6075. Engine.prototype.setFloat = function (uniform, value) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniform1f(uniform, value);
  6079. };
  6080. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniform2f(uniform, x, y);
  6084. };
  6085. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniform3f(uniform, x, y, z);
  6089. };
  6090. Engine.prototype.setBool = function (uniform, bool) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform1i(uniform, bool);
  6094. };
  6095. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform4f(uniform, x, y, z, w);
  6099. };
  6100. Engine.prototype.setColor3 = function (uniform, color3) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6104. };
  6105. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6109. };
  6110. // States
  6111. Engine.prototype.setState = function (culling, zOffset, force) {
  6112. if (zOffset === void 0) { zOffset = 0; }
  6113. // Culling
  6114. if (this._depthCullingState.cull !== culling || force) {
  6115. if (culling) {
  6116. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6117. this._depthCullingState.cull = true;
  6118. }
  6119. else {
  6120. this._depthCullingState.cull = false;
  6121. }
  6122. }
  6123. // Z offset
  6124. this._depthCullingState.zOffset = zOffset;
  6125. };
  6126. Engine.prototype.setDepthBuffer = function (enable) {
  6127. this._depthCullingState.depthTest = enable;
  6128. };
  6129. Engine.prototype.getDepthWrite = function () {
  6130. return this._depthCullingState.depthMask;
  6131. };
  6132. Engine.prototype.setDepthWrite = function (enable) {
  6133. this._depthCullingState.depthMask = enable;
  6134. };
  6135. Engine.prototype.setColorWrite = function (enable) {
  6136. this._gl.colorMask(enable, enable, enable, enable);
  6137. };
  6138. Engine.prototype.setAlphaMode = function (mode) {
  6139. switch (mode) {
  6140. case Engine.ALPHA_DISABLE:
  6141. this.setDepthWrite(true);
  6142. this._alphaState.alphaBlend = false;
  6143. break;
  6144. case Engine.ALPHA_COMBINE:
  6145. this.setDepthWrite(false);
  6146. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6147. this._alphaState.alphaBlend = true;
  6148. break;
  6149. case Engine.ALPHA_ADD:
  6150. this.setDepthWrite(false);
  6151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6152. this._alphaState.alphaBlend = true;
  6153. break;
  6154. }
  6155. this._alphaMode = mode;
  6156. };
  6157. Engine.prototype.getAlphaMode = function () {
  6158. return this._alphaMode;
  6159. };
  6160. Engine.prototype.setAlphaTesting = function (enable) {
  6161. this._alphaTest = enable;
  6162. };
  6163. Engine.prototype.getAlphaTesting = function () {
  6164. return this._alphaTest;
  6165. };
  6166. // Textures
  6167. Engine.prototype.wipeCaches = function () {
  6168. this._activeTexturesCache = [];
  6169. this._currentEffect = null;
  6170. this._depthCullingState.reset();
  6171. this._alphaState.reset();
  6172. this._cachedVertexBuffers = null;
  6173. this._cachedIndexBuffer = null;
  6174. this._cachedEffectForVertexBuffers = null;
  6175. };
  6176. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6177. var gl = this._gl;
  6178. gl.bindTexture(gl.TEXTURE_2D, texture);
  6179. var magFilter = gl.NEAREST;
  6180. var minFilter = gl.NEAREST;
  6181. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6182. magFilter = gl.LINEAR;
  6183. minFilter = gl.LINEAR;
  6184. }
  6185. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6186. magFilter = gl.LINEAR;
  6187. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6188. }
  6189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6191. gl.bindTexture(gl.TEXTURE_2D, null);
  6192. texture.samplingMode = samplingMode;
  6193. };
  6194. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6195. var _this = this;
  6196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6197. if (onLoad === void 0) { onLoad = null; }
  6198. if (onError === void 0) { onError = null; }
  6199. if (buffer === void 0) { buffer = null; }
  6200. var texture = this._gl.createTexture();
  6201. var extension;
  6202. var fromData = false;
  6203. if (url.substr(0, 5) === "data:") {
  6204. fromData = true;
  6205. }
  6206. if (!fromData)
  6207. extension = url.substr(url.length - 4, 4).toLowerCase();
  6208. else {
  6209. var oldUrl = url;
  6210. fromData = oldUrl.split(':');
  6211. url = oldUrl;
  6212. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6213. }
  6214. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6215. var isTGA = (extension === ".tga");
  6216. scene._addPendingData(texture);
  6217. texture.url = url;
  6218. texture.noMipmap = noMipmap;
  6219. texture.references = 1;
  6220. texture.samplingMode = samplingMode;
  6221. this._loadedTexturesCache.push(texture);
  6222. var onerror = function () {
  6223. scene._removePendingData(texture);
  6224. if (onError) {
  6225. onError();
  6226. }
  6227. };
  6228. if (isTGA) {
  6229. var callback = function (arrayBuffer) {
  6230. var data = new Uint8Array(arrayBuffer);
  6231. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6232. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6233. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6234. if (onLoad) {
  6235. onLoad();
  6236. }
  6237. }, samplingMode);
  6238. };
  6239. if (!(fromData instanceof Array))
  6240. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6241. callback(arrayBuffer);
  6242. }, onerror, scene.database, true);
  6243. else
  6244. callback(buffer);
  6245. }
  6246. else if (isDDS) {
  6247. callback = function (data) {
  6248. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6249. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6250. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6251. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6252. if (onLoad) {
  6253. onLoad();
  6254. }
  6255. }, samplingMode);
  6256. };
  6257. if (!(fromData instanceof Array))
  6258. BABYLON.Tools.LoadFile(url, function (data) {
  6259. callback(data);
  6260. }, onerror, scene.database, true);
  6261. else
  6262. callback(buffer);
  6263. }
  6264. else {
  6265. var onload = function (img) {
  6266. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6267. var isPot = (img.width === potWidth && img.height === potHeight);
  6268. if (!isPot) {
  6269. _this._prepareWorkingCanvas();
  6270. _this._workingCanvas.width = potWidth;
  6271. _this._workingCanvas.height = potHeight;
  6272. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6273. _this._workingContext.imageSmoothingEnabled = false;
  6274. _this._workingContext.mozImageSmoothingEnabled = false;
  6275. _this._workingContext.oImageSmoothingEnabled = false;
  6276. _this._workingContext.webkitImageSmoothingEnabled = false;
  6277. _this._workingContext.msImageSmoothingEnabled = false;
  6278. }
  6279. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6280. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6281. _this._workingContext.imageSmoothingEnabled = true;
  6282. _this._workingContext.mozImageSmoothingEnabled = true;
  6283. _this._workingContext.oImageSmoothingEnabled = true;
  6284. _this._workingContext.webkitImageSmoothingEnabled = true;
  6285. _this._workingContext.msImageSmoothingEnabled = true;
  6286. }
  6287. }
  6288. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6289. if (onLoad) {
  6290. onLoad();
  6291. }
  6292. }, samplingMode);
  6293. };
  6294. if (!(fromData instanceof Array))
  6295. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6296. else
  6297. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6298. }
  6299. return texture;
  6300. };
  6301. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6302. var texture = this._gl.createTexture();
  6303. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6304. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6305. // Format
  6306. var internalFormat = this._gl.RGBA;
  6307. switch (format) {
  6308. case Engine.TEXTUREFORMAT_ALPHA:
  6309. internalFormat = this._gl.ALPHA;
  6310. break;
  6311. case Engine.TEXTUREFORMAT_LUMINANCE:
  6312. internalFormat = this._gl.LUMINANCE;
  6313. break;
  6314. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6315. internalFormat = this._gl.LUMINANCE_ALPHA;
  6316. break;
  6317. case Engine.TEXTUREFORMAT_RGB:
  6318. internalFormat = this._gl.RGB;
  6319. break;
  6320. case Engine.TEXTUREFORMAT_RGBA:
  6321. internalFormat = this._gl.RGBA;
  6322. break;
  6323. }
  6324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6325. if (generateMipMaps) {
  6326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6327. }
  6328. // Filters
  6329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6332. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6333. this._activeTexturesCache = [];
  6334. texture._baseWidth = width;
  6335. texture._baseHeight = height;
  6336. texture._width = width;
  6337. texture._height = height;
  6338. texture.isReady = true;
  6339. texture.references = 1;
  6340. texture.samplingMode = samplingMode;
  6341. this._loadedTexturesCache.push(texture);
  6342. return texture;
  6343. };
  6344. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6345. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6346. var texture = this._gl.createTexture();
  6347. texture._baseWidth = width;
  6348. texture._baseHeight = height;
  6349. if (forceExponantOfTwo) {
  6350. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6351. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6352. }
  6353. this._activeTexturesCache = [];
  6354. texture._width = width;
  6355. texture._height = height;
  6356. texture.isReady = false;
  6357. texture.generateMipMaps = generateMipMaps;
  6358. texture.references = 1;
  6359. texture.samplingMode = samplingMode;
  6360. this.updateTextureSamplingMode(samplingMode, texture);
  6361. this._loadedTexturesCache.push(texture);
  6362. return texture;
  6363. };
  6364. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6365. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6366. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. };
  6371. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6372. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6373. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6374. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6375. if (texture.generateMipMaps) {
  6376. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6377. }
  6378. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6379. this._activeTexturesCache = [];
  6380. texture.isReady = true;
  6381. };
  6382. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6385. // Testing video texture support
  6386. if (this._videoTextureSupported === undefined) {
  6387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6388. if (this._gl.getError() !== 0) {
  6389. this._videoTextureSupported = false;
  6390. }
  6391. else {
  6392. this._videoTextureSupported = true;
  6393. }
  6394. }
  6395. // Copy video through the current working canvas if video texture is not supported
  6396. if (!this._videoTextureSupported) {
  6397. if (!texture._workingCanvas) {
  6398. texture._workingCanvas = document.createElement("canvas");
  6399. texture._workingContext = texture._workingCanvas.getContext("2d");
  6400. texture._workingCanvas.width = texture._width;
  6401. texture._workingCanvas.height = texture._height;
  6402. }
  6403. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6404. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6405. }
  6406. else {
  6407. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6408. }
  6409. if (texture.generateMipMaps) {
  6410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6411. }
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6413. this._activeTexturesCache = [];
  6414. texture.isReady = true;
  6415. };
  6416. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6417. // old version had a "generateMipMaps" arg instead of options.
  6418. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6419. // in the same way, generateDepthBuffer is defaulted to true
  6420. var generateMipMaps = false;
  6421. var generateDepthBuffer = true;
  6422. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6423. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6424. if (options !== undefined) {
  6425. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6426. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6427. type = options.type === undefined ? type : options.type;
  6428. if (options.samplingMode !== undefined) {
  6429. samplingMode = options.samplingMode;
  6430. }
  6431. if (type === Engine.TEXTURETYPE_FLOAT) {
  6432. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6433. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6434. }
  6435. }
  6436. var gl = this._gl;
  6437. var texture = gl.createTexture();
  6438. gl.bindTexture(gl.TEXTURE_2D, texture);
  6439. var width = size.width || size;
  6440. var height = size.height || size;
  6441. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6442. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6443. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6444. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6445. }
  6446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6450. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6451. var depthBuffer;
  6452. // Create the depth buffer
  6453. if (generateDepthBuffer) {
  6454. depthBuffer = gl.createRenderbuffer();
  6455. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6456. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6457. }
  6458. // Create the framebuffer
  6459. var framebuffer = gl.createFramebuffer();
  6460. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6462. if (generateDepthBuffer) {
  6463. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6464. }
  6465. // Unbind
  6466. gl.bindTexture(gl.TEXTURE_2D, null);
  6467. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6468. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6469. texture._framebuffer = framebuffer;
  6470. if (generateDepthBuffer) {
  6471. texture._depthBuffer = depthBuffer;
  6472. }
  6473. texture._width = width;
  6474. texture._height = height;
  6475. texture.isReady = true;
  6476. texture.generateMipMaps = generateMipMaps;
  6477. texture.references = 1;
  6478. texture.samplingMode = samplingMode;
  6479. this._activeTexturesCache = [];
  6480. this._loadedTexturesCache.push(texture);
  6481. return texture;
  6482. };
  6483. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6484. var _this = this;
  6485. var gl = this._gl;
  6486. var texture = gl.createTexture();
  6487. texture.isCube = true;
  6488. texture.url = rootUrl;
  6489. texture.references = 1;
  6490. this._loadedTexturesCache.push(texture);
  6491. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6492. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6493. if (isDDS) {
  6494. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6495. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6496. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6497. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6498. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6499. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6500. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6501. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6502. }
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6507. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6508. _this._activeTexturesCache = [];
  6509. texture._width = info.width;
  6510. texture._height = info.height;
  6511. texture.isReady = true;
  6512. }, null, null, true);
  6513. }
  6514. else {
  6515. cascadeLoad(rootUrl, scene, function (imgs) {
  6516. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6517. var height = width;
  6518. _this._prepareWorkingCanvas();
  6519. _this._workingCanvas.width = width;
  6520. _this._workingCanvas.height = height;
  6521. var faces = [
  6522. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6523. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6524. ];
  6525. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6527. for (var index = 0; index < faces.length; index++) {
  6528. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6529. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6530. }
  6531. if (!noMipmap) {
  6532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6533. }
  6534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6538. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6539. _this._activeTexturesCache = [];
  6540. texture._width = width;
  6541. texture._height = height;
  6542. texture.isReady = true;
  6543. }, extensions);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype._releaseTexture = function (texture) {
  6548. var gl = this._gl;
  6549. if (texture._framebuffer) {
  6550. gl.deleteFramebuffer(texture._framebuffer);
  6551. }
  6552. if (texture._depthBuffer) {
  6553. gl.deleteRenderbuffer(texture._depthBuffer);
  6554. }
  6555. gl.deleteTexture(texture);
  6556. // Unbind channels
  6557. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6558. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6559. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6560. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6561. this._activeTexturesCache[channel] = null;
  6562. }
  6563. var index = this._loadedTexturesCache.indexOf(texture);
  6564. if (index !== -1) {
  6565. this._loadedTexturesCache.splice(index, 1);
  6566. }
  6567. };
  6568. Engine.prototype.bindSamplers = function (effect) {
  6569. this._gl.useProgram(effect.getProgram());
  6570. var samplers = effect.getSamplers();
  6571. for (var index = 0; index < samplers.length; index++) {
  6572. var uniform = effect.getUniform(samplers[index]);
  6573. this._gl.uniform1i(uniform, index);
  6574. }
  6575. this._currentEffect = null;
  6576. };
  6577. Engine.prototype._bindTexture = function (channel, texture) {
  6578. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6579. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6580. this._activeTexturesCache[channel] = null;
  6581. };
  6582. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6583. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6584. };
  6585. Engine.prototype.setTexture = function (channel, texture) {
  6586. if (channel < 0) {
  6587. return;
  6588. }
  6589. // Not ready?
  6590. if (!texture || !texture.isReady()) {
  6591. if (this._activeTexturesCache[channel] != null) {
  6592. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6593. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6594. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6595. this._activeTexturesCache[channel] = null;
  6596. }
  6597. return;
  6598. }
  6599. // Video
  6600. if (texture instanceof BABYLON.VideoTexture) {
  6601. if (texture.update()) {
  6602. this._activeTexturesCache[channel] = null;
  6603. }
  6604. }
  6605. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6606. texture.delayLoad();
  6607. return;
  6608. }
  6609. if (this._activeTexturesCache[channel] === texture) {
  6610. return;
  6611. }
  6612. this._activeTexturesCache[channel] = texture;
  6613. var internalTexture = texture.getInternalTexture();
  6614. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6615. if (internalTexture.isCube) {
  6616. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6617. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6618. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6619. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6620. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6621. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6622. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6623. }
  6624. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6625. }
  6626. else {
  6627. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6628. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6629. internalTexture._cachedWrapU = texture.wrapU;
  6630. switch (texture.wrapU) {
  6631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6633. break;
  6634. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, 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_S, this._gl.MIRRORED_REPEAT);
  6639. break;
  6640. }
  6641. }
  6642. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6643. internalTexture._cachedWrapV = texture.wrapV;
  6644. switch (texture.wrapV) {
  6645. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6647. break;
  6648. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6650. break;
  6651. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6653. break;
  6654. }
  6655. }
  6656. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6657. }
  6658. };
  6659. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6660. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6661. var value = texture.anisotropicFilteringLevel;
  6662. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6663. value = 1;
  6664. }
  6665. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6666. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6667. texture._cachedAnisotropicFilteringLevel = value;
  6668. }
  6669. };
  6670. Engine.prototype.readPixels = function (x, y, width, height) {
  6671. var data = new Uint8Array(height * width * 4);
  6672. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6673. return data;
  6674. };
  6675. // Dispose
  6676. Engine.prototype.dispose = function () {
  6677. this.hideLoadingUI();
  6678. this.stopRenderLoop();
  6679. // Release scenes
  6680. while (this.scenes.length) {
  6681. this.scenes[0].dispose();
  6682. }
  6683. // Release audio engine
  6684. Engine.audioEngine.dispose();
  6685. // Release effects
  6686. for (var name in this._compiledEffects) {
  6687. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6688. }
  6689. // Unbind
  6690. for (var i in this._vertexAttribArrays) {
  6691. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6692. continue;
  6693. }
  6694. this._gl.disableVertexAttribArray(i);
  6695. }
  6696. // Events
  6697. window.removeEventListener("blur", this._onBlur);
  6698. window.removeEventListener("focus", this._onFocus);
  6699. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6700. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6701. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6702. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6703. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6704. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6705. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6706. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6707. };
  6708. // Loading screen
  6709. Engine.prototype.displayLoadingUI = function () {
  6710. var _this = this;
  6711. this._loadingDiv = document.createElement("div");
  6712. this._loadingDiv.style.opacity = "0";
  6713. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6714. // Loading text
  6715. this._loadingTextDiv = document.createElement("div");
  6716. this._loadingTextDiv.style.position = "absolute";
  6717. this._loadingTextDiv.style.left = "0";
  6718. this._loadingTextDiv.style.top = "50%";
  6719. this._loadingTextDiv.style.marginTop = "80px";
  6720. this._loadingTextDiv.style.width = "100%";
  6721. this._loadingTextDiv.style.height = "20px";
  6722. this._loadingTextDiv.style.fontFamily = "Arial";
  6723. this._loadingTextDiv.style.fontSize = "14px";
  6724. this._loadingTextDiv.style.color = "white";
  6725. this._loadingTextDiv.style.textAlign = "center";
  6726. this._loadingTextDiv.innerHTML = "Loading";
  6727. this._loadingDiv.appendChild(this._loadingTextDiv);
  6728. // Loading img
  6729. var imgBack = new Image();
  6730. 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==";
  6731. imgBack.style.position = "absolute";
  6732. imgBack.style.left = "50%";
  6733. imgBack.style.top = "50%";
  6734. imgBack.style.marginLeft = "-50px";
  6735. imgBack.style.marginTop = "-50px";
  6736. imgBack.style.transition = "transform 1.0s ease";
  6737. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6738. var deg = 360;
  6739. var onTransitionEnd = function () {
  6740. deg += 360;
  6741. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6742. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6743. };
  6744. imgBack.addEventListener("transitionend", onTransitionEnd);
  6745. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6746. this._loadingDiv.appendChild(imgBack);
  6747. // front image
  6748. var imgFront = new Image();
  6749. 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=";
  6750. imgFront.style.position = "absolute";
  6751. imgFront.style.left = "50%";
  6752. imgFront.style.top = "50%";
  6753. imgFront.style.marginLeft = "-50px";
  6754. imgFront.style.marginTop = "-50px";
  6755. this._loadingDiv.appendChild(imgFront);
  6756. // Resize
  6757. this._resizeLoadingUI = function () {
  6758. var canvasRect = _this.getRenderingCanvasClientRect();
  6759. _this._loadingDiv.style.position = "absolute";
  6760. _this._loadingDiv.style.left = canvasRect.left + "px";
  6761. _this._loadingDiv.style.top = canvasRect.top + "px";
  6762. _this._loadingDiv.style.width = canvasRect.width + "px";
  6763. _this._loadingDiv.style.height = canvasRect.height + "px";
  6764. };
  6765. this._resizeLoadingUI();
  6766. window.addEventListener("resize", this._resizeLoadingUI);
  6767. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6768. document.body.appendChild(this._loadingDiv);
  6769. setTimeout(function () {
  6770. _this._loadingDiv.style.opacity = "1";
  6771. imgBack.style.transform = "rotateZ(360deg)";
  6772. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6773. }, 0);
  6774. };
  6775. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6776. set: function (text) {
  6777. if (!this._loadingDiv) {
  6778. return;
  6779. }
  6780. this._loadingTextDiv.innerHTML = text;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6786. get: function () {
  6787. return this._loadingDivBackgroundColor;
  6788. },
  6789. set: function (color) {
  6790. this._loadingDivBackgroundColor = color;
  6791. if (!this._loadingDiv) {
  6792. return;
  6793. }
  6794. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6795. },
  6796. enumerable: true,
  6797. configurable: true
  6798. });
  6799. Engine.prototype.hideLoadingUI = function () {
  6800. var _this = this;
  6801. if (!this._loadingDiv) {
  6802. return;
  6803. }
  6804. var onTransitionEnd = function () {
  6805. if (!_this._loadingDiv) {
  6806. return;
  6807. }
  6808. document.body.removeChild(_this._loadingDiv);
  6809. window.removeEventListener("resize", _this._resizeLoadingUI);
  6810. _this._loadingDiv = null;
  6811. };
  6812. this._loadingDiv.style.opacity = "0";
  6813. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6814. };
  6815. // FPS
  6816. Engine.prototype.getFps = function () {
  6817. return this.fps;
  6818. };
  6819. Engine.prototype.getDeltaTime = function () {
  6820. return this.deltaTime;
  6821. };
  6822. Engine.prototype._measureFps = function () {
  6823. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6824. var length = this.previousFramesDuration.length;
  6825. if (length >= 2) {
  6826. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6827. }
  6828. if (length >= this.fpsRange) {
  6829. if (length > this.fpsRange) {
  6830. this.previousFramesDuration.splice(0, 1);
  6831. length = this.previousFramesDuration.length;
  6832. }
  6833. var sum = 0;
  6834. for (var id = 0; id < length - 1; id++) {
  6835. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6836. }
  6837. this.fps = 1000.0 / (sum / (length - 1));
  6838. }
  6839. };
  6840. // Statics
  6841. Engine.isSupported = function () {
  6842. try {
  6843. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6844. if (navigator.isCocoonJS) {
  6845. return true;
  6846. }
  6847. var tempcanvas = document.createElement("canvas");
  6848. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6849. return gl != null && !!window.WebGLRenderingContext;
  6850. }
  6851. catch (e) {
  6852. return false;
  6853. }
  6854. };
  6855. // Const statics
  6856. Engine._ALPHA_DISABLE = 0;
  6857. Engine._ALPHA_ADD = 1;
  6858. Engine._ALPHA_COMBINE = 2;
  6859. Engine._DELAYLOADSTATE_NONE = 0;
  6860. Engine._DELAYLOADSTATE_LOADED = 1;
  6861. Engine._DELAYLOADSTATE_LOADING = 2;
  6862. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6863. Engine._TEXTUREFORMAT_ALPHA = 0;
  6864. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6865. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6866. Engine._TEXTUREFORMAT_RGB = 4;
  6867. Engine._TEXTUREFORMAT_RGBA = 4;
  6868. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6869. Engine._TEXTURETYPE_FLOAT = 1;
  6870. // Updatable statics so stick with vars here
  6871. Engine.Epsilon = 0.001;
  6872. Engine.CollisionsEpsilon = 0.001;
  6873. Engine.CodeRepository = "Babylon/";
  6874. Engine.ShadersRepository = "Babylon/Shaders/";
  6875. return Engine;
  6876. })();
  6877. BABYLON.Engine = Engine;
  6878. })(BABYLON || (BABYLON = {}));
  6879. //# sourceMappingURL=babylon.engine.js.map
  6880. var BABYLON;
  6881. (function (BABYLON) {
  6882. /**
  6883. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6884. */
  6885. var Node = (function () {
  6886. /**
  6887. * @constructor
  6888. * @param {string} name - the name and id to be given to this node
  6889. * @param {BABYLON.Scene} the scene this node will be added to
  6890. */
  6891. function Node(name, scene) {
  6892. this.state = "";
  6893. this.animations = new Array();
  6894. this._childrenFlag = -1;
  6895. this._isEnabled = true;
  6896. this._isReady = true;
  6897. this._currentRenderId = -1;
  6898. this._parentRenderId = -1;
  6899. this.name = name;
  6900. this.id = name;
  6901. this._scene = scene;
  6902. this._initCache();
  6903. }
  6904. Node.prototype.getScene = function () {
  6905. return this._scene;
  6906. };
  6907. Node.prototype.getEngine = function () {
  6908. return this._scene.getEngine();
  6909. };
  6910. // override it in derived class
  6911. Node.prototype.getWorldMatrix = function () {
  6912. return BABYLON.Matrix.Identity();
  6913. };
  6914. // override it in derived class if you add new variables to the cache
  6915. // and call the parent class method
  6916. Node.prototype._initCache = function () {
  6917. this._cache = {};
  6918. this._cache.parent = undefined;
  6919. };
  6920. Node.prototype.updateCache = function (force) {
  6921. if (!force && this.isSynchronized())
  6922. return;
  6923. this._cache.parent = this.parent;
  6924. this._updateCache();
  6925. };
  6926. // override it in derived class if you add new variables to the cache
  6927. // and call the parent class method if !ignoreParentClass
  6928. Node.prototype._updateCache = function (ignoreParentClass) {
  6929. };
  6930. // override it in derived class if you add new variables to the cache
  6931. Node.prototype._isSynchronized = function () {
  6932. return true;
  6933. };
  6934. Node.prototype._markSyncedWithParent = function () {
  6935. this._parentRenderId = this.parent._currentRenderId;
  6936. };
  6937. Node.prototype.isSynchronizedWithParent = function () {
  6938. if (!this.parent) {
  6939. return true;
  6940. }
  6941. if (this._parentRenderId !== this.parent._currentRenderId) {
  6942. return false;
  6943. }
  6944. return this.parent.isSynchronized();
  6945. };
  6946. Node.prototype.isSynchronized = function (updateCache) {
  6947. var check = this.hasNewParent();
  6948. check = check || !this.isSynchronizedWithParent();
  6949. check = check || !this._isSynchronized();
  6950. if (updateCache)
  6951. this.updateCache(true);
  6952. return !check;
  6953. };
  6954. Node.prototype.hasNewParent = function (update) {
  6955. if (this._cache.parent === this.parent)
  6956. return false;
  6957. if (update)
  6958. this._cache.parent = this.parent;
  6959. return true;
  6960. };
  6961. /**
  6962. * Is this node ready to be used/rendered
  6963. * @return {boolean} is it ready
  6964. */
  6965. Node.prototype.isReady = function () {
  6966. return this._isReady;
  6967. };
  6968. /**
  6969. * Is this node enabled.
  6970. * If the node has a parent and is enabled, the parent will be inspected as well.
  6971. * @return {boolean} whether this node (and its parent) is enabled.
  6972. * @see setEnabled
  6973. */
  6974. Node.prototype.isEnabled = function () {
  6975. if (!this._isEnabled) {
  6976. return false;
  6977. }
  6978. if (this.parent) {
  6979. return this.parent.isEnabled();
  6980. }
  6981. return true;
  6982. };
  6983. /**
  6984. * Set the enabled state of this node.
  6985. * @param {boolean} value - the new enabled state
  6986. * @see isEnabled
  6987. */
  6988. Node.prototype.setEnabled = function (value) {
  6989. this._isEnabled = value;
  6990. };
  6991. /**
  6992. * Is this node a descendant of the given node.
  6993. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6994. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6995. * @see parent
  6996. */
  6997. Node.prototype.isDescendantOf = function (ancestor) {
  6998. if (this.parent) {
  6999. if (this.parent === ancestor) {
  7000. return true;
  7001. }
  7002. return this.parent.isDescendantOf(ancestor);
  7003. }
  7004. return false;
  7005. };
  7006. Node.prototype._getDescendants = function (list, results) {
  7007. for (var index = 0; index < list.length; index++) {
  7008. var item = list[index];
  7009. if (item.isDescendantOf(this)) {
  7010. results.push(item);
  7011. }
  7012. }
  7013. };
  7014. /**
  7015. * Will return all nodes that have this node as parent.
  7016. * @return {BABYLON.Node[]} all children nodes of all types.
  7017. */
  7018. Node.prototype.getDescendants = function () {
  7019. var results = [];
  7020. this._getDescendants(this._scene.meshes, results);
  7021. this._getDescendants(this._scene.lights, results);
  7022. this._getDescendants(this._scene.cameras, results);
  7023. return results;
  7024. };
  7025. Node.prototype._setReady = function (state) {
  7026. if (state == this._isReady) {
  7027. return;
  7028. }
  7029. if (!state) {
  7030. this._isReady = false;
  7031. return;
  7032. }
  7033. this._isReady = true;
  7034. if (this.onReady) {
  7035. this.onReady(this);
  7036. }
  7037. };
  7038. return Node;
  7039. })();
  7040. BABYLON.Node = Node;
  7041. })(BABYLON || (BABYLON = {}));
  7042. //# sourceMappingURL=babylon.node.js.map
  7043. var BABYLON;
  7044. (function (BABYLON) {
  7045. var FilesInput = (function () {
  7046. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7047. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7048. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7049. this._engine = p_engine;
  7050. this._canvas = p_canvas;
  7051. this._currentScene = p_scene;
  7052. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7053. this._progressCallback = p_progressCallback;
  7054. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7055. this._textureLoadingCallback = p_textureLoadingCallback;
  7056. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7057. }
  7058. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7059. var _this = this;
  7060. if (p_elementToMonitor) {
  7061. this._elementToMonitor = p_elementToMonitor;
  7062. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7063. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7064. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7065. }
  7066. };
  7067. FilesInput.prototype.renderFunction = function () {
  7068. if (this._additionnalRenderLoopLogicCallback) {
  7069. this._additionnalRenderLoopLogicCallback();
  7070. }
  7071. if (this._currentScene) {
  7072. if (this._textureLoadingCallback) {
  7073. var remaining = this._currentScene.getWaitingItemsCount();
  7074. if (remaining > 0) {
  7075. this._textureLoadingCallback(remaining);
  7076. }
  7077. }
  7078. this._currentScene.render();
  7079. }
  7080. };
  7081. FilesInput.prototype.drag = function (e) {
  7082. e.stopPropagation();
  7083. e.preventDefault();
  7084. };
  7085. FilesInput.prototype.drop = function (eventDrop) {
  7086. eventDrop.stopPropagation();
  7087. eventDrop.preventDefault();
  7088. this.loadFiles(eventDrop);
  7089. };
  7090. FilesInput.prototype.loadFiles = function (event) {
  7091. if (this._startingProcessingFilesCallback)
  7092. this._startingProcessingFilesCallback();
  7093. // Handling data transfer via drag'n'drop
  7094. if (event && event.dataTransfer && event.dataTransfer.files) {
  7095. this._filesToLoad = event.dataTransfer.files;
  7096. }
  7097. // Handling files from input files
  7098. if (event && event.target && event.target.files) {
  7099. this._filesToLoad = event.target.files;
  7100. }
  7101. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7102. for (var i = 0; i < this._filesToLoad.length; i++) {
  7103. switch (this._filesToLoad[i].type) {
  7104. case "image/jpeg":
  7105. case "image/png":
  7106. case "image/bmp":
  7107. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7108. break;
  7109. case "image/targa":
  7110. case "image/vnd.ms-dds":
  7111. case "audio/wav":
  7112. case "audio/x-wav":
  7113. case "audio/mp3":
  7114. case "audio/mpeg":
  7115. case "audio/mpeg3":
  7116. case "audio/x-mpeg-3":
  7117. case "audio/ogg":
  7118. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7119. break;
  7120. default:
  7121. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7122. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7123. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7124. this._sceneFileToLoad = this._filesToLoad[i];
  7125. }
  7126. break;
  7127. }
  7128. }
  7129. this.reload();
  7130. }
  7131. };
  7132. FilesInput.prototype.reload = function () {
  7133. var _this = this;
  7134. var that = this;
  7135. // If a ".babylon" file has been provided
  7136. if (this._sceneFileToLoad) {
  7137. if (this._currentScene) {
  7138. this._engine.stopRenderLoop();
  7139. this._currentScene.dispose();
  7140. }
  7141. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7142. that._currentScene = newScene;
  7143. // Wait for textures and shaders to be ready
  7144. that._currentScene.executeWhenReady(function () {
  7145. // Attach camera to canvas inputs
  7146. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7147. that._currentScene.createDefaultCameraOrLight();
  7148. }
  7149. that._currentScene.activeCamera.attachControl(that._canvas);
  7150. if (that._sceneLoadedCallback) {
  7151. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7152. }
  7153. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7154. });
  7155. }, function (progress) {
  7156. if (_this._progressCallback) {
  7157. _this._progressCallback(progress);
  7158. }
  7159. });
  7160. }
  7161. else {
  7162. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7163. }
  7164. };
  7165. FilesInput.FilesTextures = new Array();
  7166. FilesInput.FilesToLoad = new Array();
  7167. return FilesInput;
  7168. })();
  7169. BABYLON.FilesInput = FilesInput;
  7170. })(BABYLON || (BABYLON = {}));
  7171. //# sourceMappingURL=babylon.filesInput.js.map
  7172. var BABYLON;
  7173. (function (BABYLON) {
  7174. var IntersectionInfo = (function () {
  7175. function IntersectionInfo(bu, bv, distance) {
  7176. this.bu = bu;
  7177. this.bv = bv;
  7178. this.distance = distance;
  7179. this.faceId = 0;
  7180. this.subMeshId = 0;
  7181. }
  7182. return IntersectionInfo;
  7183. })();
  7184. BABYLON.IntersectionInfo = IntersectionInfo;
  7185. var PickingInfo = (function () {
  7186. function PickingInfo() {
  7187. this.hit = false;
  7188. this.distance = 0;
  7189. this.pickedPoint = null;
  7190. this.pickedMesh = null;
  7191. this.bu = 0;
  7192. this.bv = 0;
  7193. this.faceId = -1;
  7194. this.subMeshId = 0;
  7195. }
  7196. // Methods
  7197. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7198. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7199. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7200. return null;
  7201. }
  7202. var indices = this.pickedMesh.getIndices();
  7203. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7204. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7205. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7206. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7207. normal0 = normal0.scale(this.bu);
  7208. normal1 = normal1.scale(this.bv);
  7209. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7210. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7211. if (useWorldCoordinates) {
  7212. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7213. }
  7214. return result;
  7215. };
  7216. PickingInfo.prototype.getTextureCoordinates = function () {
  7217. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7218. return null;
  7219. }
  7220. var indices = this.pickedMesh.getIndices();
  7221. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7222. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7223. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7224. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7225. uv0 = uv0.scale(this.bu);
  7226. uv1 = uv1.scale(this.bv);
  7227. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7228. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7229. };
  7230. return PickingInfo;
  7231. })();
  7232. BABYLON.PickingInfo = PickingInfo;
  7233. })(BABYLON || (BABYLON = {}));
  7234. //# sourceMappingURL=babylon.pickingInfo.js.map
  7235. var BABYLON;
  7236. (function (BABYLON) {
  7237. var BoundingSphere = (function () {
  7238. function BoundingSphere(minimum, maximum) {
  7239. this.minimum = minimum;
  7240. this.maximum = maximum;
  7241. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7242. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7243. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7244. this.radius = distance * 0.5;
  7245. this.centerWorld = BABYLON.Vector3.Zero();
  7246. this._update(BABYLON.Matrix.Identity());
  7247. }
  7248. // Methods
  7249. BoundingSphere.prototype._update = function (world) {
  7250. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7251. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7252. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7253. };
  7254. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7255. for (var i = 0; i < 6; i++) {
  7256. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7257. return false;
  7258. }
  7259. return true;
  7260. };
  7261. BoundingSphere.prototype.intersectsPoint = function (point) {
  7262. var x = this.centerWorld.x - point.x;
  7263. var y = this.centerWorld.y - point.y;
  7264. var z = this.centerWorld.z - point.z;
  7265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7266. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7267. return false;
  7268. return true;
  7269. };
  7270. // Statics
  7271. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7272. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7273. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7274. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7275. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7276. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7277. return false;
  7278. return true;
  7279. };
  7280. return BoundingSphere;
  7281. })();
  7282. BABYLON.BoundingSphere = BoundingSphere;
  7283. })(BABYLON || (BABYLON = {}));
  7284. //# sourceMappingURL=babylon.boundingSphere.js.map
  7285. var BABYLON;
  7286. (function (BABYLON) {
  7287. var BoundingBox = (function () {
  7288. function BoundingBox(minimum, maximum) {
  7289. this.minimum = minimum;
  7290. this.maximum = maximum;
  7291. this.vectors = new Array();
  7292. this.vectorsWorld = new Array();
  7293. // Bounding vectors
  7294. this.vectors.push(this.minimum.clone());
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors.push(this.minimum.clone());
  7297. this.vectors[2].x = this.maximum.x;
  7298. this.vectors.push(this.minimum.clone());
  7299. this.vectors[3].y = this.maximum.y;
  7300. this.vectors.push(this.minimum.clone());
  7301. this.vectors[4].z = this.maximum.z;
  7302. this.vectors.push(this.maximum.clone());
  7303. this.vectors[5].z = this.minimum.z;
  7304. this.vectors.push(this.maximum.clone());
  7305. this.vectors[6].x = this.minimum.x;
  7306. this.vectors.push(this.maximum.clone());
  7307. this.vectors[7].y = this.minimum.y;
  7308. // OBB
  7309. this.center = this.maximum.add(this.minimum).scale(0.5);
  7310. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7311. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7312. // World
  7313. for (var index = 0; index < this.vectors.length; index++) {
  7314. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7315. }
  7316. this.minimumWorld = BABYLON.Vector3.Zero();
  7317. this.maximumWorld = BABYLON.Vector3.Zero();
  7318. this._update(BABYLON.Matrix.Identity());
  7319. }
  7320. // Methods
  7321. BoundingBox.prototype.getWorldMatrix = function () {
  7322. return this._worldMatrix;
  7323. };
  7324. BoundingBox.prototype._update = function (world) {
  7325. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7326. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7327. for (var index = 0; index < this.vectors.length; index++) {
  7328. var v = this.vectorsWorld[index];
  7329. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7330. if (v.x < this.minimumWorld.x)
  7331. this.minimumWorld.x = v.x;
  7332. if (v.y < this.minimumWorld.y)
  7333. this.minimumWorld.y = v.y;
  7334. if (v.z < this.minimumWorld.z)
  7335. this.minimumWorld.z = v.z;
  7336. if (v.x > this.maximumWorld.x)
  7337. this.maximumWorld.x = v.x;
  7338. if (v.y > this.maximumWorld.y)
  7339. this.maximumWorld.y = v.y;
  7340. if (v.z > this.maximumWorld.z)
  7341. this.maximumWorld.z = v.z;
  7342. }
  7343. // OBB
  7344. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7345. this.center.scaleInPlace(0.5);
  7346. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7347. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7348. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7349. this._worldMatrix = world;
  7350. };
  7351. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7352. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7353. };
  7354. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7355. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7356. };
  7357. BoundingBox.prototype.intersectsPoint = function (point) {
  7358. var delta = -BABYLON.Engine.Epsilon;
  7359. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7360. return false;
  7361. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7362. return false;
  7363. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7364. return false;
  7365. return true;
  7366. };
  7367. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7368. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7369. };
  7370. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7371. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7372. return false;
  7373. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7374. return false;
  7375. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7376. return false;
  7377. return true;
  7378. };
  7379. // Statics
  7380. BoundingBox.Intersects = function (box0, box1) {
  7381. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7382. return false;
  7383. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7384. return false;
  7385. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7386. return false;
  7387. return true;
  7388. };
  7389. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7390. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7391. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7392. return (num <= (sphereRadius * sphereRadius));
  7393. };
  7394. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7395. for (var p = 0; p < 6; p++) {
  7396. for (var i = 0; i < 8; i++) {
  7397. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7398. return false;
  7399. }
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7405. for (var p = 0; p < 6; p++) {
  7406. var inCount = 8;
  7407. for (var i = 0; i < 8; i++) {
  7408. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7409. --inCount;
  7410. }
  7411. else {
  7412. break;
  7413. }
  7414. }
  7415. if (inCount === 0)
  7416. return false;
  7417. }
  7418. return true;
  7419. };
  7420. return BoundingBox;
  7421. })();
  7422. BABYLON.BoundingBox = BoundingBox;
  7423. })(BABYLON || (BABYLON = {}));
  7424. //# sourceMappingURL=babylon.boundingBox.js.map
  7425. var BABYLON;
  7426. (function (BABYLON) {
  7427. var computeBoxExtents = function (axis, box) {
  7428. var p = BABYLON.Vector3.Dot(box.center, axis);
  7429. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7430. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7431. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7432. var r = r0 + r1 + r2;
  7433. return {
  7434. min: p - r,
  7435. max: p + r
  7436. };
  7437. };
  7438. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7439. var axisOverlap = function (axis, box0, box1) {
  7440. var result0 = computeBoxExtents(axis, box0);
  7441. var result1 = computeBoxExtents(axis, box1);
  7442. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7443. };
  7444. var BoundingInfo = (function () {
  7445. function BoundingInfo(minimum, maximum) {
  7446. this.minimum = minimum;
  7447. this.maximum = maximum;
  7448. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7449. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7450. }
  7451. // Methods
  7452. BoundingInfo.prototype._update = function (world) {
  7453. this.boundingBox._update(world);
  7454. this.boundingSphere._update(world);
  7455. };
  7456. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7457. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7458. return false;
  7459. return this.boundingBox.isInFrustum(frustumPlanes);
  7460. };
  7461. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7462. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7463. };
  7464. BoundingInfo.prototype._checkCollision = function (collider) {
  7465. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7466. };
  7467. BoundingInfo.prototype.intersectsPoint = function (point) {
  7468. if (!this.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!this.boundingSphere.intersectsPoint(point)) {
  7472. return false;
  7473. }
  7474. if (!this.boundingBox.intersectsPoint(point)) {
  7475. return false;
  7476. }
  7477. return true;
  7478. };
  7479. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7480. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7481. return false;
  7482. }
  7483. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7484. return false;
  7485. }
  7486. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7487. return false;
  7488. }
  7489. if (!precise) {
  7490. return true;
  7491. }
  7492. var box0 = this.boundingBox;
  7493. var box1 = boundingInfo.boundingBox;
  7494. if (!axisOverlap(box0.directions[0], box0, box1))
  7495. return false;
  7496. if (!axisOverlap(box0.directions[1], box0, box1))
  7497. return false;
  7498. if (!axisOverlap(box0.directions[2], box0, box1))
  7499. return false;
  7500. if (!axisOverlap(box1.directions[0], box0, box1))
  7501. return false;
  7502. if (!axisOverlap(box1.directions[1], box0, box1))
  7503. return false;
  7504. if (!axisOverlap(box1.directions[2], box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7511. return false;
  7512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7513. return false;
  7514. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7515. return false;
  7516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7517. return false;
  7518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7519. return false;
  7520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7521. return false;
  7522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7523. return false;
  7524. return true;
  7525. };
  7526. return BoundingInfo;
  7527. })();
  7528. BABYLON.BoundingInfo = BoundingInfo;
  7529. })(BABYLON || (BABYLON = {}));
  7530. //# sourceMappingURL=babylon.boundingInfo.js.map
  7531. var __extends = this.__extends || function (d, b) {
  7532. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7533. function __() { this.constructor = d; }
  7534. __.prototype = b.prototype;
  7535. d.prototype = new __();
  7536. };
  7537. var BABYLON;
  7538. (function (BABYLON) {
  7539. var AbstractMesh = (function (_super) {
  7540. __extends(AbstractMesh, _super);
  7541. function AbstractMesh(name, scene) {
  7542. var _this = this;
  7543. _super.call(this, name, scene);
  7544. // Properties
  7545. this.definedFacingForward = true; // orientation for POV movement & rotation
  7546. this.position = new BABYLON.Vector3(0, 0, 0);
  7547. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7548. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7549. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7550. this.visibility = 1.0;
  7551. this.alphaIndex = Number.MAX_VALUE;
  7552. this.infiniteDistance = false;
  7553. this.isVisible = true;
  7554. this.isPickable = true;
  7555. this.showBoundingBox = false;
  7556. this.showSubMeshesBoundingBox = false;
  7557. this.onDispose = null;
  7558. this.checkCollisions = false;
  7559. this.isBlocker = false;
  7560. this.renderingGroupId = 0;
  7561. this.receiveShadows = false;
  7562. this.renderOutline = false;
  7563. this.outlineColor = BABYLON.Color3.Red();
  7564. this.outlineWidth = 0.02;
  7565. this.renderOverlay = false;
  7566. this.overlayColor = BABYLON.Color3.Red();
  7567. this.overlayAlpha = 0.5;
  7568. this.hasVertexAlpha = false;
  7569. this.useVertexColors = true;
  7570. this.applyFog = true;
  7571. this.useOctreeForRenderingSelection = true;
  7572. this.useOctreeForPicking = true;
  7573. this.useOctreeForCollisions = true;
  7574. this.layerMask = 0x0FFFFFFF;
  7575. this.alwaysSelectAsActiveMesh = false;
  7576. // Physics
  7577. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7578. // Collisions
  7579. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7580. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7581. this._collider = new BABYLON.Collider();
  7582. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7583. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7584. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7585. // Cache
  7586. this._localScaling = BABYLON.Matrix.Zero();
  7587. this._localRotation = BABYLON.Matrix.Zero();
  7588. this._localTranslation = BABYLON.Matrix.Zero();
  7589. this._localBillboard = BABYLON.Matrix.Zero();
  7590. this._localPivotScaling = BABYLON.Matrix.Zero();
  7591. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7592. this._localWorld = BABYLON.Matrix.Zero();
  7593. this._worldMatrix = BABYLON.Matrix.Zero();
  7594. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7595. this._absolutePosition = BABYLON.Vector3.Zero();
  7596. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7597. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7598. this._isDirty = false;
  7599. this._pivotMatrix = BABYLON.Matrix.Identity();
  7600. this._isDisposed = false;
  7601. this._renderId = 0;
  7602. this._intersectionsInProgress = new Array();
  7603. this._onAfterWorldMatrixUpdate = new Array();
  7604. this._isWorldMatrixFrozen = false;
  7605. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7606. if (collidedMesh === void 0) { collidedMesh = null; }
  7607. //TODO move this to the collision coordinator!
  7608. if (_this.getScene().workerCollisions)
  7609. newPosition.multiplyInPlace(_this._collider.radius);
  7610. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7611. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7612. _this.position.addInPlace(_this._diffPositionForCollisions);
  7613. }
  7614. };
  7615. scene.addMesh(this);
  7616. }
  7617. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7618. get: function () {
  7619. return AbstractMesh._BILLBOARDMODE_NONE;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7625. get: function () {
  7626. return AbstractMesh._BILLBOARDMODE_X;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7632. get: function () {
  7633. return AbstractMesh._BILLBOARDMODE_Y;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7639. get: function () {
  7640. return AbstractMesh._BILLBOARDMODE_Z;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7646. get: function () {
  7647. return AbstractMesh._BILLBOARDMODE_ALL;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7653. // Methods
  7654. get: function () {
  7655. return false;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. AbstractMesh.prototype.getLOD = function (camera) {
  7661. return this;
  7662. };
  7663. AbstractMesh.prototype.getTotalVertices = function () {
  7664. return 0;
  7665. };
  7666. AbstractMesh.prototype.getIndices = function () {
  7667. return null;
  7668. };
  7669. AbstractMesh.prototype.getVerticesData = function (kind) {
  7670. return null;
  7671. };
  7672. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7673. return false;
  7674. };
  7675. AbstractMesh.prototype.getBoundingInfo = function () {
  7676. if (this._masterMesh) {
  7677. return this._masterMesh.getBoundingInfo();
  7678. }
  7679. if (!this._boundingInfo) {
  7680. this._updateBoundingInfo();
  7681. }
  7682. return this._boundingInfo;
  7683. };
  7684. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7685. get: function () {
  7686. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. AbstractMesh.prototype._preActivate = function () {
  7692. };
  7693. AbstractMesh.prototype._activate = function (renderId) {
  7694. this._renderId = renderId;
  7695. };
  7696. AbstractMesh.prototype.getWorldMatrix = function () {
  7697. if (this._masterMesh) {
  7698. return this._masterMesh.getWorldMatrix();
  7699. }
  7700. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7701. this.computeWorldMatrix();
  7702. }
  7703. return this._worldMatrix;
  7704. };
  7705. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7706. get: function () {
  7707. return this._worldMatrix;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7713. get: function () {
  7714. return this._absolutePosition;
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7720. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7721. this.computeWorldMatrix(true);
  7722. this._isWorldMatrixFrozen = true;
  7723. };
  7724. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7725. this._isWorldMatrixFrozen = false;
  7726. this.computeWorldMatrix(true);
  7727. };
  7728. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7729. get: function () {
  7730. return this._isWorldMatrixFrozen;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7736. if (!this.rotationQuaternion) {
  7737. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7738. this.rotation = BABYLON.Vector3.Zero();
  7739. }
  7740. if (!space || space === BABYLON.Space.LOCAL) {
  7741. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7742. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7743. }
  7744. else {
  7745. if (this.parent) {
  7746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7747. invertParentWorldMatrix.invert();
  7748. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7749. }
  7750. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7751. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7752. }
  7753. };
  7754. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7755. var displacementVector = axis.scale(distance);
  7756. if (!space || space === BABYLON.Space.LOCAL) {
  7757. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7758. this.setPositionWithLocalVector(tempV3);
  7759. }
  7760. else {
  7761. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7762. }
  7763. };
  7764. AbstractMesh.prototype.getAbsolutePosition = function () {
  7765. this.computeWorldMatrix();
  7766. return this._absolutePosition;
  7767. };
  7768. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7769. if (!absolutePosition) {
  7770. return;
  7771. }
  7772. var absolutePositionX;
  7773. var absolutePositionY;
  7774. var absolutePositionZ;
  7775. if (absolutePosition.x === undefined) {
  7776. if (arguments.length < 3) {
  7777. return;
  7778. }
  7779. absolutePositionX = arguments[0];
  7780. absolutePositionY = arguments[1];
  7781. absolutePositionZ = arguments[2];
  7782. }
  7783. else {
  7784. absolutePositionX = absolutePosition.x;
  7785. absolutePositionY = absolutePosition.y;
  7786. absolutePositionZ = absolutePosition.z;
  7787. }
  7788. if (this.parent) {
  7789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7790. invertParentWorldMatrix.invert();
  7791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7793. }
  7794. else {
  7795. this.position.x = absolutePositionX;
  7796. this.position.y = absolutePositionY;
  7797. this.position.z = absolutePositionZ;
  7798. }
  7799. };
  7800. // ================================== Point of View Movement =================================
  7801. /**
  7802. * Perform relative position change from the point of view of behind the front of the mesh.
  7803. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7804. * Supports definition of mesh facing forward or backward.
  7805. * @param {number} amountRight
  7806. * @param {number} amountUp
  7807. * @param {number} amountForward
  7808. */
  7809. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7810. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7811. };
  7812. /**
  7813. * Calculate relative position change from the point of view of behind the front of the mesh.
  7814. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7815. * Supports definition of mesh facing forward or backward.
  7816. * @param {number} amountRight
  7817. * @param {number} amountUp
  7818. * @param {number} amountForward
  7819. */
  7820. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7821. var rotMatrix = new BABYLON.Matrix();
  7822. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7823. rotQuaternion.toRotationMatrix(rotMatrix);
  7824. var translationDelta = BABYLON.Vector3.Zero();
  7825. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7827. return translationDelta;
  7828. };
  7829. // ================================== Point of View Rotation =================================
  7830. /**
  7831. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7832. * Supports definition of mesh facing forward or backward.
  7833. * @param {number} flipBack
  7834. * @param {number} twirlClockwise
  7835. * @param {number} tiltRight
  7836. */
  7837. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7839. };
  7840. /**
  7841. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7842. * Supports definition of mesh facing forward or backward.
  7843. * @param {number} flipBack
  7844. * @param {number} twirlClockwise
  7845. * @param {number} tiltRight
  7846. */
  7847. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7848. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7849. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7850. };
  7851. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7852. this._pivotMatrix = matrix;
  7853. this._cache.pivotMatrixUpdated = true;
  7854. };
  7855. AbstractMesh.prototype.getPivotMatrix = function () {
  7856. return this._pivotMatrix;
  7857. };
  7858. AbstractMesh.prototype._isSynchronized = function () {
  7859. if (this._isDirty) {
  7860. return false;
  7861. }
  7862. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7863. return false;
  7864. if (this._cache.pivotMatrixUpdated) {
  7865. return false;
  7866. }
  7867. if (this.infiniteDistance) {
  7868. return false;
  7869. }
  7870. if (!this._cache.position.equals(this.position))
  7871. return false;
  7872. if (this.rotationQuaternion) {
  7873. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7874. return false;
  7875. }
  7876. else {
  7877. if (!this._cache.rotation.equals(this.rotation))
  7878. return false;
  7879. }
  7880. if (!this._cache.scaling.equals(this.scaling))
  7881. return false;
  7882. return true;
  7883. };
  7884. AbstractMesh.prototype._initCache = function () {
  7885. _super.prototype._initCache.call(this);
  7886. this._cache.localMatrixUpdated = false;
  7887. this._cache.position = BABYLON.Vector3.Zero();
  7888. this._cache.scaling = BABYLON.Vector3.Zero();
  7889. this._cache.rotation = BABYLON.Vector3.Zero();
  7890. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7891. };
  7892. AbstractMesh.prototype.markAsDirty = function (property) {
  7893. if (property === "rotation") {
  7894. this.rotationQuaternion = null;
  7895. }
  7896. this._currentRenderId = Number.MAX_VALUE;
  7897. this._isDirty = true;
  7898. };
  7899. AbstractMesh.prototype._updateBoundingInfo = function () {
  7900. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7901. this._boundingInfo._update(this.worldMatrixFromCache);
  7902. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7903. };
  7904. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7905. if (!this.subMeshes) {
  7906. return;
  7907. }
  7908. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7909. var subMesh = this.subMeshes[subIndex];
  7910. subMesh.updateBoundingInfo(matrix);
  7911. }
  7912. };
  7913. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7914. if (this._isWorldMatrixFrozen) {
  7915. return this._worldMatrix;
  7916. }
  7917. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7918. return this._worldMatrix;
  7919. }
  7920. this._cache.position.copyFrom(this.position);
  7921. this._cache.scaling.copyFrom(this.scaling);
  7922. this._cache.pivotMatrixUpdated = false;
  7923. this._currentRenderId = this.getScene().getRenderId();
  7924. this._isDirty = false;
  7925. // Scaling
  7926. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7927. // Rotation
  7928. if (this.rotationQuaternion) {
  7929. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7930. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7931. }
  7932. else {
  7933. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7934. this._cache.rotation.copyFrom(this.rotation);
  7935. }
  7936. // Translation
  7937. if (this.infiniteDistance && !this.parent) {
  7938. var camera = this.getScene().activeCamera;
  7939. var cameraWorldMatrix = camera.getWorldMatrix();
  7940. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7941. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7942. }
  7943. else {
  7944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7945. }
  7946. // Composing transformations
  7947. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7948. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7949. // Billboarding
  7950. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7951. var localPosition = this.position.clone();
  7952. var zero = this.getScene().activeCamera.globalPosition.clone();
  7953. if (this.parent && this.parent.position) {
  7954. localPosition.addInPlace(this.parent.position);
  7955. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7956. }
  7957. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7958. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7959. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7960. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7961. zero.y = localPosition.y + 0.001;
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7963. zero.z = localPosition.z + 0.001;
  7964. }
  7965. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7966. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7967. this._localBillboard.invert();
  7968. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7969. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7970. }
  7971. // Local world
  7972. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7973. // Parent
  7974. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7975. this._markSyncedWithParent();
  7976. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7977. }
  7978. else {
  7979. this._worldMatrix.copyFrom(this._localWorld);
  7980. }
  7981. // Bounding info
  7982. this._updateBoundingInfo();
  7983. // Absolute position
  7984. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7985. // Callbacks
  7986. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7987. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7988. }
  7989. return this._worldMatrix;
  7990. };
  7991. /**
  7992. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7993. * @param func: callback function to add
  7994. */
  7995. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7996. this._onAfterWorldMatrixUpdate.push(func);
  7997. };
  7998. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7999. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8000. if (index > -1) {
  8001. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8002. }
  8003. };
  8004. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8005. this.computeWorldMatrix();
  8006. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8007. };
  8008. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8009. this.computeWorldMatrix();
  8010. var invLocalWorldMatrix = this._localWorld.clone();
  8011. invLocalWorldMatrix.invert();
  8012. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8013. };
  8014. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8015. this.computeWorldMatrix(true);
  8016. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8017. };
  8018. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8019. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8020. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8021. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8022. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8023. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8024. /// <returns>Mesh oriented towards targetMesh</returns>
  8025. yawCor = yawCor || 0; // default to zero if undefined
  8026. pitchCor = pitchCor || 0;
  8027. rollCor = rollCor || 0;
  8028. var dv = targetPoint.subtract(this.position);
  8029. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8030. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8031. var pitch = Math.atan2(dv.y, len);
  8032. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8033. };
  8034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8035. return this._boundingInfo.isInFrustum(frustumPlanes);
  8036. };
  8037. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8038. if (!camera) {
  8039. camera = this.getScene().activeCamera;
  8040. }
  8041. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8042. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8043. return false;
  8044. }
  8045. return true;
  8046. };
  8047. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8048. if (!this._boundingInfo || !mesh._boundingInfo) {
  8049. return false;
  8050. }
  8051. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8052. };
  8053. AbstractMesh.prototype.intersectsPoint = function (point) {
  8054. if (!this._boundingInfo) {
  8055. return false;
  8056. }
  8057. return this._boundingInfo.intersectsPoint(point);
  8058. };
  8059. // Physics
  8060. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8061. var physicsEngine = this.getScene().getPhysicsEngine();
  8062. if (!physicsEngine) {
  8063. return;
  8064. }
  8065. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8066. if (impostor.impostor) {
  8067. // Old API
  8068. options = impostor;
  8069. impostor = impostor.impostor;
  8070. }
  8071. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8072. physicsEngine._unregisterMesh(this);
  8073. return;
  8074. }
  8075. if (!options) {
  8076. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8077. }
  8078. else {
  8079. if (!options.mass && options.mass !== 0)
  8080. options.mass = 0;
  8081. if (!options.friction && options.friction !== 0)
  8082. options.friction = 0.2;
  8083. if (!options.restitution && options.restitution !== 0)
  8084. options.restitution = 0.2;
  8085. }
  8086. this._physicImpostor = impostor;
  8087. this._physicsMass = options.mass;
  8088. this._physicsFriction = options.friction;
  8089. this._physicRestitution = options.restitution;
  8090. return physicsEngine._registerMesh(this, impostor, options);
  8091. };
  8092. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8093. if (!this._physicImpostor) {
  8094. return BABYLON.PhysicsEngine.NoImpostor;
  8095. }
  8096. return this._physicImpostor;
  8097. };
  8098. AbstractMesh.prototype.getPhysicsMass = function () {
  8099. if (!this._physicsMass) {
  8100. return 0;
  8101. }
  8102. return this._physicsMass;
  8103. };
  8104. AbstractMesh.prototype.getPhysicsFriction = function () {
  8105. if (!this._physicsFriction) {
  8106. return 0;
  8107. }
  8108. return this._physicsFriction;
  8109. };
  8110. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8111. if (!this._physicRestitution) {
  8112. return 0;
  8113. }
  8114. return this._physicRestitution;
  8115. };
  8116. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8117. if (!camera) {
  8118. camera = this.getScene().activeCamera;
  8119. }
  8120. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8121. };
  8122. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8123. if (!camera) {
  8124. camera = this.getScene().activeCamera;
  8125. }
  8126. return this.absolutePosition.subtract(camera.position).length();
  8127. };
  8128. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8129. if (!this._physicImpostor) {
  8130. return;
  8131. }
  8132. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8133. };
  8134. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8135. if (!this._physicImpostor) {
  8136. return;
  8137. }
  8138. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8139. };
  8140. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8141. if (!this._physicImpostor) {
  8142. return;
  8143. }
  8144. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8145. };
  8146. // Collisions
  8147. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8148. var globalPosition = this.getAbsolutePosition();
  8149. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8150. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8151. this._collider.radius = this.ellipsoid;
  8152. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8153. };
  8154. // Submeshes octree
  8155. /**
  8156. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8157. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8158. */
  8159. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8160. if (maxCapacity === void 0) { maxCapacity = 64; }
  8161. if (maxDepth === void 0) { maxDepth = 2; }
  8162. if (!this._submeshesOctree) {
  8163. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8164. }
  8165. this.computeWorldMatrix(true);
  8166. // Update octree
  8167. var bbox = this.getBoundingInfo().boundingBox;
  8168. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8169. return this._submeshesOctree;
  8170. };
  8171. // Collisions
  8172. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8173. this._generatePointsArray();
  8174. // Transformation
  8175. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8176. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8177. subMesh._lastColliderWorldVertices = [];
  8178. subMesh._trianglePlanes = [];
  8179. var start = subMesh.verticesStart;
  8180. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8181. for (var i = start; i < end; i++) {
  8182. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8183. }
  8184. }
  8185. // Collide
  8186. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8187. if (collider.collisionFound) {
  8188. collider.collidedMesh = this;
  8189. }
  8190. };
  8191. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8192. var subMeshes;
  8193. var len;
  8194. // Octrees
  8195. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8196. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8197. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8198. len = intersections.length;
  8199. subMeshes = intersections.data;
  8200. }
  8201. else {
  8202. subMeshes = this.subMeshes;
  8203. len = subMeshes.length;
  8204. }
  8205. for (var index = 0; index < len; index++) {
  8206. var subMesh = subMeshes[index];
  8207. // Bounding test
  8208. if (len > 1 && !subMesh._checkCollision(collider))
  8209. continue;
  8210. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8211. }
  8212. };
  8213. AbstractMesh.prototype._checkCollision = function (collider) {
  8214. // Bounding box test
  8215. if (!this._boundingInfo._checkCollision(collider))
  8216. return;
  8217. // Transformation matrix
  8218. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8219. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8220. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8221. };
  8222. // Picking
  8223. AbstractMesh.prototype._generatePointsArray = function () {
  8224. return false;
  8225. };
  8226. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8227. var pickingInfo = new BABYLON.PickingInfo();
  8228. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8229. return pickingInfo;
  8230. }
  8231. if (!this._generatePointsArray()) {
  8232. return pickingInfo;
  8233. }
  8234. var intersectInfo = null;
  8235. // Octrees
  8236. var subMeshes;
  8237. var len;
  8238. if (this._submeshesOctree && this.useOctreeForPicking) {
  8239. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8240. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8241. len = intersections.length;
  8242. subMeshes = intersections.data;
  8243. }
  8244. else {
  8245. subMeshes = this.subMeshes;
  8246. len = subMeshes.length;
  8247. }
  8248. for (var index = 0; index < len; index++) {
  8249. var subMesh = subMeshes[index];
  8250. // Bounding test
  8251. if (len > 1 && !subMesh.canIntersects(ray))
  8252. continue;
  8253. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8254. if (currentIntersectInfo) {
  8255. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8256. intersectInfo = currentIntersectInfo;
  8257. intersectInfo.subMeshId = index;
  8258. if (fastCheck) {
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (intersectInfo) {
  8265. // Get picked point
  8266. var world = this.getWorldMatrix();
  8267. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8268. var direction = ray.direction.clone();
  8269. direction = direction.scale(intersectInfo.distance);
  8270. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8271. var pickedPoint = worldOrigin.add(worldDirection);
  8272. // Return result
  8273. pickingInfo.hit = true;
  8274. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8275. pickingInfo.pickedPoint = pickedPoint;
  8276. pickingInfo.pickedMesh = this;
  8277. pickingInfo.bu = intersectInfo.bu;
  8278. pickingInfo.bv = intersectInfo.bv;
  8279. pickingInfo.faceId = intersectInfo.faceId;
  8280. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8281. return pickingInfo;
  8282. }
  8283. return pickingInfo;
  8284. };
  8285. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8286. return null;
  8287. };
  8288. AbstractMesh.prototype.releaseSubMeshes = function () {
  8289. if (this.subMeshes) {
  8290. while (this.subMeshes.length) {
  8291. this.subMeshes[0].dispose();
  8292. }
  8293. }
  8294. else {
  8295. this.subMeshes = new Array();
  8296. }
  8297. };
  8298. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8299. var index;
  8300. // Physics
  8301. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8302. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8303. }
  8304. // Intersections in progress
  8305. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8306. var other = this._intersectionsInProgress[index];
  8307. var pos = other._intersectionsInProgress.indexOf(this);
  8308. other._intersectionsInProgress.splice(pos, 1);
  8309. }
  8310. this._intersectionsInProgress = [];
  8311. // SubMeshes
  8312. this.releaseSubMeshes();
  8313. // Remove from scene
  8314. this.getScene().removeMesh(this);
  8315. if (!doNotRecurse) {
  8316. // Particles
  8317. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8318. if (this.getScene().particleSystems[index].emitter === this) {
  8319. this.getScene().particleSystems[index].dispose();
  8320. index--;
  8321. }
  8322. }
  8323. // Children
  8324. var objects = this.getScene().meshes.slice(0);
  8325. for (index = 0; index < objects.length; index++) {
  8326. if (objects[index].parent === this) {
  8327. objects[index].dispose();
  8328. }
  8329. }
  8330. }
  8331. else {
  8332. for (index = 0; index < this.getScene().meshes.length; index++) {
  8333. var obj = this.getScene().meshes[index];
  8334. if (obj.parent === this) {
  8335. obj.parent = null;
  8336. obj.computeWorldMatrix(true);
  8337. }
  8338. }
  8339. }
  8340. this._onAfterWorldMatrixUpdate = [];
  8341. this._isDisposed = true;
  8342. // Callback
  8343. if (this.onDispose) {
  8344. this.onDispose();
  8345. }
  8346. };
  8347. // Statics
  8348. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8349. AbstractMesh._BILLBOARDMODE_X = 1;
  8350. AbstractMesh._BILLBOARDMODE_Y = 2;
  8351. AbstractMesh._BILLBOARDMODE_Z = 4;
  8352. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8353. return AbstractMesh;
  8354. })(BABYLON.Node);
  8355. BABYLON.AbstractMesh = AbstractMesh;
  8356. })(BABYLON || (BABYLON = {}));
  8357. //# sourceMappingURL=babylon.abstractMesh.js.map
  8358. var __extends = this.__extends || function (d, b) {
  8359. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8360. function __() { this.constructor = d; }
  8361. __.prototype = b.prototype;
  8362. d.prototype = new __();
  8363. };
  8364. var BABYLON;
  8365. (function (BABYLON) {
  8366. var Light = (function (_super) {
  8367. __extends(Light, _super);
  8368. function Light(name, scene) {
  8369. _super.call(this, name, scene);
  8370. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8371. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8372. this.intensity = 1.0;
  8373. this.range = Number.MAX_VALUE;
  8374. this.includeOnlyWithLayerMask = 0;
  8375. this.includedOnlyMeshes = new Array();
  8376. this.excludedMeshes = new Array();
  8377. this.excludeWithLayerMask = 0;
  8378. this._excludedMeshesIds = new Array();
  8379. this._includedOnlyMeshesIds = new Array();
  8380. scene.addLight(this);
  8381. }
  8382. Light.prototype.getShadowGenerator = function () {
  8383. return this._shadowGenerator;
  8384. };
  8385. Light.prototype.getAbsolutePosition = function () {
  8386. return BABYLON.Vector3.Zero();
  8387. };
  8388. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8389. };
  8390. Light.prototype._getWorldMatrix = function () {
  8391. return BABYLON.Matrix.Identity();
  8392. };
  8393. Light.prototype.canAffectMesh = function (mesh) {
  8394. if (!mesh) {
  8395. return true;
  8396. }
  8397. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8398. return false;
  8399. }
  8400. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8401. return false;
  8402. }
  8403. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8404. return false;
  8405. }
  8406. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8407. return false;
  8408. }
  8409. return true;
  8410. };
  8411. Light.prototype.getWorldMatrix = function () {
  8412. this._currentRenderId = this.getScene().getRenderId();
  8413. var worldMatrix = this._getWorldMatrix();
  8414. if (this.parent && this.parent.getWorldMatrix) {
  8415. if (!this._parentedWorldMatrix) {
  8416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8417. }
  8418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8419. this._markSyncedWithParent();
  8420. return this._parentedWorldMatrix;
  8421. }
  8422. return worldMatrix;
  8423. };
  8424. Light.prototype.dispose = function () {
  8425. if (this._shadowGenerator) {
  8426. this._shadowGenerator.dispose();
  8427. this._shadowGenerator = null;
  8428. }
  8429. // Remove from scene
  8430. this.getScene().removeLight(this);
  8431. };
  8432. return Light;
  8433. })(BABYLON.Node);
  8434. BABYLON.Light = Light;
  8435. })(BABYLON || (BABYLON = {}));
  8436. //# sourceMappingURL=babylon.light.js.map
  8437. var __extends = this.__extends || function (d, b) {
  8438. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8439. function __() { this.constructor = d; }
  8440. __.prototype = b.prototype;
  8441. d.prototype = new __();
  8442. };
  8443. var BABYLON;
  8444. (function (BABYLON) {
  8445. var PointLight = (function (_super) {
  8446. __extends(PointLight, _super);
  8447. function PointLight(name, position, scene) {
  8448. _super.call(this, name, scene);
  8449. this.position = position;
  8450. }
  8451. PointLight.prototype.getAbsolutePosition = function () {
  8452. return this._transformedPosition ? this._transformedPosition : this.position;
  8453. };
  8454. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8455. if (this.parent && this.parent.getWorldMatrix) {
  8456. if (!this._transformedPosition) {
  8457. this._transformedPosition = BABYLON.Vector3.Zero();
  8458. }
  8459. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8460. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8461. return;
  8462. }
  8463. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8464. };
  8465. PointLight.prototype.getShadowGenerator = function () {
  8466. return null;
  8467. };
  8468. PointLight.prototype._getWorldMatrix = function () {
  8469. if (!this._worldMatrix) {
  8470. this._worldMatrix = BABYLON.Matrix.Identity();
  8471. }
  8472. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8473. return this._worldMatrix;
  8474. };
  8475. return PointLight;
  8476. })(BABYLON.Light);
  8477. BABYLON.PointLight = PointLight;
  8478. })(BABYLON || (BABYLON = {}));
  8479. //# sourceMappingURL=babylon.pointLight.js.map
  8480. var __extends = this.__extends || function (d, b) {
  8481. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8482. function __() { this.constructor = d; }
  8483. __.prototype = b.prototype;
  8484. d.prototype = new __();
  8485. };
  8486. var BABYLON;
  8487. (function (BABYLON) {
  8488. var SpotLight = (function (_super) {
  8489. __extends(SpotLight, _super);
  8490. function SpotLight(name, position, direction, angle, exponent, scene) {
  8491. _super.call(this, name, scene);
  8492. this.position = position;
  8493. this.direction = direction;
  8494. this.angle = angle;
  8495. this.exponent = exponent;
  8496. }
  8497. SpotLight.prototype.getAbsolutePosition = function () {
  8498. return this.transformedPosition ? this.transformedPosition : this.position;
  8499. };
  8500. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8501. var activeCamera = this.getScene().activeCamera;
  8502. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8503. };
  8504. SpotLight.prototype.supportsVSM = function () {
  8505. return true;
  8506. };
  8507. SpotLight.prototype.needRefreshPerFrame = function () {
  8508. return false;
  8509. };
  8510. SpotLight.prototype.setDirectionToTarget = function (target) {
  8511. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8512. return this.direction;
  8513. };
  8514. SpotLight.prototype.computeTransformedPosition = function () {
  8515. if (this.parent && this.parent.getWorldMatrix) {
  8516. if (!this.transformedPosition) {
  8517. this.transformedPosition = BABYLON.Vector3.Zero();
  8518. }
  8519. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8520. return true;
  8521. }
  8522. return false;
  8523. };
  8524. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8525. var normalizeDirection;
  8526. if (this.parent && this.parent.getWorldMatrix) {
  8527. if (!this._transformedDirection) {
  8528. this._transformedDirection = BABYLON.Vector3.Zero();
  8529. }
  8530. this.computeTransformedPosition();
  8531. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8533. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8534. }
  8535. else {
  8536. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8537. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8538. }
  8539. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8540. };
  8541. SpotLight.prototype._getWorldMatrix = function () {
  8542. if (!this._worldMatrix) {
  8543. this._worldMatrix = BABYLON.Matrix.Identity();
  8544. }
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8546. return this._worldMatrix;
  8547. };
  8548. return SpotLight;
  8549. })(BABYLON.Light);
  8550. BABYLON.SpotLight = SpotLight;
  8551. })(BABYLON || (BABYLON = {}));
  8552. //# sourceMappingURL=babylon.spotLight.js.map
  8553. var __extends = this.__extends || function (d, b) {
  8554. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8555. function __() { this.constructor = d; }
  8556. __.prototype = b.prototype;
  8557. d.prototype = new __();
  8558. };
  8559. var BABYLON;
  8560. (function (BABYLON) {
  8561. var HemisphericLight = (function (_super) {
  8562. __extends(HemisphericLight, _super);
  8563. function HemisphericLight(name, direction, scene) {
  8564. _super.call(this, name, scene);
  8565. this.direction = direction;
  8566. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8567. }
  8568. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8569. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8570. return this.direction;
  8571. };
  8572. HemisphericLight.prototype.getShadowGenerator = function () {
  8573. return null;
  8574. };
  8575. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8576. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8577. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8578. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8579. };
  8580. HemisphericLight.prototype._getWorldMatrix = function () {
  8581. if (!this._worldMatrix) {
  8582. this._worldMatrix = BABYLON.Matrix.Identity();
  8583. }
  8584. return this._worldMatrix;
  8585. };
  8586. return HemisphericLight;
  8587. })(BABYLON.Light);
  8588. BABYLON.HemisphericLight = HemisphericLight;
  8589. })(BABYLON || (BABYLON = {}));
  8590. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8591. var __extends = this.__extends || function (d, b) {
  8592. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8593. function __() { this.constructor = d; }
  8594. __.prototype = b.prototype;
  8595. d.prototype = new __();
  8596. };
  8597. var BABYLON;
  8598. (function (BABYLON) {
  8599. var DirectionalLight = (function (_super) {
  8600. __extends(DirectionalLight, _super);
  8601. function DirectionalLight(name, direction, scene) {
  8602. _super.call(this, name, scene);
  8603. this.direction = direction;
  8604. this.shadowOrthoScale = 0.5;
  8605. this.position = direction.scale(-1);
  8606. }
  8607. DirectionalLight.prototype.getAbsolutePosition = function () {
  8608. return this.transformedPosition ? this.transformedPosition : this.position;
  8609. };
  8610. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8611. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8612. return this.direction;
  8613. };
  8614. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8615. var orthoLeft = Number.MAX_VALUE;
  8616. var orthoRight = Number.MIN_VALUE;
  8617. var orthoTop = Number.MIN_VALUE;
  8618. var orthoBottom = Number.MAX_VALUE;
  8619. var tempVector3 = BABYLON.Vector3.Zero();
  8620. var activeCamera = this.getScene().activeCamera;
  8621. // Check extends
  8622. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8623. var mesh = renderList[meshIndex];
  8624. if (!mesh) {
  8625. continue;
  8626. }
  8627. var boundingInfo = mesh.getBoundingInfo();
  8628. if (!boundingInfo) {
  8629. continue;
  8630. }
  8631. var boundingBox = boundingInfo.boundingBox;
  8632. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8633. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8634. if (tempVector3.x < orthoLeft)
  8635. orthoLeft = tempVector3.x;
  8636. if (tempVector3.y < orthoBottom)
  8637. orthoBottom = tempVector3.y;
  8638. if (tempVector3.x > orthoRight)
  8639. orthoRight = tempVector3.x;
  8640. if (tempVector3.y > orthoTop)
  8641. orthoTop = tempVector3.y;
  8642. }
  8643. }
  8644. var xOffset = orthoRight - orthoLeft;
  8645. var yOffset = orthoTop - orthoBottom;
  8646. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8647. };
  8648. DirectionalLight.prototype.supportsVSM = function () {
  8649. return true;
  8650. };
  8651. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8652. return true;
  8653. };
  8654. DirectionalLight.prototype.computeTransformedPosition = function () {
  8655. if (this.parent && this.parent.getWorldMatrix) {
  8656. if (!this.transformedPosition) {
  8657. this.transformedPosition = BABYLON.Vector3.Zero();
  8658. }
  8659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8660. return true;
  8661. }
  8662. return false;
  8663. };
  8664. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8665. if (this.parent && this.parent.getWorldMatrix) {
  8666. if (!this._transformedDirection) {
  8667. this._transformedDirection = BABYLON.Vector3.Zero();
  8668. }
  8669. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8670. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8671. return;
  8672. }
  8673. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8674. };
  8675. DirectionalLight.prototype._getWorldMatrix = function () {
  8676. if (!this._worldMatrix) {
  8677. this._worldMatrix = BABYLON.Matrix.Identity();
  8678. }
  8679. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8680. return this._worldMatrix;
  8681. };
  8682. return DirectionalLight;
  8683. })(BABYLON.Light);
  8684. BABYLON.DirectionalLight = DirectionalLight;
  8685. })(BABYLON || (BABYLON = {}));
  8686. //# sourceMappingURL=babylon.directionalLight.js.map
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. var ShadowGenerator = (function () {
  8690. function ShadowGenerator(mapSize, light) {
  8691. var _this = this;
  8692. // Members
  8693. this._filter = ShadowGenerator.FILTER_NONE;
  8694. this.blurScale = 2;
  8695. this._blurBoxOffset = 0;
  8696. this._bias = 0.00005;
  8697. this._darkness = 0;
  8698. this._transparencyShadow = false;
  8699. this._viewMatrix = BABYLON.Matrix.Zero();
  8700. this._projectionMatrix = BABYLON.Matrix.Zero();
  8701. this._transformMatrix = BABYLON.Matrix.Zero();
  8702. this._worldViewProjection = BABYLON.Matrix.Zero();
  8703. this._light = light;
  8704. this._scene = light.getScene();
  8705. this._mapSize = mapSize;
  8706. light._shadowGenerator = this;
  8707. // Render target
  8708. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8709. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8710. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8711. this._shadowMap.anisotropicFilteringLevel = 1;
  8712. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8713. this._shadowMap.renderParticles = false;
  8714. this._shadowMap.onAfterUnbind = function () {
  8715. if (!_this.useBlurVarianceShadowMap) {
  8716. return;
  8717. }
  8718. if (!_this._shadowMap2) {
  8719. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8720. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8721. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8722. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8723. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8724. _this._downSamplePostprocess.onApply = function (effect) {
  8725. effect.setTexture("textureSampler", _this._shadowMap);
  8726. };
  8727. _this.blurBoxOffset = 1;
  8728. }
  8729. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8730. };
  8731. // Custom render function
  8732. var renderSubMesh = function (subMesh) {
  8733. var mesh = subMesh.getRenderingMesh();
  8734. var scene = _this._scene;
  8735. var engine = scene.getEngine();
  8736. // Culling
  8737. engine.setState(subMesh.getMaterial().backFaceCulling);
  8738. // Managing instances
  8739. var batch = mesh._getInstancesRenderList(subMesh._id);
  8740. if (batch.mustReturn) {
  8741. return;
  8742. }
  8743. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8744. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8745. engine.enableEffect(_this._effect);
  8746. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8747. var material = subMesh.getMaterial();
  8748. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8749. // Alpha test
  8750. if (material && material.needAlphaTesting()) {
  8751. var alphaTexture = material.getAlphaTestTexture();
  8752. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8753. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8754. }
  8755. // Bones
  8756. if (mesh.useBones) {
  8757. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8758. }
  8759. // Draw
  8760. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8761. }
  8762. else {
  8763. // Need to reset refresh rate of the shadowMap
  8764. _this._shadowMap.resetRefreshCounter();
  8765. }
  8766. };
  8767. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8768. var index;
  8769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8770. renderSubMesh(opaqueSubMeshes.data[index]);
  8771. }
  8772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8773. renderSubMesh(alphaTestSubMeshes.data[index]);
  8774. }
  8775. if (_this._transparencyShadow) {
  8776. for (index = 0; index < transparentSubMeshes.length; index++) {
  8777. renderSubMesh(transparentSubMeshes.data[index]);
  8778. }
  8779. }
  8780. };
  8781. this._shadowMap.onClear = function (engine) {
  8782. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8783. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8784. }
  8785. else {
  8786. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8787. }
  8788. };
  8789. }
  8790. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8791. // Static
  8792. get: function () {
  8793. return ShadowGenerator._FILTER_NONE;
  8794. },
  8795. enumerable: true,
  8796. configurable: true
  8797. });
  8798. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8799. get: function () {
  8800. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8806. get: function () {
  8807. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8808. },
  8809. enumerable: true,
  8810. configurable: true
  8811. });
  8812. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8813. get: function () {
  8814. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8820. get: function () {
  8821. return this._bias;
  8822. },
  8823. set: function (bias) {
  8824. this._bias = bias;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8830. get: function () {
  8831. return this._blurBoxOffset;
  8832. },
  8833. set: function (value) {
  8834. var _this = this;
  8835. if (this._blurBoxOffset === value) {
  8836. return;
  8837. }
  8838. this._blurBoxOffset = value;
  8839. if (this._boxBlurPostprocess) {
  8840. this._boxBlurPostprocess.dispose();
  8841. }
  8842. 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);
  8843. this._boxBlurPostprocess.onApply = function (effect) {
  8844. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8845. };
  8846. },
  8847. enumerable: true,
  8848. configurable: true
  8849. });
  8850. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8851. get: function () {
  8852. return this._filter;
  8853. },
  8854. set: function (value) {
  8855. if (this._filter === value) {
  8856. return;
  8857. }
  8858. this._filter = value;
  8859. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8860. this._shadowMap.anisotropicFilteringLevel = 16;
  8861. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8862. }
  8863. else {
  8864. this._shadowMap.anisotropicFilteringLevel = 1;
  8865. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8866. }
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8872. get: function () {
  8873. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8874. },
  8875. set: function (value) {
  8876. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8882. get: function () {
  8883. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8884. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8885. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8886. },
  8887. set: function (value) {
  8888. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8894. get: function () {
  8895. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8896. },
  8897. set: function (value) {
  8898. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8899. },
  8900. enumerable: true,
  8901. configurable: true
  8902. });
  8903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8904. var defines = [];
  8905. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8906. defines.push("#define VSM");
  8907. }
  8908. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8909. var mesh = subMesh.getMesh();
  8910. var material = subMesh.getMaterial();
  8911. // Alpha test
  8912. if (material && material.needAlphaTesting()) {
  8913. defines.push("#define ALPHATEST");
  8914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8915. attribs.push(BABYLON.VertexBuffer.UVKind);
  8916. defines.push("#define UV1");
  8917. }
  8918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8919. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8920. defines.push("#define UV2");
  8921. }
  8922. }
  8923. // Bones
  8924. if (mesh.useBones) {
  8925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8927. defines.push("#define BONES");
  8928. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8929. }
  8930. // Instances
  8931. if (useInstances) {
  8932. defines.push("#define INSTANCES");
  8933. attribs.push("world0");
  8934. attribs.push("world1");
  8935. attribs.push("world2");
  8936. attribs.push("world3");
  8937. }
  8938. // Get correct effect
  8939. var join = defines.join("\n");
  8940. if (this._cachedDefines !== join) {
  8941. this._cachedDefines = join;
  8942. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8943. }
  8944. return this._effect.isReady();
  8945. };
  8946. ShadowGenerator.prototype.getShadowMap = function () {
  8947. return this._shadowMap;
  8948. };
  8949. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8950. if (this._shadowMap2) {
  8951. return this._shadowMap2;
  8952. }
  8953. return this._shadowMap;
  8954. };
  8955. ShadowGenerator.prototype.getLight = function () {
  8956. return this._light;
  8957. };
  8958. // Methods
  8959. ShadowGenerator.prototype.getTransformMatrix = function () {
  8960. var scene = this._scene;
  8961. if (this._currentRenderID === scene.getRenderId()) {
  8962. return this._transformMatrix;
  8963. }
  8964. this._currentRenderID = scene.getRenderId();
  8965. var lightPosition = this._light.position;
  8966. var lightDirection = this._light.direction;
  8967. if (this._light.computeTransformedPosition()) {
  8968. lightPosition = this._light.transformedPosition;
  8969. }
  8970. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8971. this._cachedPosition = lightPosition.clone();
  8972. this._cachedDirection = lightDirection.clone();
  8973. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8974. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8975. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8976. }
  8977. return this._transformMatrix;
  8978. };
  8979. ShadowGenerator.prototype.getDarkness = function () {
  8980. return this._darkness;
  8981. };
  8982. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8983. if (darkness >= 1.0)
  8984. this._darkness = 1.0;
  8985. else if (darkness <= 0.0)
  8986. this._darkness = 0.0;
  8987. else
  8988. this._darkness = darkness;
  8989. };
  8990. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8991. this._transparencyShadow = hasShadow;
  8992. };
  8993. ShadowGenerator.prototype._packHalf = function (depth) {
  8994. var scale = depth * 255.0;
  8995. var fract = scale - Math.floor(scale);
  8996. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8997. };
  8998. ShadowGenerator.prototype.dispose = function () {
  8999. this._shadowMap.dispose();
  9000. if (this._shadowMap2) {
  9001. this._shadowMap2.dispose();
  9002. }
  9003. if (this._downSamplePostprocess) {
  9004. this._downSamplePostprocess.dispose();
  9005. }
  9006. if (this._boxBlurPostprocess) {
  9007. this._boxBlurPostprocess.dispose();
  9008. }
  9009. };
  9010. ShadowGenerator._FILTER_NONE = 0;
  9011. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9012. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9013. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9014. return ShadowGenerator;
  9015. })();
  9016. BABYLON.ShadowGenerator = ShadowGenerator;
  9017. })(BABYLON || (BABYLON = {}));
  9018. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9019. var BABYLON;
  9020. (function (BABYLON) {
  9021. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9022. if (boxMin.x > sphereCenter.x + sphereRadius)
  9023. return false;
  9024. if (sphereCenter.x - sphereRadius > boxMax.x)
  9025. return false;
  9026. if (boxMin.y > sphereCenter.y + sphereRadius)
  9027. return false;
  9028. if (sphereCenter.y - sphereRadius > boxMax.y)
  9029. return false;
  9030. if (boxMin.z > sphereCenter.z + sphereRadius)
  9031. return false;
  9032. if (sphereCenter.z - sphereRadius > boxMax.z)
  9033. return false;
  9034. return true;
  9035. };
  9036. var getLowestRoot = function (a, b, c, maxR) {
  9037. var determinant = b * b - 4.0 * a * c;
  9038. var result = { root: 0, found: false };
  9039. if (determinant < 0)
  9040. return result;
  9041. var sqrtD = Math.sqrt(determinant);
  9042. var r1 = (-b - sqrtD) / (2.0 * a);
  9043. var r2 = (-b + sqrtD) / (2.0 * a);
  9044. if (r1 > r2) {
  9045. var temp = r2;
  9046. r2 = r1;
  9047. r1 = temp;
  9048. }
  9049. if (r1 > 0 && r1 < maxR) {
  9050. result.root = r1;
  9051. result.found = true;
  9052. return result;
  9053. }
  9054. if (r2 > 0 && r2 < maxR) {
  9055. result.root = r2;
  9056. result.found = true;
  9057. return result;
  9058. }
  9059. return result;
  9060. };
  9061. var Collider = (function () {
  9062. function Collider() {
  9063. this.radius = new BABYLON.Vector3(1, 1, 1);
  9064. this.retry = 0;
  9065. this.basePointWorld = BABYLON.Vector3.Zero();
  9066. this.velocityWorld = BABYLON.Vector3.Zero();
  9067. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9068. this._collisionPoint = BABYLON.Vector3.Zero();
  9069. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9070. this._tempVector = BABYLON.Vector3.Zero();
  9071. this._tempVector2 = BABYLON.Vector3.Zero();
  9072. this._tempVector3 = BABYLON.Vector3.Zero();
  9073. this._tempVector4 = BABYLON.Vector3.Zero();
  9074. this._edge = BABYLON.Vector3.Zero();
  9075. this._baseToVertex = BABYLON.Vector3.Zero();
  9076. this._destinationPoint = BABYLON.Vector3.Zero();
  9077. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9078. this._displacementVector = BABYLON.Vector3.Zero();
  9079. }
  9080. // Methods
  9081. Collider.prototype._initialize = function (source, dir, e) {
  9082. this.velocity = dir;
  9083. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9084. this.basePoint = source;
  9085. source.multiplyToRef(this.radius, this.basePointWorld);
  9086. dir.multiplyToRef(this.radius, this.velocityWorld);
  9087. this.velocityWorldLength = this.velocityWorld.length();
  9088. this.epsilon = e;
  9089. this.collisionFound = false;
  9090. };
  9091. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9092. pa.subtractToRef(point, this._tempVector);
  9093. pb.subtractToRef(point, this._tempVector2);
  9094. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9095. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9096. if (d < 0)
  9097. return false;
  9098. pc.subtractToRef(point, this._tempVector3);
  9099. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9100. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9101. if (d < 0)
  9102. return false;
  9103. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9104. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9105. return d >= 0;
  9106. };
  9107. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9108. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9109. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9110. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9111. return false;
  9112. }
  9113. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9114. return false;
  9115. return true;
  9116. };
  9117. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9118. var t0;
  9119. var embeddedInPlane = false;
  9120. //defensive programming, actually not needed.
  9121. if (!trianglePlaneArray) {
  9122. trianglePlaneArray = [];
  9123. }
  9124. if (!trianglePlaneArray[faceIndex]) {
  9125. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9126. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9127. }
  9128. var trianglePlane = trianglePlaneArray[faceIndex];
  9129. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9130. return;
  9131. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9132. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9133. if (normalDotVelocity == 0) {
  9134. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9135. return;
  9136. embeddedInPlane = true;
  9137. t0 = 0;
  9138. }
  9139. else {
  9140. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9141. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9142. if (t0 > t1) {
  9143. var temp = t1;
  9144. t1 = t0;
  9145. t0 = temp;
  9146. }
  9147. if (t0 > 1.0 || t1 < 0.0)
  9148. return;
  9149. if (t0 < 0)
  9150. t0 = 0;
  9151. if (t0 > 1.0)
  9152. t0 = 1.0;
  9153. }
  9154. this._collisionPoint.copyFromFloats(0, 0, 0);
  9155. var found = false;
  9156. var t = 1.0;
  9157. if (!embeddedInPlane) {
  9158. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9159. this.velocity.scaleToRef(t0, this._tempVector);
  9160. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9161. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9162. found = true;
  9163. t = t0;
  9164. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9165. }
  9166. }
  9167. if (!found) {
  9168. var velocitySquaredLength = this.velocity.lengthSquared();
  9169. var a = velocitySquaredLength;
  9170. this.basePoint.subtractToRef(p1, this._tempVector);
  9171. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9172. var c = this._tempVector.lengthSquared() - 1.0;
  9173. var lowestRoot = getLowestRoot(a, b, c, t);
  9174. if (lowestRoot.found) {
  9175. t = lowestRoot.root;
  9176. found = true;
  9177. this._collisionPoint.copyFrom(p1);
  9178. }
  9179. this.basePoint.subtractToRef(p2, this._tempVector);
  9180. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9181. c = this._tempVector.lengthSquared() - 1.0;
  9182. lowestRoot = getLowestRoot(a, b, c, t);
  9183. if (lowestRoot.found) {
  9184. t = lowestRoot.root;
  9185. found = true;
  9186. this._collisionPoint.copyFrom(p2);
  9187. }
  9188. this.basePoint.subtractToRef(p3, this._tempVector);
  9189. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9190. c = this._tempVector.lengthSquared() - 1.0;
  9191. lowestRoot = getLowestRoot(a, b, c, t);
  9192. if (lowestRoot.found) {
  9193. t = lowestRoot.root;
  9194. found = true;
  9195. this._collisionPoint.copyFrom(p3);
  9196. }
  9197. p2.subtractToRef(p1, this._edge);
  9198. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9199. var edgeSquaredLength = this._edge.lengthSquared();
  9200. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9201. var 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. var 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. p1.addToRef(this._edge, this._collisionPoint);
  9213. }
  9214. }
  9215. p3.subtractToRef(p2, this._edge);
  9216. p2.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. p2.addToRef(this._edge, this._collisionPoint);
  9231. }
  9232. }
  9233. p1.subtractToRef(p3, this._edge);
  9234. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9235. edgeSquaredLength = this._edge.lengthSquared();
  9236. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9237. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9238. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9239. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9240. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9241. lowestRoot = getLowestRoot(a, b, c, t);
  9242. if (lowestRoot.found) {
  9243. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9244. if (f >= 0.0 && f <= 1.0) {
  9245. t = lowestRoot.root;
  9246. found = true;
  9247. this._edge.scaleInPlace(f);
  9248. p3.addToRef(this._edge, this._collisionPoint);
  9249. }
  9250. }
  9251. }
  9252. if (found) {
  9253. var distToCollision = t * this.velocity.length();
  9254. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9255. if (!this.intersectionPoint) {
  9256. this.intersectionPoint = this._collisionPoint.clone();
  9257. }
  9258. else {
  9259. this.intersectionPoint.copyFrom(this._collisionPoint);
  9260. }
  9261. this.nearestDistance = distToCollision;
  9262. this.collisionFound = true;
  9263. }
  9264. }
  9265. };
  9266. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9267. for (var i = indexStart; i < indexEnd; i += 3) {
  9268. var p1 = pts[indices[i] - decal];
  9269. var p2 = pts[indices[i + 1] - decal];
  9270. var p3 = pts[indices[i + 2] - decal];
  9271. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9272. }
  9273. };
  9274. Collider.prototype._getResponse = function (pos, vel) {
  9275. pos.addToRef(vel, this._destinationPoint);
  9276. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9277. this.basePoint.addToRef(vel, pos);
  9278. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9279. this._slidePlaneNormal.normalize();
  9280. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9281. pos.addInPlace(this._displacementVector);
  9282. this.intersectionPoint.addInPlace(this._displacementVector);
  9283. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9284. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9285. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9286. };
  9287. return Collider;
  9288. })();
  9289. BABYLON.Collider = Collider;
  9290. })(BABYLON || (BABYLON = {}));
  9291. //# sourceMappingURL=babylon.collider.js.map
  9292. var BABYLON;
  9293. (function (BABYLON) {
  9294. //WebWorker code will be inserted to this variable.
  9295. BABYLON.CollisionWorker = "";
  9296. (function (WorkerTaskType) {
  9297. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9298. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9299. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9300. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9301. var WorkerTaskType = BABYLON.WorkerTaskType;
  9302. (function (WorkerReplyType) {
  9303. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9304. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9305. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9306. var WorkerReplyType = BABYLON.WorkerReplyType;
  9307. var CollisionCoordinatorWorker = (function () {
  9308. function CollisionCoordinatorWorker() {
  9309. var _this = this;
  9310. this._scaledPosition = BABYLON.Vector3.Zero();
  9311. this._scaledVelocity = BABYLON.Vector3.Zero();
  9312. this.onMeshUpdated = function (mesh) {
  9313. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9314. };
  9315. this.onGeometryUpdated = function (geometry) {
  9316. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9317. };
  9318. this._afterRender = function () {
  9319. if (!_this._init)
  9320. return;
  9321. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9322. return;
  9323. }
  9324. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9325. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9326. if (_this._runningUpdated > 4) {
  9327. return;
  9328. }
  9329. ++_this._runningUpdated;
  9330. var payload = {
  9331. updatedMeshes: _this._addUpdateMeshesList,
  9332. updatedGeometries: _this._addUpdateGeometriesList,
  9333. removedGeometries: _this._toRemoveGeometryArray,
  9334. removedMeshes: _this._toRemoveMeshesArray
  9335. };
  9336. var message = {
  9337. payload: payload,
  9338. taskType: WorkerTaskType.UPDATE
  9339. };
  9340. var serializable = [];
  9341. for (var id in payload.updatedGeometries) {
  9342. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9343. //prepare transferables
  9344. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9345. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9346. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9347. }
  9348. }
  9349. _this._worker.postMessage(message, serializable);
  9350. _this._addUpdateMeshesList = {};
  9351. _this._addUpdateGeometriesList = {};
  9352. _this._toRemoveGeometryArray = [];
  9353. _this._toRemoveMeshesArray = [];
  9354. };
  9355. this._onMessageFromWorker = function (e) {
  9356. var returnData = e.data;
  9357. if (returnData.error != WorkerReplyType.SUCCESS) {
  9358. //TODO what errors can be returned from the worker?
  9359. BABYLON.Tools.Warn("error returned from worker!");
  9360. return;
  9361. }
  9362. switch (returnData.taskType) {
  9363. case WorkerTaskType.INIT:
  9364. _this._init = true;
  9365. //Update the worked with ALL of the scene's current state
  9366. _this._scene.meshes.forEach(function (mesh) {
  9367. _this.onMeshAdded(mesh);
  9368. });
  9369. _this._scene.getGeometries().forEach(function (geometry) {
  9370. _this.onGeometryAdded(geometry);
  9371. });
  9372. break;
  9373. case WorkerTaskType.UPDATE:
  9374. _this._runningUpdated--;
  9375. break;
  9376. case WorkerTaskType.COLLIDE:
  9377. _this._runningCollisionTask = false;
  9378. var returnPayload = returnData.payload;
  9379. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9380. return;
  9381. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9382. //cleanup
  9383. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9384. break;
  9385. }
  9386. };
  9387. this._collisionsCallbackArray = [];
  9388. this._init = false;
  9389. this._runningUpdated = 0;
  9390. this._runningCollisionTask = false;
  9391. this._addUpdateMeshesList = {};
  9392. this._addUpdateGeometriesList = {};
  9393. this._toRemoveGeometryArray = [];
  9394. this._toRemoveMeshesArray = [];
  9395. }
  9396. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9397. if (!this._init)
  9398. return;
  9399. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9400. return;
  9401. position.divideToRef(collider.radius, this._scaledPosition);
  9402. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9403. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9404. var payload = {
  9405. collider: {
  9406. position: this._scaledPosition.asArray(),
  9407. velocity: this._scaledVelocity.asArray(),
  9408. radius: collider.radius.asArray()
  9409. },
  9410. collisionId: collisionIndex,
  9411. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9412. maximumRetry: maximumRetry
  9413. };
  9414. var message = {
  9415. payload: payload,
  9416. taskType: WorkerTaskType.COLLIDE
  9417. };
  9418. this._worker.postMessage(message);
  9419. };
  9420. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9421. this._scene = scene;
  9422. this._scene.registerAfterRender(this._afterRender);
  9423. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9424. this._worker = new Worker(workerUrl);
  9425. this._worker.onmessage = this._onMessageFromWorker;
  9426. var message = {
  9427. payload: {},
  9428. taskType: WorkerTaskType.INIT
  9429. };
  9430. this._worker.postMessage(message);
  9431. };
  9432. CollisionCoordinatorWorker.prototype.destroy = function () {
  9433. this._scene.unregisterAfterRender(this._afterRender);
  9434. this._worker.terminate();
  9435. };
  9436. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9437. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9438. this.onMeshUpdated(mesh);
  9439. };
  9440. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9441. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9442. };
  9443. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9444. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9445. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9446. this.onGeometryUpdated(geometry);
  9447. };
  9448. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9449. this._toRemoveGeometryArray.push(geometry.id);
  9450. };
  9451. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9452. var submeshes = [];
  9453. if (mesh.subMeshes) {
  9454. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9455. return {
  9456. position: idx,
  9457. verticesStart: sm.verticesStart,
  9458. verticesCount: sm.verticesCount,
  9459. indexStart: sm.indexStart,
  9460. indexCount: sm.indexCount,
  9461. hasMaterial: !!sm.getMaterial(),
  9462. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9463. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9464. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9465. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9466. };
  9467. });
  9468. }
  9469. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9470. return {
  9471. uniqueId: mesh.uniqueId,
  9472. id: mesh.id,
  9473. name: mesh.name,
  9474. geometryId: geometryId,
  9475. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9476. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9477. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9478. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9480. subMeshes: submeshes,
  9481. checkCollisions: mesh.checkCollisions
  9482. };
  9483. };
  9484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9485. return {
  9486. id: geometry.id,
  9487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9489. indices: new Int32Array(geometry.getIndices() || []),
  9490. };
  9491. };
  9492. return CollisionCoordinatorWorker;
  9493. })();
  9494. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9495. var CollisionCoordinatorLegacy = (function () {
  9496. function CollisionCoordinatorLegacy() {
  9497. this._scaledPosition = BABYLON.Vector3.Zero();
  9498. this._scaledVelocity = BABYLON.Vector3.Zero();
  9499. this._finalPosition = BABYLON.Vector3.Zero();
  9500. }
  9501. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9502. position.divideToRef(collider.radius, this._scaledPosition);
  9503. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9504. collider.retry = 0;
  9505. collider.initialVelocity = this._scaledVelocity;
  9506. collider.initialPosition = this._scaledPosition;
  9507. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9508. this._finalPosition.multiplyInPlace(collider.radius);
  9509. //run the callback
  9510. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9511. };
  9512. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9513. this._scene = scene;
  9514. };
  9515. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9516. //Legacy need no destruction method.
  9517. };
  9518. //No update in legacy mode
  9519. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9520. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9521. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9522. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9523. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9524. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9525. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9526. if (excludedMesh === void 0) { excludedMesh = null; }
  9527. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9528. if (collider.retry >= maximumRetry) {
  9529. finalPosition.copyFrom(position);
  9530. return;
  9531. }
  9532. collider._initialize(position, velocity, closeDistance);
  9533. // Check all meshes
  9534. for (var index = 0; index < this._scene.meshes.length; index++) {
  9535. var mesh = this._scene.meshes[index];
  9536. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9537. mesh._checkCollision(collider);
  9538. }
  9539. }
  9540. if (!collider.collisionFound) {
  9541. position.addToRef(velocity, finalPosition);
  9542. return;
  9543. }
  9544. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9545. collider._getResponse(position, velocity);
  9546. }
  9547. if (velocity.length() <= closeDistance) {
  9548. finalPosition.copyFrom(position);
  9549. return;
  9550. }
  9551. collider.retry++;
  9552. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9553. };
  9554. return CollisionCoordinatorLegacy;
  9555. })();
  9556. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9557. })(BABYLON || (BABYLON = {}));
  9558. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9559. var __extends = this.__extends || function (d, b) {
  9560. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9561. function __() { this.constructor = d; }
  9562. __.prototype = b.prototype;
  9563. d.prototype = new __();
  9564. };
  9565. var BABYLON;
  9566. (function (BABYLON) {
  9567. var VRCameraMetrics = (function () {
  9568. function VRCameraMetrics() {
  9569. this.compensateDistorsion = true;
  9570. }
  9571. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9572. get: function () {
  9573. return this.hResolution / (2 * this.vResolution);
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9579. get: function () {
  9580. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9586. get: function () {
  9587. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9588. var h = (4 * meters) / this.hScreenSize;
  9589. return BABYLON.Matrix.Translation(h, 0, 0);
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9595. get: function () {
  9596. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9597. var h = (4 * meters) / this.hScreenSize;
  9598. return BABYLON.Matrix.Translation(-h, 0, 0);
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9604. get: function () {
  9605. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9611. get: function () {
  9612. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. VRCameraMetrics.GetDefault = function () {
  9618. var result = new VRCameraMetrics();
  9619. result.hResolution = 1280;
  9620. result.vResolution = 800;
  9621. result.hScreenSize = 0.149759993;
  9622. result.vScreenSize = 0.0935999975;
  9623. result.vScreenCenter = 0.0467999987,
  9624. result.eyeToScreenDistance = 0.0410000011;
  9625. result.lensSeparationDistance = 0.0635000020;
  9626. result.interpupillaryDistance = 0.0640000030;
  9627. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9628. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9629. result.postProcessScaleFactor = 1.714605507808412;
  9630. result.lensCenterOffset = 0.151976421;
  9631. return result;
  9632. };
  9633. return VRCameraMetrics;
  9634. })();
  9635. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9636. var Camera = (function (_super) {
  9637. __extends(Camera, _super);
  9638. function Camera(name, position, scene) {
  9639. _super.call(this, name, scene);
  9640. this.position = position;
  9641. // Members
  9642. this.upVector = BABYLON.Vector3.Up();
  9643. this.orthoLeft = null;
  9644. this.orthoRight = null;
  9645. this.orthoBottom = null;
  9646. this.orthoTop = null;
  9647. this.fov = 0.8;
  9648. this.minZ = 1.0;
  9649. this.maxZ = 10000.0;
  9650. this.inertia = 0.9;
  9651. this.mode = Camera.PERSPECTIVE_CAMERA;
  9652. this.isIntermediate = false;
  9653. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9654. this.layerMask = 0x0FFFFFFF;
  9655. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9656. // Subcamera members
  9657. this.subCameras = new Array();
  9658. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9659. // Cache
  9660. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9661. this._projectionMatrix = new BABYLON.Matrix();
  9662. this._postProcesses = new Array();
  9663. this._postProcessesTakenIndices = [];
  9664. this._activeMeshes = new BABYLON.SmartArray(256);
  9665. this._globalPosition = BABYLON.Vector3.Zero();
  9666. scene.addCamera(this);
  9667. if (!scene.activeCamera) {
  9668. scene.activeCamera = this;
  9669. }
  9670. }
  9671. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9672. get: function () {
  9673. return Camera._PERSPECTIVE_CAMERA;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9679. get: function () {
  9680. return Camera._ORTHOGRAPHIC_CAMERA;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9686. get: function () {
  9687. return Camera._FOVMODE_VERTICAL_FIXED;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9693. get: function () {
  9694. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9700. get: function () {
  9701. return Camera._SUB_CAMERA_MODE_NONE;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9707. get: function () {
  9708. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Camera, "SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM", {
  9714. get: function () {
  9715. return Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VERTICAL_STEREOGRAM", {
  9721. get: function () {
  9722. return Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9728. get: function () {
  9729. return Camera._SUB_CAMERA_MODE_VR;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9735. get: function () {
  9736. return Camera._SUB_CAMERAID_A;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9742. get: function () {
  9743. return Camera._SUB_CAMERAID_B;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(Camera.prototype, "globalPosition", {
  9749. get: function () {
  9750. return this._globalPosition;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Camera.prototype.getActiveMeshes = function () {
  9756. return this._activeMeshes;
  9757. };
  9758. Camera.prototype.isActiveMesh = function (mesh) {
  9759. return (this._activeMeshes.indexOf(mesh) !== -1);
  9760. };
  9761. //Cache
  9762. Camera.prototype._initCache = function () {
  9763. _super.prototype._initCache.call(this);
  9764. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9765. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9766. this._cache.mode = undefined;
  9767. this._cache.minZ = undefined;
  9768. this._cache.maxZ = undefined;
  9769. this._cache.fov = undefined;
  9770. this._cache.aspectRatio = undefined;
  9771. this._cache.orthoLeft = undefined;
  9772. this._cache.orthoRight = undefined;
  9773. this._cache.orthoBottom = undefined;
  9774. this._cache.orthoTop = undefined;
  9775. this._cache.renderWidth = undefined;
  9776. this._cache.renderHeight = undefined;
  9777. };
  9778. Camera.prototype._updateCache = function (ignoreParentClass) {
  9779. if (!ignoreParentClass) {
  9780. _super.prototype._updateCache.call(this);
  9781. }
  9782. var engine = this.getEngine();
  9783. this._cache.position.copyFrom(this.position);
  9784. this._cache.upVector.copyFrom(this.upVector);
  9785. this._cache.mode = this.mode;
  9786. this._cache.minZ = this.minZ;
  9787. this._cache.maxZ = this.maxZ;
  9788. this._cache.fov = this.fov;
  9789. this._cache.aspectRatio = engine.getAspectRatio(this);
  9790. this._cache.orthoLeft = this.orthoLeft;
  9791. this._cache.orthoRight = this.orthoRight;
  9792. this._cache.orthoBottom = this.orthoBottom;
  9793. this._cache.orthoTop = this.orthoTop;
  9794. this._cache.renderWidth = engine.getRenderWidth();
  9795. this._cache.renderHeight = engine.getRenderHeight();
  9796. };
  9797. Camera.prototype._updateFromScene = function () {
  9798. this.updateCache();
  9799. this._update();
  9800. };
  9801. // Synchronized
  9802. Camera.prototype._isSynchronized = function () {
  9803. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9804. };
  9805. Camera.prototype._isSynchronizedViewMatrix = function () {
  9806. if (!_super.prototype._isSynchronized.call(this))
  9807. return false;
  9808. return this._cache.position.equals(this.position)
  9809. && this._cache.upVector.equals(this.upVector)
  9810. && this.isSynchronizedWithParent();
  9811. };
  9812. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9813. var check = this._cache.mode === this.mode
  9814. && this._cache.minZ === this.minZ
  9815. && this._cache.maxZ === this.maxZ;
  9816. if (!check) {
  9817. return false;
  9818. }
  9819. var engine = this.getEngine();
  9820. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9821. check = this._cache.fov === this.fov
  9822. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9823. }
  9824. else {
  9825. check = this._cache.orthoLeft === this.orthoLeft
  9826. && this._cache.orthoRight === this.orthoRight
  9827. && this._cache.orthoBottom === this.orthoBottom
  9828. && this._cache.orthoTop === this.orthoTop
  9829. && this._cache.renderWidth === engine.getRenderWidth()
  9830. && this._cache.renderHeight === engine.getRenderHeight();
  9831. }
  9832. return check;
  9833. };
  9834. // Controls
  9835. Camera.prototype.attachControl = function (element) {
  9836. };
  9837. Camera.prototype.detachControl = function (element) {
  9838. };
  9839. Camera.prototype._update = function () {
  9840. this._checkInputs();
  9841. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9842. this._updateSubCameras();
  9843. }
  9844. };
  9845. Camera.prototype._checkInputs = function () {
  9846. };
  9847. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9848. if (insertAt === void 0) { insertAt = null; }
  9849. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9850. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9851. return 0;
  9852. }
  9853. if (insertAt == null || insertAt < 0) {
  9854. this._postProcesses.push(postProcess);
  9855. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9856. return this._postProcesses.length - 1;
  9857. }
  9858. var add = 0;
  9859. if (this._postProcesses[insertAt]) {
  9860. var start = this._postProcesses.length - 1;
  9861. for (var i = start; i >= insertAt + 1; --i) {
  9862. this._postProcesses[i + 1] = this._postProcesses[i];
  9863. }
  9864. add = 1;
  9865. }
  9866. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9867. if (this._postProcessesTakenIndices[i] < insertAt) {
  9868. continue;
  9869. }
  9870. start = this._postProcessesTakenIndices.length - 1;
  9871. for (var j = start; j >= i; --j) {
  9872. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9873. }
  9874. this._postProcessesTakenIndices[i] = insertAt;
  9875. break;
  9876. }
  9877. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9878. this._postProcessesTakenIndices.push(insertAt);
  9879. }
  9880. var result = insertAt + add;
  9881. this._postProcesses[result] = postProcess;
  9882. return result;
  9883. };
  9884. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9885. if (atIndices === void 0) { atIndices = null; }
  9886. var result = [];
  9887. if (!atIndices) {
  9888. var length = this._postProcesses.length;
  9889. for (var i = 0; i < length; i++) {
  9890. if (this._postProcesses[i] !== postProcess) {
  9891. continue;
  9892. }
  9893. delete this._postProcesses[i];
  9894. var index = this._postProcessesTakenIndices.indexOf(i);
  9895. this._postProcessesTakenIndices.splice(index, 1);
  9896. }
  9897. }
  9898. else {
  9899. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9900. for (i = 0; i < atIndices.length; i++) {
  9901. var foundPostProcess = this._postProcesses[atIndices[i]];
  9902. if (foundPostProcess !== postProcess) {
  9903. result.push(i);
  9904. continue;
  9905. }
  9906. delete this._postProcesses[atIndices[i]];
  9907. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9908. this._postProcessesTakenIndices.splice(index, 1);
  9909. }
  9910. }
  9911. return result;
  9912. };
  9913. Camera.prototype.getWorldMatrix = function () {
  9914. if (!this._worldMatrix) {
  9915. this._worldMatrix = BABYLON.Matrix.Identity();
  9916. }
  9917. var viewMatrix = this.getViewMatrix();
  9918. viewMatrix.invertToRef(this._worldMatrix);
  9919. return this._worldMatrix;
  9920. };
  9921. Camera.prototype._getViewMatrix = function () {
  9922. return BABYLON.Matrix.Identity();
  9923. };
  9924. Camera.prototype.getViewMatrix = function (force) {
  9925. this._computedViewMatrix = this._computeViewMatrix(force);
  9926. if (!force && this._isSynchronizedViewMatrix()) {
  9927. return this._computedViewMatrix;
  9928. }
  9929. if (!this.parent || !this.parent.getWorldMatrix) {
  9930. this._globalPosition.copyFrom(this.position);
  9931. }
  9932. else {
  9933. if (!this._worldMatrix) {
  9934. this._worldMatrix = BABYLON.Matrix.Identity();
  9935. }
  9936. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9937. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9938. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9939. this._computedViewMatrix.invert();
  9940. this._markSyncedWithParent();
  9941. }
  9942. this._currentRenderId = this.getScene().getRenderId();
  9943. return this._computedViewMatrix;
  9944. };
  9945. Camera.prototype._computeViewMatrix = function (force) {
  9946. if (!force && this._isSynchronizedViewMatrix()) {
  9947. return this._computedViewMatrix;
  9948. }
  9949. this._computedViewMatrix = this._getViewMatrix();
  9950. this._currentRenderId = this.getScene().getRenderId();
  9951. return this._computedViewMatrix;
  9952. };
  9953. Camera.prototype.getProjectionMatrix = function (force) {
  9954. if (!force && this._isSynchronizedProjectionMatrix()) {
  9955. return this._projectionMatrix;
  9956. }
  9957. var engine = this.getEngine();
  9958. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9959. if (this.minZ <= 0) {
  9960. this.minZ = 0.1;
  9961. }
  9962. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9963. return this._projectionMatrix;
  9964. }
  9965. var halfWidth = engine.getRenderWidth() / 2.0;
  9966. var halfHeight = engine.getRenderHeight() / 2.0;
  9967. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9968. return this._projectionMatrix;
  9969. };
  9970. Camera.prototype.dispose = function () {
  9971. // Remove from scene
  9972. this.getScene().removeCamera(this);
  9973. while (this.subCameras.length > 0) {
  9974. this.subCameras.pop().dispose();
  9975. }
  9976. // Postprocesses
  9977. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9978. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9979. }
  9980. };
  9981. // ---- 3D cameras section ----
  9982. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9983. if (halfSpace === void 0) { halfSpace = 0; }
  9984. while (this.subCameras.length > 0) {
  9985. this.subCameras.pop().dispose();
  9986. }
  9987. this._subCameraMode = mode;
  9988. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9989. var camA = this.getSubCamera(this.name + "_A", true);
  9990. var camB = this.getSubCamera(this.name + "_B", false);
  9991. var postProcessA;
  9992. var postProcessB;
  9993. switch (this._subCameraMode) {
  9994. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9995. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9996. camA.isIntermediate = true;
  9997. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9998. postProcessB.onApply = function (effect) {
  9999. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  10000. };
  10001. break;
  10002. case Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM:
  10003. case Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM:
  10004. var isStereogramHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  10005. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  10006. camA.isIntermediate = true;
  10007. postProcessB = new BABYLON.StereogramInterlacePostProcess("st_interlace", camB, postProcessA, isStereogramHoriz);
  10008. break;
  10009. case Camera.SUB_CAMERA_MODE_VR:
  10010. metrics = metrics || VRCameraMetrics.GetDefault();
  10011. camA._vrMetrics = metrics;
  10012. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10013. camA._vrWorkMatrix = new BABYLON.Matrix();
  10014. camA._vrHMatrix = metrics.leftHMatrix;
  10015. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  10016. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  10017. if (metrics.compensateDistorsion) {
  10018. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  10019. }
  10020. camB._vrMetrics = camA._vrMetrics;
  10021. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10022. camB._vrWorkMatrix = new BABYLON.Matrix();
  10023. camB._vrHMatrix = metrics.rightHMatrix;
  10024. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  10025. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  10026. if (metrics.compensateDistorsion) {
  10027. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  10028. }
  10029. }
  10030. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  10031. this.subCameras.push(camA);
  10032. this.subCameras.push(camB);
  10033. }
  10034. this._update();
  10035. };
  10036. Camera.prototype._getVRProjectionMatrix = function () {
  10037. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10038. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10039. return this._projectionMatrix;
  10040. };
  10041. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10042. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10043. };
  10044. /**
  10045. * May needs to be overridden by children so sub has required properties to be copied
  10046. */
  10047. Camera.prototype.getSubCamera = function (name, isA) {
  10048. return null;
  10049. };
  10050. /**
  10051. * May needs to be overridden by children
  10052. */
  10053. Camera.prototype._updateSubCameras = function () {
  10054. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10055. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10056. camA.minZ = camB.minZ = this.minZ;
  10057. camA.maxZ = camB.maxZ = this.maxZ;
  10058. camA.fov = camB.fov = this.fov;
  10059. // only update viewport, when ANAGLYPH
  10060. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10061. camA.viewport = camB.viewport = this.viewport;
  10062. }
  10063. };
  10064. // Statics
  10065. Camera._PERSPECTIVE_CAMERA = 0;
  10066. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10067. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10068. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10069. Camera._SUB_CAMERA_MODE_NONE = 0;
  10070. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10071. Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM = 2;
  10072. Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM = 3;
  10073. Camera._SUB_CAMERA_MODE_VR = 4;
  10074. Camera._SUB_CAMERAID_A = 0;
  10075. Camera._SUB_CAMERAID_B = 1;
  10076. return Camera;
  10077. })(BABYLON.Node);
  10078. BABYLON.Camera = Camera;
  10079. })(BABYLON || (BABYLON = {}));
  10080. //# sourceMappingURL=babylon.camera.js.map
  10081. var __extends = this.__extends || function (d, b) {
  10082. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10083. function __() { this.constructor = d; }
  10084. __.prototype = b.prototype;
  10085. d.prototype = new __();
  10086. };
  10087. var BABYLON;
  10088. (function (BABYLON) {
  10089. var TargetCamera = (function (_super) {
  10090. __extends(TargetCamera, _super);
  10091. function TargetCamera(name, position, scene) {
  10092. _super.call(this, name, position, scene);
  10093. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10094. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10095. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10096. this.speed = 2.0;
  10097. this.noRotationConstraint = false;
  10098. this.lockedTarget = null;
  10099. this._currentTarget = BABYLON.Vector3.Zero();
  10100. this._viewMatrix = BABYLON.Matrix.Zero();
  10101. this._camMatrix = BABYLON.Matrix.Zero();
  10102. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10103. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10104. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10105. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10106. this._lookAtTemp = BABYLON.Matrix.Zero();
  10107. this._tempMatrix = BABYLON.Matrix.Zero();
  10108. }
  10109. TargetCamera.prototype._getLockedTargetPosition = function () {
  10110. if (!this.lockedTarget) {
  10111. return null;
  10112. }
  10113. return this.lockedTarget.position || this.lockedTarget;
  10114. };
  10115. // Cache
  10116. TargetCamera.prototype._initCache = function () {
  10117. _super.prototype._initCache.call(this);
  10118. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10119. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10120. };
  10121. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10122. if (!ignoreParentClass) {
  10123. _super.prototype._updateCache.call(this);
  10124. }
  10125. var lockedTargetPosition = this._getLockedTargetPosition();
  10126. if (!lockedTargetPosition) {
  10127. this._cache.lockedTarget = null;
  10128. }
  10129. else {
  10130. if (!this._cache.lockedTarget) {
  10131. this._cache.lockedTarget = lockedTargetPosition.clone();
  10132. }
  10133. else {
  10134. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10135. }
  10136. }
  10137. this._cache.rotation.copyFrom(this.rotation);
  10138. };
  10139. // Synchronized
  10140. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10141. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10142. return false;
  10143. }
  10144. var lockedTargetPosition = this._getLockedTargetPosition();
  10145. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10146. && this._cache.rotation.equals(this.rotation);
  10147. };
  10148. // Methods
  10149. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10150. var engine = this.getEngine();
  10151. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10152. };
  10153. // Target
  10154. TargetCamera.prototype.setTarget = function (target) {
  10155. this.upVector.normalize();
  10156. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10157. this._camMatrix.invert();
  10158. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10159. var vDir = target.subtract(this.position);
  10160. if (vDir.x >= 0.0) {
  10161. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10162. }
  10163. else {
  10164. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10165. }
  10166. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10167. if (isNaN(this.rotation.x)) {
  10168. this.rotation.x = 0;
  10169. }
  10170. if (isNaN(this.rotation.y)) {
  10171. this.rotation.y = 0;
  10172. }
  10173. if (isNaN(this.rotation.z)) {
  10174. this.rotation.z = 0;
  10175. }
  10176. };
  10177. TargetCamera.prototype.getTarget = function () {
  10178. return this._currentTarget;
  10179. };
  10180. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10181. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10182. };
  10183. TargetCamera.prototype._updatePosition = function () {
  10184. this.position.addInPlace(this.cameraDirection);
  10185. };
  10186. TargetCamera.prototype._checkInputs = function () {
  10187. var needToMove = this._decideIfNeedsToMove();
  10188. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10189. // Move
  10190. if (needToMove) {
  10191. this._updatePosition();
  10192. }
  10193. // Rotate
  10194. if (needToRotate) {
  10195. this.rotation.x += this.cameraRotation.x;
  10196. this.rotation.y += this.cameraRotation.y;
  10197. if (!this.noRotationConstraint) {
  10198. var limit = (Math.PI / 2) * 0.95;
  10199. if (this.rotation.x > limit)
  10200. this.rotation.x = limit;
  10201. if (this.rotation.x < -limit)
  10202. this.rotation.x = -limit;
  10203. }
  10204. }
  10205. // Inertia
  10206. if (needToMove) {
  10207. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10208. this.cameraDirection.x = 0;
  10209. }
  10210. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10211. this.cameraDirection.y = 0;
  10212. }
  10213. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10214. this.cameraDirection.z = 0;
  10215. }
  10216. this.cameraDirection.scaleInPlace(this.inertia);
  10217. }
  10218. if (needToRotate) {
  10219. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10220. this.cameraRotation.x = 0;
  10221. }
  10222. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10223. this.cameraRotation.y = 0;
  10224. }
  10225. this.cameraRotation.scaleInPlace(this.inertia);
  10226. }
  10227. _super.prototype._checkInputs.call(this);
  10228. };
  10229. TargetCamera.prototype._getViewMatrix = function () {
  10230. if (!this.lockedTarget) {
  10231. // Compute
  10232. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10233. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10234. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10235. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10236. this._lookAtTemp.invert();
  10237. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10238. }
  10239. else {
  10240. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10241. }
  10242. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10243. // Computing target and final matrix
  10244. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10245. }
  10246. else {
  10247. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10248. }
  10249. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10250. return this._viewMatrix;
  10251. };
  10252. TargetCamera.prototype._getVRViewMatrix = function () {
  10253. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10254. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10255. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10256. // Computing target and final matrix
  10257. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10258. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10259. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10260. return this._viewMatrix;
  10261. };
  10262. /**
  10263. * @override
  10264. * needs to be overridden, so sub has required properties to be copied
  10265. */
  10266. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10267. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10268. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10269. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10270. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10271. }
  10272. return subCamera;
  10273. };
  10274. /**
  10275. * @override
  10276. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10277. */
  10278. TargetCamera.prototype._updateSubCameras = function () {
  10279. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10280. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10281. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10282. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10283. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10284. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10285. camA.position.copyFrom(this.position);
  10286. camB.position.copyFrom(this.position);
  10287. }
  10288. else {
  10289. camA.setTarget(this.getTarget());
  10290. camB.setTarget(this.getTarget());
  10291. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10292. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10293. }
  10294. _super.prototype._updateSubCameras.call(this);
  10295. };
  10296. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10297. if (!this._subCamTransformMatrix) {
  10298. this._subCamTransformMatrix = new BABYLON.Matrix();
  10299. }
  10300. var target = this.getTarget();
  10301. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10302. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10304. };
  10305. return TargetCamera;
  10306. })(BABYLON.Camera);
  10307. BABYLON.TargetCamera = TargetCamera;
  10308. })(BABYLON || (BABYLON = {}));
  10309. //# sourceMappingURL=babylon.targetCamera.js.map
  10310. var __extends = this.__extends || function (d, b) {
  10311. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10312. function __() { this.constructor = d; }
  10313. __.prototype = b.prototype;
  10314. d.prototype = new __();
  10315. };
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var FreeCamera = (function (_super) {
  10319. __extends(FreeCamera, _super);
  10320. function FreeCamera(name, position, scene) {
  10321. var _this = this;
  10322. _super.call(this, name, position, scene);
  10323. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10324. this.keysUp = [38];
  10325. this.keysDown = [40];
  10326. this.keysLeft = [37];
  10327. this.keysRight = [39];
  10328. this.checkCollisions = false;
  10329. this.applyGravity = false;
  10330. this.angularSensibility = 2000.0;
  10331. this._keys = [];
  10332. this._collider = new BABYLON.Collider();
  10333. this._needMoveForGravity = false;
  10334. this._oldPosition = BABYLON.Vector3.Zero();
  10335. this._diffPosition = BABYLON.Vector3.Zero();
  10336. this._newPosition = BABYLON.Vector3.Zero();
  10337. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10338. if (collidedMesh === void 0) { collidedMesh = null; }
  10339. //TODO move this to the collision coordinator!
  10340. if (_this.getScene().workerCollisions)
  10341. newPosition.multiplyInPlace(_this._collider.radius);
  10342. var updatePosition = function (newPos) {
  10343. _this._newPosition.copyFrom(newPos);
  10344. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10345. var oldPosition = _this.position.clone();
  10346. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10347. _this.position.addInPlace(_this._diffPosition);
  10348. if (_this.onCollide && collidedMesh) {
  10349. _this.onCollide(collidedMesh);
  10350. }
  10351. }
  10352. };
  10353. updatePosition(newPosition);
  10354. };
  10355. }
  10356. // Controls
  10357. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10358. var _this = this;
  10359. var previousPosition;
  10360. var engine = this.getEngine();
  10361. if (this._attachedElement) {
  10362. return;
  10363. }
  10364. this._attachedElement = element;
  10365. if (this._onMouseDown === undefined) {
  10366. this._onMouseDown = function (evt) {
  10367. previousPosition = {
  10368. x: evt.clientX,
  10369. y: evt.clientY
  10370. };
  10371. if (!noPreventDefault) {
  10372. evt.preventDefault();
  10373. }
  10374. };
  10375. this._onMouseUp = function (evt) {
  10376. previousPosition = null;
  10377. if (!noPreventDefault) {
  10378. evt.preventDefault();
  10379. }
  10380. };
  10381. this._onMouseOut = function (evt) {
  10382. previousPosition = null;
  10383. _this._keys = [];
  10384. if (!noPreventDefault) {
  10385. evt.preventDefault();
  10386. }
  10387. };
  10388. this._onMouseMove = function (evt) {
  10389. if (!previousPosition && !engine.isPointerLock) {
  10390. return;
  10391. }
  10392. var offsetX;
  10393. var offsetY;
  10394. if (!engine.isPointerLock) {
  10395. offsetX = evt.clientX - previousPosition.x;
  10396. offsetY = evt.clientY - previousPosition.y;
  10397. }
  10398. else {
  10399. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10400. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10401. }
  10402. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10403. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10404. previousPosition = {
  10405. x: evt.clientX,
  10406. y: evt.clientY
  10407. };
  10408. if (!noPreventDefault) {
  10409. evt.preventDefault();
  10410. }
  10411. };
  10412. this._onKeyDown = function (evt) {
  10413. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10414. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10415. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10416. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10417. var index = _this._keys.indexOf(evt.keyCode);
  10418. if (index === -1) {
  10419. _this._keys.push(evt.keyCode);
  10420. }
  10421. if (!noPreventDefault) {
  10422. evt.preventDefault();
  10423. }
  10424. }
  10425. };
  10426. this._onKeyUp = function (evt) {
  10427. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10428. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10429. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10430. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10431. var index = _this._keys.indexOf(evt.keyCode);
  10432. if (index >= 0) {
  10433. _this._keys.splice(index, 1);
  10434. }
  10435. if (!noPreventDefault) {
  10436. evt.preventDefault();
  10437. }
  10438. }
  10439. };
  10440. this._onLostFocus = function () {
  10441. _this._keys = [];
  10442. };
  10443. this._reset = function () {
  10444. _this._keys = [];
  10445. previousPosition = null;
  10446. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10447. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10448. };
  10449. }
  10450. element.addEventListener("mousedown", this._onMouseDown, false);
  10451. element.addEventListener("mouseup", this._onMouseUp, false);
  10452. element.addEventListener("mouseout", this._onMouseOut, false);
  10453. element.addEventListener("mousemove", this._onMouseMove, false);
  10454. BABYLON.Tools.RegisterTopRootEvents([
  10455. { name: "keydown", handler: this._onKeyDown },
  10456. { name: "keyup", handler: this._onKeyUp },
  10457. { name: "blur", handler: this._onLostFocus }
  10458. ]);
  10459. };
  10460. FreeCamera.prototype.detachControl = function (element) {
  10461. if (this._attachedElement != element) {
  10462. return;
  10463. }
  10464. element.removeEventListener("mousedown", this._onMouseDown);
  10465. element.removeEventListener("mouseup", this._onMouseUp);
  10466. element.removeEventListener("mouseout", this._onMouseOut);
  10467. element.removeEventListener("mousemove", this._onMouseMove);
  10468. BABYLON.Tools.UnregisterTopRootEvents([
  10469. { name: "keydown", handler: this._onKeyDown },
  10470. { name: "keyup", handler: this._onKeyUp },
  10471. { name: "blur", handler: this._onLostFocus }
  10472. ]);
  10473. this._attachedElement = null;
  10474. if (this._reset) {
  10475. this._reset();
  10476. }
  10477. };
  10478. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10479. var globalPosition;
  10480. if (this.parent) {
  10481. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10482. }
  10483. else {
  10484. globalPosition = this.position;
  10485. }
  10486. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10487. this._collider.radius = this.ellipsoid;
  10488. //add gravity to the velocity to prevent the dual-collision checking
  10489. if (this.applyGravity) {
  10490. velocity.addInPlace(this.getScene().gravity);
  10491. }
  10492. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10493. };
  10494. FreeCamera.prototype._checkInputs = function () {
  10495. if (!this._localDirection) {
  10496. this._localDirection = BABYLON.Vector3.Zero();
  10497. this._transformedDirection = BABYLON.Vector3.Zero();
  10498. }
  10499. // Keyboard
  10500. for (var index = 0; index < this._keys.length; index++) {
  10501. var keyCode = this._keys[index];
  10502. var speed = this._computeLocalCameraSpeed();
  10503. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10504. this._localDirection.copyFromFloats(-speed, 0, 0);
  10505. }
  10506. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10507. this._localDirection.copyFromFloats(0, 0, speed);
  10508. }
  10509. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10510. this._localDirection.copyFromFloats(speed, 0, 0);
  10511. }
  10512. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10513. this._localDirection.copyFromFloats(0, 0, -speed);
  10514. }
  10515. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10516. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10517. this.cameraDirection.addInPlace(this._transformedDirection);
  10518. }
  10519. _super.prototype._checkInputs.call(this);
  10520. };
  10521. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10522. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10523. };
  10524. FreeCamera.prototype._updatePosition = function () {
  10525. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10526. this._collideWithWorld(this.cameraDirection);
  10527. }
  10528. else {
  10529. this.position.addInPlace(this.cameraDirection);
  10530. }
  10531. };
  10532. return FreeCamera;
  10533. })(BABYLON.TargetCamera);
  10534. BABYLON.FreeCamera = FreeCamera;
  10535. })(BABYLON || (BABYLON = {}));
  10536. //# sourceMappingURL=babylon.freeCamera.js.map
  10537. var __extends = this.__extends || function (d, b) {
  10538. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10539. function __() { this.constructor = d; }
  10540. __.prototype = b.prototype;
  10541. d.prototype = new __();
  10542. };
  10543. var BABYLON;
  10544. (function (BABYLON) {
  10545. var FollowCamera = (function (_super) {
  10546. __extends(FollowCamera, _super);
  10547. function FollowCamera(name, position, scene) {
  10548. _super.call(this, name, position, scene);
  10549. this.radius = 12;
  10550. this.rotationOffset = 0;
  10551. this.heightOffset = 4;
  10552. this.cameraAcceleration = 0.05;
  10553. this.maxCameraSpeed = 20;
  10554. }
  10555. FollowCamera.prototype.getRadians = function (degrees) {
  10556. return degrees * Math.PI / 180;
  10557. };
  10558. FollowCamera.prototype.follow = function (cameraTarget) {
  10559. if (!cameraTarget)
  10560. return;
  10561. var yRotation;
  10562. if (cameraTarget.rotationQuaternion) {
  10563. var rotMatrix = new BABYLON.Matrix();
  10564. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10565. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10566. }
  10567. else {
  10568. yRotation = cameraTarget.rotation.y;
  10569. }
  10570. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10571. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10572. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10573. var dx = targetX - this.position.x;
  10574. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10575. var dz = (targetZ) - this.position.z;
  10576. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10577. var vy = dy * this.cameraAcceleration;
  10578. var vz = dz * this.cameraAcceleration * 2;
  10579. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10580. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10581. }
  10582. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10583. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10584. }
  10585. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10586. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10587. }
  10588. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10589. this.setTarget(cameraTarget.position);
  10590. };
  10591. FollowCamera.prototype._checkInputs = function () {
  10592. _super.prototype._checkInputs.call(this);
  10593. this.follow(this.target);
  10594. };
  10595. return FollowCamera;
  10596. })(BABYLON.TargetCamera);
  10597. BABYLON.FollowCamera = FollowCamera;
  10598. })(BABYLON || (BABYLON = {}));
  10599. //# sourceMappingURL=babylon.followCamera.js.map
  10600. var __extends = this.__extends || function (d, b) {
  10601. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10602. function __() { this.constructor = d; }
  10603. __.prototype = b.prototype;
  10604. d.prototype = new __();
  10605. };
  10606. var BABYLON;
  10607. (function (BABYLON) {
  10608. // We're mainly based on the logic defined into the FreeCamera code
  10609. var TouchCamera = (function (_super) {
  10610. __extends(TouchCamera, _super);
  10611. function TouchCamera(name, position, scene) {
  10612. _super.call(this, name, position, scene);
  10613. this._offsetX = null;
  10614. this._offsetY = null;
  10615. this._pointerCount = 0;
  10616. this._pointerPressed = [];
  10617. this.angularSensibility = 200000.0;
  10618. this.moveSensibility = 500.0;
  10619. }
  10620. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10621. var _this = this;
  10622. var previousPosition;
  10623. if (this._attachedCanvas) {
  10624. return;
  10625. }
  10626. this._attachedCanvas = canvas;
  10627. if (this._onPointerDown === undefined) {
  10628. this._onPointerDown = function (evt) {
  10629. if (!noPreventDefault) {
  10630. evt.preventDefault();
  10631. }
  10632. _this._pointerPressed.push(evt.pointerId);
  10633. if (_this._pointerPressed.length !== 1) {
  10634. return;
  10635. }
  10636. previousPosition = {
  10637. x: evt.clientX,
  10638. y: evt.clientY
  10639. };
  10640. };
  10641. this._onPointerUp = function (evt) {
  10642. if (!noPreventDefault) {
  10643. evt.preventDefault();
  10644. }
  10645. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10646. if (index === -1) {
  10647. return;
  10648. }
  10649. _this._pointerPressed.splice(index, 1);
  10650. if (index != 0) {
  10651. return;
  10652. }
  10653. previousPosition = null;
  10654. _this._offsetX = null;
  10655. _this._offsetY = null;
  10656. };
  10657. this._onPointerMove = function (evt) {
  10658. if (!noPreventDefault) {
  10659. evt.preventDefault();
  10660. }
  10661. if (!previousPosition) {
  10662. return;
  10663. }
  10664. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10665. if (index != 0) {
  10666. return;
  10667. }
  10668. _this._offsetX = evt.clientX - previousPosition.x;
  10669. _this._offsetY = -(evt.clientY - previousPosition.y);
  10670. };
  10671. this._onLostFocus = function () {
  10672. _this._offsetX = null;
  10673. _this._offsetY = null;
  10674. };
  10675. }
  10676. canvas.addEventListener("pointerdown", this._onPointerDown);
  10677. canvas.addEventListener("pointerup", this._onPointerUp);
  10678. canvas.addEventListener("pointerout", this._onPointerUp);
  10679. canvas.addEventListener("pointermove", this._onPointerMove);
  10680. BABYLON.Tools.RegisterTopRootEvents([
  10681. { name: "blur", handler: this._onLostFocus }
  10682. ]);
  10683. };
  10684. TouchCamera.prototype.detachControl = function (canvas) {
  10685. if (this._attachedCanvas != canvas) {
  10686. return;
  10687. }
  10688. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10689. canvas.removeEventListener("pointerup", this._onPointerUp);
  10690. canvas.removeEventListener("pointerout", this._onPointerUp);
  10691. canvas.removeEventListener("pointermove", this._onPointerMove);
  10692. BABYLON.Tools.UnregisterTopRootEvents([
  10693. { name: "blur", handler: this._onLostFocus }
  10694. ]);
  10695. this._attachedCanvas = null;
  10696. };
  10697. TouchCamera.prototype._checkInputs = function () {
  10698. if (!this._offsetX) {
  10699. return;
  10700. }
  10701. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10702. if (this._pointerPressed.length > 1) {
  10703. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10704. }
  10705. else {
  10706. var speed = this._computeLocalCameraSpeed();
  10707. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10708. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10709. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10710. }
  10711. _super.prototype._checkInputs.call(this);
  10712. };
  10713. return TouchCamera;
  10714. })(BABYLON.FreeCamera);
  10715. BABYLON.TouchCamera = TouchCamera;
  10716. })(BABYLON || (BABYLON = {}));
  10717. //# sourceMappingURL=babylon.touchCamera.js.map
  10718. var __extends = this.__extends || function (d, b) {
  10719. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10720. function __() { this.constructor = d; }
  10721. __.prototype = b.prototype;
  10722. d.prototype = new __();
  10723. };
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10727. var ArcRotateCamera = (function (_super) {
  10728. __extends(ArcRotateCamera, _super);
  10729. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10730. var _this = this;
  10731. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10732. this.alpha = alpha;
  10733. this.beta = beta;
  10734. this.radius = radius;
  10735. this.target = target;
  10736. this.inertialAlphaOffset = 0;
  10737. this.inertialBetaOffset = 0;
  10738. this.inertialRadiusOffset = 0;
  10739. this.lowerAlphaLimit = null;
  10740. this.upperAlphaLimit = null;
  10741. this.lowerBetaLimit = 0.01;
  10742. this.upperBetaLimit = Math.PI;
  10743. this.lowerRadiusLimit = null;
  10744. this.upperRadiusLimit = null;
  10745. this.angularSensibility = 1000.0;
  10746. this.wheelPrecision = 3.0;
  10747. this.pinchPrecision = 2.0;
  10748. this.keysUp = [38];
  10749. this.keysDown = [40];
  10750. this.keysLeft = [37];
  10751. this.keysRight = [39];
  10752. this.zoomOnFactor = 1;
  10753. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10754. this.pinchInwards = true;
  10755. this._keys = [];
  10756. this._viewMatrix = new BABYLON.Matrix();
  10757. this.checkCollisions = false;
  10758. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10759. this._collider = new BABYLON.Collider();
  10760. this._previousPosition = BABYLON.Vector3.Zero();
  10761. this._collisionVelocity = BABYLON.Vector3.Zero();
  10762. this._newPosition = BABYLON.Vector3.Zero();
  10763. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10764. if (collidedMesh === void 0) { collidedMesh = null; }
  10765. if (collisionId != null || collisionId != undefined)
  10766. newPosition.multiplyInPlace(_this._collider.radius);
  10767. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10768. _this.position.copyFrom(_this._previousPosition);
  10769. _this.alpha = _this._previousAlpha;
  10770. _this.beta = _this._previousBeta;
  10771. _this.radius = _this._previousRadius;
  10772. if (_this.onCollide && collidedMesh) {
  10773. _this.onCollide(collidedMesh);
  10774. }
  10775. }
  10776. _this._collisionTriggered = false;
  10777. };
  10778. if (!this.target) {
  10779. this.target = BABYLON.Vector3.Zero();
  10780. }
  10781. this.getViewMatrix();
  10782. }
  10783. ArcRotateCamera.prototype._getTargetPosition = function () {
  10784. return this.target.position || this.target;
  10785. };
  10786. // Cache
  10787. ArcRotateCamera.prototype._initCache = function () {
  10788. _super.prototype._initCache.call(this);
  10789. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10790. this._cache.alpha = undefined;
  10791. this._cache.beta = undefined;
  10792. this._cache.radius = undefined;
  10793. this._cache.targetScreenOffset = undefined;
  10794. };
  10795. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10796. if (!ignoreParentClass) {
  10797. _super.prototype._updateCache.call(this);
  10798. }
  10799. this._cache.target.copyFrom(this._getTargetPosition());
  10800. this._cache.alpha = this.alpha;
  10801. this._cache.beta = this.beta;
  10802. this._cache.radius = this.radius;
  10803. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10804. };
  10805. // Synchronized
  10806. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10807. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10808. return false;
  10809. return this._cache.target.equals(this._getTargetPosition())
  10810. && this._cache.alpha === this.alpha
  10811. && this._cache.beta === this.beta
  10812. && this._cache.radius === this.radius
  10813. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10814. };
  10815. // Methods
  10816. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10817. var _this = this;
  10818. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10819. var previousPinchDistance = 0;
  10820. var pointers = new BABYLON.SmartCollection();
  10821. if (this._attachedElement) {
  10822. return;
  10823. }
  10824. this._attachedElement = element;
  10825. var engine = this.getEngine();
  10826. if (this._onPointerDown === undefined) {
  10827. this._onPointerDown = function (evt) {
  10828. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10829. cacheSoloPointer = pointers.item(evt.pointerId);
  10830. if (!noPreventDefault) {
  10831. evt.preventDefault();
  10832. }
  10833. };
  10834. this._onPointerUp = function (evt) {
  10835. cacheSoloPointer = null;
  10836. previousPinchDistance = 0;
  10837. pointers.remove(evt.pointerId);
  10838. if (!noPreventDefault) {
  10839. evt.preventDefault();
  10840. }
  10841. };
  10842. this._onPointerMove = function (evt) {
  10843. if (!noPreventDefault) {
  10844. evt.preventDefault();
  10845. }
  10846. switch (pointers.count) {
  10847. case 1:
  10848. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10849. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10850. var offsetX = evt.clientX - cacheSoloPointer.x;
  10851. var offsetY = evt.clientY - cacheSoloPointer.y;
  10852. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10853. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10854. //pointers.item(evt.pointerId).x = evt.clientX;
  10855. //pointers.item(evt.pointerId).y = evt.clientY;
  10856. cacheSoloPointer.x = evt.clientX;
  10857. cacheSoloPointer.y = evt.clientY;
  10858. break;
  10859. case 2:
  10860. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10861. pointers.item(evt.pointerId).x = evt.clientX;
  10862. pointers.item(evt.pointerId).y = evt.clientY;
  10863. var direction = _this.pinchInwards ? 1 : -1;
  10864. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10865. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10866. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10867. if (previousPinchDistance === 0) {
  10868. previousPinchDistance = pinchSquaredDistance;
  10869. return;
  10870. }
  10871. if (pinchSquaredDistance !== previousPinchDistance) {
  10872. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10873. previousPinchDistance = pinchSquaredDistance;
  10874. }
  10875. break;
  10876. default:
  10877. if (pointers.item(evt.pointerId)) {
  10878. pointers.item(evt.pointerId).x = evt.clientX;
  10879. pointers.item(evt.pointerId).y = evt.clientY;
  10880. }
  10881. }
  10882. };
  10883. this._onMouseMove = function (evt) {
  10884. if (!engine.isPointerLock) {
  10885. return;
  10886. }
  10887. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10888. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10889. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10890. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10891. if (!noPreventDefault) {
  10892. evt.preventDefault();
  10893. }
  10894. };
  10895. this._wheel = function (event) {
  10896. var delta = 0;
  10897. if (event.wheelDelta) {
  10898. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10899. }
  10900. else if (event.detail) {
  10901. delta = -event.detail / _this.wheelPrecision;
  10902. }
  10903. if (delta)
  10904. _this.inertialRadiusOffset += delta;
  10905. if (event.preventDefault) {
  10906. if (!noPreventDefault) {
  10907. event.preventDefault();
  10908. }
  10909. }
  10910. };
  10911. this._onKeyDown = function (evt) {
  10912. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10913. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10914. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10915. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10916. var index = _this._keys.indexOf(evt.keyCode);
  10917. if (index === -1) {
  10918. _this._keys.push(evt.keyCode);
  10919. }
  10920. if (evt.preventDefault) {
  10921. if (!noPreventDefault) {
  10922. evt.preventDefault();
  10923. }
  10924. }
  10925. }
  10926. };
  10927. this._onKeyUp = function (evt) {
  10928. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10929. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10930. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10931. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10932. var index = _this._keys.indexOf(evt.keyCode);
  10933. if (index >= 0) {
  10934. _this._keys.splice(index, 1);
  10935. }
  10936. if (evt.preventDefault) {
  10937. if (!noPreventDefault) {
  10938. evt.preventDefault();
  10939. }
  10940. }
  10941. }
  10942. };
  10943. this._onLostFocus = function () {
  10944. _this._keys = [];
  10945. pointers.empty();
  10946. previousPinchDistance = 0;
  10947. cacheSoloPointer = null;
  10948. };
  10949. this._onGestureStart = function (e) {
  10950. if (window.MSGesture === undefined) {
  10951. return;
  10952. }
  10953. if (!_this._MSGestureHandler) {
  10954. _this._MSGestureHandler = new MSGesture();
  10955. _this._MSGestureHandler.target = element;
  10956. }
  10957. _this._MSGestureHandler.addPointer(e.pointerId);
  10958. };
  10959. this._onGesture = function (e) {
  10960. _this.radius *= e.scale;
  10961. if (e.preventDefault) {
  10962. if (!noPreventDefault) {
  10963. e.stopPropagation();
  10964. e.preventDefault();
  10965. }
  10966. }
  10967. };
  10968. this._reset = function () {
  10969. _this._keys = [];
  10970. _this.inertialAlphaOffset = 0;
  10971. _this.inertialBetaOffset = 0;
  10972. _this.inertialRadiusOffset = 0;
  10973. pointers.empty();
  10974. previousPinchDistance = 0;
  10975. cacheSoloPointer = null;
  10976. };
  10977. }
  10978. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10979. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10980. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10981. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10982. element.addEventListener("mousemove", this._onMouseMove, false);
  10983. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10984. element.addEventListener("MSGestureChange", this._onGesture, false);
  10985. element.addEventListener('mousewheel', this._wheel, false);
  10986. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10987. BABYLON.Tools.RegisterTopRootEvents([
  10988. { name: "keydown", handler: this._onKeyDown },
  10989. { name: "keyup", handler: this._onKeyUp },
  10990. { name: "blur", handler: this._onLostFocus }
  10991. ]);
  10992. };
  10993. ArcRotateCamera.prototype.detachControl = function (element) {
  10994. if (this._attachedElement !== element) {
  10995. return;
  10996. }
  10997. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10998. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10999. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11000. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11001. element.removeEventListener("mousemove", this._onMouseMove);
  11002. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11003. element.removeEventListener("MSGestureChange", this._onGesture);
  11004. element.removeEventListener('mousewheel', this._wheel);
  11005. element.removeEventListener('DOMMouseScroll', this._wheel);
  11006. BABYLON.Tools.UnregisterTopRootEvents([
  11007. { name: "keydown", handler: this._onKeyDown },
  11008. { name: "keyup", handler: this._onKeyUp },
  11009. { name: "blur", handler: this._onLostFocus }
  11010. ]);
  11011. this._MSGestureHandler = null;
  11012. this._attachedElement = null;
  11013. if (this._reset) {
  11014. this._reset();
  11015. }
  11016. };
  11017. ArcRotateCamera.prototype._checkInputs = function () {
  11018. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11019. if (this._collisionTriggered) {
  11020. return;
  11021. }
  11022. // Keyboard
  11023. for (var index = 0; index < this._keys.length; index++) {
  11024. var keyCode = this._keys[index];
  11025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11026. this.inertialAlphaOffset -= 0.01;
  11027. }
  11028. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11029. this.inertialBetaOffset -= 0.01;
  11030. }
  11031. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11032. this.inertialAlphaOffset += 0.01;
  11033. }
  11034. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11035. this.inertialBetaOffset += 0.01;
  11036. }
  11037. }
  11038. // Inertia
  11039. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11040. this.alpha += this.inertialAlphaOffset;
  11041. this.beta += this.inertialBetaOffset;
  11042. this.radius -= this.inertialRadiusOffset;
  11043. this.inertialAlphaOffset *= this.inertia;
  11044. this.inertialBetaOffset *= this.inertia;
  11045. this.inertialRadiusOffset *= this.inertia;
  11046. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11047. this.inertialAlphaOffset = 0;
  11048. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11049. this.inertialBetaOffset = 0;
  11050. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11051. this.inertialRadiusOffset = 0;
  11052. }
  11053. // Limits
  11054. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11055. this.alpha = this.lowerAlphaLimit;
  11056. }
  11057. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11058. this.alpha = this.upperAlphaLimit;
  11059. }
  11060. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  11061. this.beta = this.lowerBetaLimit;
  11062. }
  11063. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  11064. this.beta = this.upperBetaLimit;
  11065. }
  11066. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11067. this.radius = this.lowerRadiusLimit;
  11068. }
  11069. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11070. this.radius = this.upperRadiusLimit;
  11071. }
  11072. _super.prototype._checkInputs.call(this);
  11073. };
  11074. ArcRotateCamera.prototype.setPosition = function (position) {
  11075. var radiusv3 = position.subtract(this._getTargetPosition());
  11076. this.radius = radiusv3.length();
  11077. // Alpha
  11078. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11079. if (radiusv3.z < 0) {
  11080. this.alpha = 2 * Math.PI - this.alpha;
  11081. }
  11082. // Beta
  11083. this.beta = Math.acos(radiusv3.y / this.radius);
  11084. };
  11085. ArcRotateCamera.prototype._getViewMatrix = function () {
  11086. // Compute
  11087. var cosa = Math.cos(this.alpha);
  11088. var sina = Math.sin(this.alpha);
  11089. var cosb = Math.cos(this.beta);
  11090. var sinb = Math.sin(this.beta);
  11091. var target = this._getTargetPosition();
  11092. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11093. if (this.checkCollisions) {
  11094. this._collider.radius = this.collisionRadius;
  11095. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11096. this._collisionTriggered = true;
  11097. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11098. }
  11099. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  11100. this._previousAlpha = this.alpha;
  11101. this._previousBeta = this.beta;
  11102. this._previousRadius = this.radius;
  11103. this._previousPosition.copyFrom(this.position);
  11104. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11105. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11106. return this._viewMatrix;
  11107. };
  11108. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11109. meshes = meshes || this.getScene().meshes;
  11110. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11111. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11112. this.radius = distance * this.zoomOnFactor;
  11113. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11114. };
  11115. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11116. var meshesOrMinMaxVector;
  11117. var distance;
  11118. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11119. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11120. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11121. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11122. }
  11123. else {
  11124. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11125. distance = meshesOrMinMaxVectorAndDistance.distance;
  11126. }
  11127. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11128. this.maxZ = distance * 2;
  11129. };
  11130. /**
  11131. * @override
  11132. * needs to be overridden, so sub has required properties to be copied
  11133. */
  11134. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11135. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11136. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11137. };
  11138. /**
  11139. * @override
  11140. * needs to be overridden, adding copy of alpha, beta & radius
  11141. */
  11142. ArcRotateCamera.prototype._updateSubCameras = function () {
  11143. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11144. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11145. camA.alpha = this.alpha - this._subCamHalfSpace;
  11146. camB.alpha = this.alpha + this._subCamHalfSpace;
  11147. camA.beta = camB.beta = this.beta;
  11148. camA.radius = camB.radius = this.radius;
  11149. _super.prototype._updateSubCameras.call(this);
  11150. };
  11151. return ArcRotateCamera;
  11152. })(BABYLON.Camera);
  11153. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11154. })(BABYLON || (BABYLON = {}));
  11155. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11156. var __extends = this.__extends || function (d, b) {
  11157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11158. function __() { this.constructor = d; }
  11159. __.prototype = b.prototype;
  11160. d.prototype = new __();
  11161. };
  11162. var BABYLON;
  11163. (function (BABYLON) {
  11164. // We're mainly based on the logic defined into the FreeCamera code
  11165. var DeviceOrientationCamera = (function (_super) {
  11166. __extends(DeviceOrientationCamera, _super);
  11167. function DeviceOrientationCamera(name, position, scene) {
  11168. var _this = this;
  11169. _super.call(this, name, position, scene);
  11170. this._offsetX = null;
  11171. this._offsetY = null;
  11172. this._orientationGamma = 0;
  11173. this._orientationBeta = 0;
  11174. this._initialOrientationGamma = 0;
  11175. this._initialOrientationBeta = 0;
  11176. this.angularSensibility = 10000.0;
  11177. this.moveSensibility = 50.0;
  11178. window.addEventListener("resize", function () {
  11179. _this._initialOrientationGamma = null;
  11180. }, false);
  11181. }
  11182. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11183. var _this = this;
  11184. if (this._attachedCanvas) {
  11185. return;
  11186. }
  11187. this._attachedCanvas = canvas;
  11188. if (!this._orientationChanged) {
  11189. this._orientationChanged = function (evt) {
  11190. if (!_this._initialOrientationGamma) {
  11191. _this._initialOrientationGamma = evt.gamma;
  11192. _this._initialOrientationBeta = evt.beta;
  11193. }
  11194. _this._orientationGamma = evt.gamma;
  11195. _this._orientationBeta = evt.beta;
  11196. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11197. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11198. };
  11199. }
  11200. window.addEventListener("deviceorientation", this._orientationChanged);
  11201. };
  11202. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11203. if (this._attachedCanvas != canvas) {
  11204. return;
  11205. }
  11206. window.removeEventListener("deviceorientation", this._orientationChanged);
  11207. this._attachedCanvas = null;
  11208. this._orientationGamma = 0;
  11209. this._orientationBeta = 0;
  11210. this._initialOrientationGamma = 0;
  11211. this._initialOrientationBeta = 0;
  11212. };
  11213. DeviceOrientationCamera.prototype._checkInputs = function () {
  11214. if (!this._offsetX) {
  11215. return;
  11216. }
  11217. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11218. var speed = this._computeLocalCameraSpeed();
  11219. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11220. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11221. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11222. _super.prototype._checkInputs.call(this);
  11223. };
  11224. return DeviceOrientationCamera;
  11225. })(BABYLON.FreeCamera);
  11226. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11227. })(BABYLON || (BABYLON = {}));
  11228. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11229. var __extends = this.__extends || function (d, b) {
  11230. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11231. function __() { this.constructor = d; }
  11232. __.prototype = b.prototype;
  11233. d.prototype = new __();
  11234. };
  11235. var BABYLON;
  11236. (function (BABYLON) {
  11237. var Gamepads = (function () {
  11238. function Gamepads(ongamedpadconnected) {
  11239. var _this = this;
  11240. this.babylonGamepads = [];
  11241. this.oneGamepadConnected = false;
  11242. this.isMonitoring = false;
  11243. this.gamepadEventSupported = 'GamepadEvent' in window;
  11244. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11245. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11246. 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=";
  11247. this._callbackGamepadConnected = ongamedpadconnected;
  11248. if (this.gamepadSupportAvailable) {
  11249. // Checking if the gamepad connected event is supported (like in Firefox)
  11250. if (this.gamepadEventSupported) {
  11251. window.addEventListener('gamepadconnected', function (evt) {
  11252. _this._onGamepadConnected(evt);
  11253. }, false);
  11254. window.addEventListener('gamepaddisconnected', function (evt) {
  11255. _this._onGamepadDisconnected(evt);
  11256. }, false);
  11257. }
  11258. else {
  11259. this._startMonitoringGamepads();
  11260. }
  11261. if (!this.oneGamepadConnected) {
  11262. this._insertGamepadDOMInstructions();
  11263. }
  11264. }
  11265. else {
  11266. this._insertGamepadDOMNotSupported();
  11267. }
  11268. }
  11269. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11270. Gamepads.gamepadDOMInfo = document.createElement("div");
  11271. var buttonAImage = document.createElement("img");
  11272. buttonAImage.src = this.buttonADataURL;
  11273. var spanMessage = document.createElement("span");
  11274. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11275. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11276. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11277. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11278. Gamepads.gamepadDOMInfo.style.width = "100%";
  11279. Gamepads.gamepadDOMInfo.style.height = "48px";
  11280. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11281. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11282. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11283. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11284. buttonAImage.style.position = "relative";
  11285. buttonAImage.style.bottom = "8px";
  11286. spanMessage.style.position = "relative";
  11287. spanMessage.style.fontSize = "32px";
  11288. spanMessage.style.bottom = "32px";
  11289. spanMessage.style.color = "green";
  11290. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11291. };
  11292. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11293. Gamepads.gamepadDOMInfo = document.createElement("div");
  11294. var spanMessage = document.createElement("span");
  11295. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11296. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11297. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11298. Gamepads.gamepadDOMInfo.style.width = "100%";
  11299. Gamepads.gamepadDOMInfo.style.height = "40px";
  11300. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11301. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11302. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11303. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11304. spanMessage.style.position = "relative";
  11305. spanMessage.style.fontSize = "32px";
  11306. spanMessage.style.color = "red";
  11307. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11308. };
  11309. Gamepads.prototype.dispose = function () {
  11310. if (Gamepads.gamepadDOMInfo) {
  11311. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11312. }
  11313. };
  11314. Gamepads.prototype._onGamepadConnected = function (evt) {
  11315. var newGamepad = this._addNewGamepad(evt.gamepad);
  11316. if (this._callbackGamepadConnected)
  11317. this._callbackGamepadConnected(newGamepad);
  11318. this._startMonitoringGamepads();
  11319. };
  11320. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11321. if (!this.oneGamepadConnected) {
  11322. this.oneGamepadConnected = true;
  11323. if (Gamepads.gamepadDOMInfo) {
  11324. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11325. Gamepads.gamepadDOMInfo = null;
  11326. }
  11327. }
  11328. var newGamepad;
  11329. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11330. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11331. }
  11332. else {
  11333. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11334. }
  11335. this.babylonGamepads.push(newGamepad);
  11336. return newGamepad;
  11337. };
  11338. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11339. // Remove the gamepad from the list of gamepads to monitor.
  11340. for (var i in this.babylonGamepads) {
  11341. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11342. this.babylonGamepads.splice(i, 1);
  11343. break;
  11344. }
  11345. }
  11346. // If no gamepads are left, stop the polling loop.
  11347. if (this.babylonGamepads.length == 0) {
  11348. this._stopMonitoringGamepads();
  11349. }
  11350. };
  11351. Gamepads.prototype._startMonitoringGamepads = function () {
  11352. if (!this.isMonitoring) {
  11353. this.isMonitoring = true;
  11354. this._checkGamepadsStatus();
  11355. }
  11356. };
  11357. Gamepads.prototype._stopMonitoringGamepads = function () {
  11358. this.isMonitoring = false;
  11359. };
  11360. Gamepads.prototype._checkGamepadsStatus = function () {
  11361. var _this = this;
  11362. // updating gamepad objects
  11363. this._updateGamepadObjects();
  11364. for (var i in this.babylonGamepads) {
  11365. this.babylonGamepads[i].update();
  11366. }
  11367. if (this.isMonitoring) {
  11368. if (window.requestAnimationFrame) {
  11369. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11370. }
  11371. else if (window.mozRequestAnimationFrame) {
  11372. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11373. }
  11374. else if (window.webkitRequestAnimationFrame) {
  11375. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11376. }
  11377. }
  11378. };
  11379. // This function is called only on Chrome, which does not yet support
  11380. // connection/disconnection events, but requires you to monitor
  11381. // an array for changes.
  11382. Gamepads.prototype._updateGamepadObjects = function () {
  11383. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11384. for (var i = 0; i < gamepads.length; i++) {
  11385. if (gamepads[i]) {
  11386. if (!(gamepads[i].index in this.babylonGamepads)) {
  11387. var newGamepad = this._addNewGamepad(gamepads[i]);
  11388. if (this._callbackGamepadConnected) {
  11389. this._callbackGamepadConnected(newGamepad);
  11390. }
  11391. }
  11392. else {
  11393. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11394. }
  11395. }
  11396. }
  11397. };
  11398. return Gamepads;
  11399. })();
  11400. BABYLON.Gamepads = Gamepads;
  11401. var StickValues = (function () {
  11402. function StickValues(x, y) {
  11403. this.x = x;
  11404. this.y = y;
  11405. }
  11406. return StickValues;
  11407. })();
  11408. BABYLON.StickValues = StickValues;
  11409. var Gamepad = (function () {
  11410. function Gamepad(id, index, browserGamepad) {
  11411. this.id = id;
  11412. this.index = index;
  11413. this.browserGamepad = browserGamepad;
  11414. if (this.browserGamepad.axes.length >= 2) {
  11415. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11416. }
  11417. if (this.browserGamepad.axes.length >= 4) {
  11418. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11419. }
  11420. }
  11421. Gamepad.prototype.onleftstickchanged = function (callback) {
  11422. this._onleftstickchanged = callback;
  11423. };
  11424. Gamepad.prototype.onrightstickchanged = function (callback) {
  11425. this._onrightstickchanged = callback;
  11426. };
  11427. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11428. get: function () {
  11429. return this._leftStick;
  11430. },
  11431. set: function (newValues) {
  11432. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11433. this._onleftstickchanged(newValues);
  11434. }
  11435. this._leftStick = newValues;
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11441. get: function () {
  11442. return this._rightStick;
  11443. },
  11444. set: function (newValues) {
  11445. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11446. this._onrightstickchanged(newValues);
  11447. }
  11448. this._rightStick = newValues;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Gamepad.prototype.update = function () {
  11454. if (this._leftStick) {
  11455. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11456. }
  11457. if (this._rightStick) {
  11458. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11459. }
  11460. };
  11461. return Gamepad;
  11462. })();
  11463. BABYLON.Gamepad = Gamepad;
  11464. var GenericPad = (function (_super) {
  11465. __extends(GenericPad, _super);
  11466. function GenericPad(id, index, gamepad) {
  11467. _super.call(this, id, index, gamepad);
  11468. this.id = id;
  11469. this.index = index;
  11470. this.gamepad = gamepad;
  11471. this._buttons = new Array(gamepad.buttons.length);
  11472. }
  11473. GenericPad.prototype.onbuttondown = function (callback) {
  11474. this._onbuttondown = callback;
  11475. };
  11476. GenericPad.prototype.onbuttonup = function (callback) {
  11477. this._onbuttonup = callback;
  11478. };
  11479. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11480. if (newValue !== currentValue) {
  11481. if (this._onbuttondown && newValue === 1) {
  11482. this._onbuttondown(buttonIndex);
  11483. }
  11484. if (this._onbuttonup && newValue === 0) {
  11485. this._onbuttonup(buttonIndex);
  11486. }
  11487. }
  11488. return newValue;
  11489. };
  11490. GenericPad.prototype.update = function () {
  11491. _super.prototype.update.call(this);
  11492. for (var index = 0; index < this._buttons.length; index++) {
  11493. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11494. }
  11495. };
  11496. return GenericPad;
  11497. })(Gamepad);
  11498. BABYLON.GenericPad = GenericPad;
  11499. (function (Xbox360Button) {
  11500. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11501. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11502. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11503. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11504. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11505. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11506. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11507. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11508. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11509. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11510. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11511. var Xbox360Button = BABYLON.Xbox360Button;
  11512. (function (Xbox360Dpad) {
  11513. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11514. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11515. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11516. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11517. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11518. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11519. var Xbox360Pad = (function (_super) {
  11520. __extends(Xbox360Pad, _super);
  11521. function Xbox360Pad() {
  11522. _super.apply(this, arguments);
  11523. this._leftTrigger = 0;
  11524. this._rightTrigger = 0;
  11525. this._buttonA = 0;
  11526. this._buttonB = 0;
  11527. this._buttonX = 0;
  11528. this._buttonY = 0;
  11529. this._buttonBack = 0;
  11530. this._buttonStart = 0;
  11531. this._buttonLB = 0;
  11532. this._buttonRB = 0;
  11533. this._buttonLeftStick = 0;
  11534. this._buttonRightStick = 0;
  11535. this._dPadUp = 0;
  11536. this._dPadDown = 0;
  11537. this._dPadLeft = 0;
  11538. this._dPadRight = 0;
  11539. }
  11540. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11541. this._onlefttriggerchanged = callback;
  11542. };
  11543. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11544. this._onrighttriggerchanged = callback;
  11545. };
  11546. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11547. get: function () {
  11548. return this._leftTrigger;
  11549. },
  11550. set: function (newValue) {
  11551. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11552. this._onlefttriggerchanged(newValue);
  11553. }
  11554. this._leftTrigger = newValue;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11560. get: function () {
  11561. return this._rightTrigger;
  11562. },
  11563. set: function (newValue) {
  11564. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11565. this._onrighttriggerchanged(newValue);
  11566. }
  11567. this._rightTrigger = newValue;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11573. this._onbuttondown = callback;
  11574. };
  11575. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11576. this._onbuttonup = callback;
  11577. };
  11578. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11579. this._ondpaddown = callback;
  11580. };
  11581. Xbox360Pad.prototype.ondpadup = function (callback) {
  11582. this._ondpadup = callback;
  11583. };
  11584. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11585. if (newValue !== currentValue) {
  11586. if (this._onbuttondown && newValue === 1) {
  11587. this._onbuttondown(buttonType);
  11588. }
  11589. if (this._onbuttonup && newValue === 0) {
  11590. this._onbuttonup(buttonType);
  11591. }
  11592. }
  11593. return newValue;
  11594. };
  11595. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11596. if (newValue !== currentValue) {
  11597. if (this._ondpaddown && newValue === 1) {
  11598. this._ondpaddown(buttonType);
  11599. }
  11600. if (this._ondpadup && newValue === 0) {
  11601. this._ondpadup(buttonType);
  11602. }
  11603. }
  11604. return newValue;
  11605. };
  11606. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11607. get: function () {
  11608. return this._buttonA;
  11609. },
  11610. set: function (value) {
  11611. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11617. get: function () {
  11618. return this._buttonB;
  11619. },
  11620. set: function (value) {
  11621. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11627. get: function () {
  11628. return this._buttonX;
  11629. },
  11630. set: function (value) {
  11631. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11637. get: function () {
  11638. return this._buttonY;
  11639. },
  11640. set: function (value) {
  11641. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11647. get: function () {
  11648. return this._buttonStart;
  11649. },
  11650. set: function (value) {
  11651. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11657. get: function () {
  11658. return this._buttonBack;
  11659. },
  11660. set: function (value) {
  11661. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11667. get: function () {
  11668. return this._buttonLB;
  11669. },
  11670. set: function (value) {
  11671. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11677. get: function () {
  11678. return this._buttonRB;
  11679. },
  11680. set: function (value) {
  11681. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11687. get: function () {
  11688. return this._buttonLeftStick;
  11689. },
  11690. set: function (value) {
  11691. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11697. get: function () {
  11698. return this._buttonRightStick;
  11699. },
  11700. set: function (value) {
  11701. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11707. get: function () {
  11708. return this._dPadUp;
  11709. },
  11710. set: function (value) {
  11711. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11717. get: function () {
  11718. return this._dPadDown;
  11719. },
  11720. set: function (value) {
  11721. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11727. get: function () {
  11728. return this._dPadLeft;
  11729. },
  11730. set: function (value) {
  11731. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11737. get: function () {
  11738. return this._dPadRight;
  11739. },
  11740. set: function (value) {
  11741. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Xbox360Pad.prototype.update = function () {
  11747. _super.prototype.update.call(this);
  11748. this.buttonA = this.browserGamepad.buttons[0].value;
  11749. this.buttonB = this.browserGamepad.buttons[1].value;
  11750. this.buttonX = this.browserGamepad.buttons[2].value;
  11751. this.buttonY = this.browserGamepad.buttons[3].value;
  11752. this.buttonLB = this.browserGamepad.buttons[4].value;
  11753. this.buttonRB = this.browserGamepad.buttons[5].value;
  11754. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11755. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11756. this.buttonBack = this.browserGamepad.buttons[8].value;
  11757. this.buttonStart = this.browserGamepad.buttons[9].value;
  11758. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11759. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11760. this.dPadUp = this.browserGamepad.buttons[12].value;
  11761. this.dPadDown = this.browserGamepad.buttons[13].value;
  11762. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11763. this.dPadRight = this.browserGamepad.buttons[15].value;
  11764. };
  11765. return Xbox360Pad;
  11766. })(Gamepad);
  11767. BABYLON.Xbox360Pad = Xbox360Pad;
  11768. })(BABYLON || (BABYLON = {}));
  11769. //# sourceMappingURL=babylon.gamepads.js.map
  11770. var __extends = this.__extends || function (d, b) {
  11771. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11772. function __() { this.constructor = d; }
  11773. __.prototype = b.prototype;
  11774. d.prototype = new __();
  11775. };
  11776. var BABYLON;
  11777. (function (BABYLON) {
  11778. // We're mainly based on the logic defined into the FreeCamera code
  11779. var GamepadCamera = (function (_super) {
  11780. __extends(GamepadCamera, _super);
  11781. function GamepadCamera(name, position, scene) {
  11782. var _this = this;
  11783. _super.call(this, name, position, scene);
  11784. this.angularSensibility = 200;
  11785. this.moveSensibility = 75;
  11786. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11787. }
  11788. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11789. // Only the first gamepad can control the camera
  11790. if (gamepad.index === 0) {
  11791. this._gamepad = gamepad;
  11792. }
  11793. };
  11794. GamepadCamera.prototype._checkInputs = function () {
  11795. if (this._gamepad) {
  11796. var LSValues = this._gamepad.leftStick;
  11797. var normalizedLX = LSValues.x / this.moveSensibility;
  11798. var normalizedLY = LSValues.y / this.moveSensibility;
  11799. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11800. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11801. var RSValues = this._gamepad.rightStick;
  11802. var normalizedRX = RSValues.x / this.angularSensibility;
  11803. var normalizedRY = RSValues.y / this.angularSensibility;
  11804. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11805. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11806. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11807. var speed = this._computeLocalCameraSpeed() * 50.0;
  11808. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11809. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11810. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11811. }
  11812. _super.prototype._checkInputs.call(this);
  11813. };
  11814. GamepadCamera.prototype.dispose = function () {
  11815. this._gamepads.dispose();
  11816. _super.prototype.dispose.call(this);
  11817. };
  11818. return GamepadCamera;
  11819. })(BABYLON.FreeCamera);
  11820. BABYLON.GamepadCamera = GamepadCamera;
  11821. })(BABYLON || (BABYLON = {}));
  11822. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11823. var BABYLON;
  11824. (function (BABYLON) {
  11825. var RenderingManager = (function () {
  11826. function RenderingManager(scene) {
  11827. this._renderingGroups = new Array();
  11828. this._scene = scene;
  11829. }
  11830. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11831. if (this._scene._activeParticleSystems.length === 0) {
  11832. return;
  11833. }
  11834. // Particles
  11835. var beforeParticlesDate = BABYLON.Tools.Now;
  11836. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11837. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11838. if (particleSystem.renderingGroupId !== index) {
  11839. continue;
  11840. }
  11841. this._clearDepthBuffer();
  11842. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11843. this._scene._activeParticles += particleSystem.render();
  11844. }
  11845. }
  11846. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11847. };
  11848. RenderingManager.prototype._renderSprites = function (index) {
  11849. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11850. return;
  11851. }
  11852. // Sprites
  11853. var beforeSpritessDate = BABYLON.Tools.Now;
  11854. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11855. var spriteManager = this._scene.spriteManagers[id];
  11856. if (spriteManager.renderingGroupId === index) {
  11857. this._clearDepthBuffer();
  11858. spriteManager.render();
  11859. }
  11860. }
  11861. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11862. };
  11863. RenderingManager.prototype._clearDepthBuffer = function () {
  11864. if (this._depthBufferAlreadyCleaned) {
  11865. return;
  11866. }
  11867. this._scene.getEngine().clear(0, false, true);
  11868. this._depthBufferAlreadyCleaned = true;
  11869. };
  11870. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11871. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11872. this._depthBufferAlreadyCleaned = false;
  11873. var renderingGroup = this._renderingGroups[index];
  11874. var needToStepBack = false;
  11875. if (renderingGroup) {
  11876. this._clearDepthBuffer();
  11877. if (!renderingGroup.render(customRenderFunction)) {
  11878. this._renderingGroups.splice(index, 1);
  11879. needToStepBack = true;
  11880. }
  11881. }
  11882. if (renderSprites) {
  11883. this._renderSprites(index);
  11884. }
  11885. if (renderParticles) {
  11886. this._renderParticles(index, activeMeshes);
  11887. }
  11888. if (needToStepBack) {
  11889. index--;
  11890. }
  11891. }
  11892. };
  11893. RenderingManager.prototype.reset = function () {
  11894. for (var index in this._renderingGroups) {
  11895. var renderingGroup = this._renderingGroups[index];
  11896. renderingGroup.prepare();
  11897. }
  11898. };
  11899. RenderingManager.prototype.dispatch = function (subMesh) {
  11900. var mesh = subMesh.getMesh();
  11901. var renderingGroupId = mesh.renderingGroupId || 0;
  11902. if (!this._renderingGroups[renderingGroupId]) {
  11903. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11904. }
  11905. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11906. };
  11907. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11908. return RenderingManager;
  11909. })();
  11910. BABYLON.RenderingManager = RenderingManager;
  11911. })(BABYLON || (BABYLON = {}));
  11912. //# sourceMappingURL=babylon.renderingManager.js.map
  11913. var BABYLON;
  11914. (function (BABYLON) {
  11915. var RenderingGroup = (function () {
  11916. function RenderingGroup(index, scene) {
  11917. this.index = index;
  11918. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11919. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11920. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11921. this._scene = scene;
  11922. }
  11923. RenderingGroup.prototype.render = function (customRenderFunction) {
  11924. if (customRenderFunction) {
  11925. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11926. return true;
  11927. }
  11928. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11929. return false;
  11930. }
  11931. var engine = this._scene.getEngine();
  11932. // Opaque
  11933. var subIndex;
  11934. var submesh;
  11935. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11936. submesh = this._opaqueSubMeshes.data[subIndex];
  11937. submesh.render();
  11938. }
  11939. // Alpha test
  11940. engine.setAlphaTesting(true);
  11941. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11942. submesh = this._alphaTestSubMeshes.data[subIndex];
  11943. submesh.render();
  11944. }
  11945. engine.setAlphaTesting(false);
  11946. // Transparent
  11947. if (this._transparentSubMeshes.length) {
  11948. // Sorting
  11949. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11950. submesh = this._transparentSubMeshes.data[subIndex];
  11951. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11952. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11953. }
  11954. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11955. sortedArray.sort(function (a, b) {
  11956. // Alpha index first
  11957. if (a._alphaIndex > b._alphaIndex) {
  11958. return 1;
  11959. }
  11960. if (a._alphaIndex < b._alphaIndex) {
  11961. return -1;
  11962. }
  11963. // Then distance to camera
  11964. if (a._distanceToCamera < b._distanceToCamera) {
  11965. return 1;
  11966. }
  11967. if (a._distanceToCamera > b._distanceToCamera) {
  11968. return -1;
  11969. }
  11970. return 0;
  11971. });
  11972. // Rendering
  11973. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11974. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11975. submesh = sortedArray[subIndex];
  11976. submesh.render();
  11977. }
  11978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11979. }
  11980. return true;
  11981. };
  11982. RenderingGroup.prototype.prepare = function () {
  11983. this._opaqueSubMeshes.reset();
  11984. this._transparentSubMeshes.reset();
  11985. this._alphaTestSubMeshes.reset();
  11986. };
  11987. RenderingGroup.prototype.dispatch = function (subMesh) {
  11988. var material = subMesh.getMaterial();
  11989. var mesh = subMesh.getMesh();
  11990. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11991. this._transparentSubMeshes.push(subMesh);
  11992. }
  11993. else if (material.needAlphaTesting()) {
  11994. this._alphaTestSubMeshes.push(subMesh);
  11995. }
  11996. else {
  11997. this._opaqueSubMeshes.push(subMesh); // Opaque
  11998. }
  11999. };
  12000. return RenderingGroup;
  12001. })();
  12002. BABYLON.RenderingGroup = RenderingGroup;
  12003. })(BABYLON || (BABYLON = {}));
  12004. //# sourceMappingURL=babylon.renderingGroup.js.map
  12005. var BABYLON;
  12006. (function (BABYLON) {
  12007. /**
  12008. * Represents a scene to be rendered by the engine.
  12009. * @see http://doc.babylonjs.com/page.php?p=21911
  12010. */
  12011. var Scene = (function () {
  12012. /**
  12013. * @constructor
  12014. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12015. */
  12016. function Scene(engine) {
  12017. // Members
  12018. this.autoClear = true;
  12019. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12020. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12021. this.forceWireframe = false;
  12022. this.forcePointsCloud = false;
  12023. this.forceShowBoundingBoxes = false;
  12024. this.animationsEnabled = true;
  12025. 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
  12026. // Fog
  12027. /**
  12028. * is fog enabled on this scene.
  12029. * @type {boolean}
  12030. */
  12031. this.fogEnabled = true;
  12032. this.fogMode = Scene.FOGMODE_NONE;
  12033. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12034. this.fogDensity = 0.1;
  12035. this.fogStart = 0;
  12036. this.fogEnd = 1000.0;
  12037. // Lights
  12038. /**
  12039. * is shadow enabled on this scene.
  12040. * @type {boolean}
  12041. */
  12042. this.shadowsEnabled = true;
  12043. /**
  12044. * is light enabled on this scene.
  12045. * @type {boolean}
  12046. */
  12047. this.lightsEnabled = true;
  12048. /**
  12049. * All of the lights added to this scene.
  12050. * @see BABYLON.Light
  12051. * @type {BABYLON.Light[]}
  12052. */
  12053. this.lights = new Array();
  12054. // Cameras
  12055. /**
  12056. * All of the cameras added to this scene.
  12057. * @see BABYLON.Camera
  12058. * @type {BABYLON.Camera[]}
  12059. */
  12060. this.cameras = new Array();
  12061. this.activeCameras = new Array();
  12062. // Meshes
  12063. /**
  12064. * All of the (abstract) meshes added to this scene.
  12065. * @see BABYLON.AbstractMesh
  12066. * @type {BABYLON.AbstractMesh[]}
  12067. */
  12068. this.meshes = new Array();
  12069. // Geometries
  12070. this._geometries = new Array();
  12071. this.materials = new Array();
  12072. this.multiMaterials = new Array();
  12073. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12074. // Textures
  12075. this.texturesEnabled = true;
  12076. this.textures = new Array();
  12077. // Particles
  12078. this.particlesEnabled = true;
  12079. this.particleSystems = new Array();
  12080. // Sprites
  12081. this.spritesEnabled = true;
  12082. this.spriteManagers = new Array();
  12083. // Layers
  12084. this.layers = new Array();
  12085. // Skeletons
  12086. this.skeletonsEnabled = true;
  12087. this.skeletons = new Array();
  12088. // Lens flares
  12089. this.lensFlaresEnabled = true;
  12090. this.lensFlareSystems = new Array();
  12091. // Collisions
  12092. this.collisionsEnabled = true;
  12093. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12094. // Postprocesses
  12095. this.postProcessesEnabled = true;
  12096. // Customs render targets
  12097. this.renderTargetsEnabled = true;
  12098. this.dumpNextRenderTargets = false;
  12099. this.customRenderTargets = new Array();
  12100. // Imported meshes
  12101. this.importedMeshesFiles = new Array();
  12102. this._actionManagers = new Array();
  12103. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12104. // Procedural textures
  12105. this.proceduralTexturesEnabled = true;
  12106. this._proceduralTextures = new Array();
  12107. this.soundTracks = new Array();
  12108. this._audioEnabled = true;
  12109. this._headphone = false;
  12110. this._totalVertices = 0;
  12111. this._activeIndices = 0;
  12112. this._activeParticles = 0;
  12113. this._lastFrameDuration = 0;
  12114. this._evaluateActiveMeshesDuration = 0;
  12115. this._renderTargetsDuration = 0;
  12116. this._particlesDuration = 0;
  12117. this._renderDuration = 0;
  12118. this._spritesDuration = 0;
  12119. this._animationRatio = 0;
  12120. this._renderId = 0;
  12121. this._executeWhenReadyTimeoutId = -1;
  12122. this._toBeDisposed = new BABYLON.SmartArray(256);
  12123. this._onReadyCallbacks = new Array();
  12124. this._pendingData = []; //ANY
  12125. this._onBeforeRenderCallbacks = new Array();
  12126. this._onAfterRenderCallbacks = new Array();
  12127. this._activeMeshes = new BABYLON.SmartArray(256);
  12128. this._processedMaterials = new BABYLON.SmartArray(256);
  12129. this._renderTargets = new BABYLON.SmartArray(256);
  12130. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12131. this._activeSkeletons = new BABYLON.SmartArray(32);
  12132. this._activeBones = 0;
  12133. this._activeAnimatables = new Array();
  12134. this._transformMatrix = BABYLON.Matrix.Zero();
  12135. this._uniqueIdCounter = 0;
  12136. this._engine = engine;
  12137. engine.scenes.push(this);
  12138. this._renderingManager = new BABYLON.RenderingManager(this);
  12139. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12140. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12141. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12142. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12143. this.attachControl();
  12144. this._debugLayer = new BABYLON.DebugLayer(this);
  12145. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12146. //simplification queue
  12147. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12148. //collision coordinator initialization. For now legacy per default.
  12149. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12150. }
  12151. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12152. get: function () {
  12153. return Scene._FOGMODE_NONE;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12159. get: function () {
  12160. return Scene._FOGMODE_EXP;
  12161. },
  12162. enumerable: true,
  12163. configurable: true
  12164. });
  12165. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12166. get: function () {
  12167. return Scene._FOGMODE_EXP2;
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12173. get: function () {
  12174. return Scene._FOGMODE_LINEAR;
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(Scene.prototype, "debugLayer", {
  12180. // Properties
  12181. get: function () {
  12182. return this._debugLayer;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12188. get: function () {
  12189. return this._workerCollisions;
  12190. },
  12191. set: function (enabled) {
  12192. enabled = (enabled && !!Worker);
  12193. this._workerCollisions = enabled;
  12194. if (this.collisionCoordinator) {
  12195. this.collisionCoordinator.destroy();
  12196. }
  12197. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12198. this.collisionCoordinator.init(this);
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12204. /**
  12205. * The mesh that is currently under the pointer.
  12206. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12207. */
  12208. get: function () {
  12209. return this._meshUnderPointer;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Scene.prototype, "pointerX", {
  12215. /**
  12216. * Current on-screen X position of the pointer
  12217. * @return {number} X position of the pointer
  12218. */
  12219. get: function () {
  12220. return this._pointerX;
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(Scene.prototype, "pointerY", {
  12226. /**
  12227. * Current on-screen Y position of the pointer
  12228. * @return {number} Y position of the pointer
  12229. */
  12230. get: function () {
  12231. return this._pointerY;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Scene.prototype.getCachedMaterial = function () {
  12237. return this._cachedMaterial;
  12238. };
  12239. Scene.prototype.getBoundingBoxRenderer = function () {
  12240. return this._boundingBoxRenderer;
  12241. };
  12242. Scene.prototype.getOutlineRenderer = function () {
  12243. return this._outlineRenderer;
  12244. };
  12245. Scene.prototype.getEngine = function () {
  12246. return this._engine;
  12247. };
  12248. Scene.prototype.getTotalVertices = function () {
  12249. return this._totalVertices;
  12250. };
  12251. Scene.prototype.getActiveIndices = function () {
  12252. return this._activeIndices;
  12253. };
  12254. Scene.prototype.getActiveParticles = function () {
  12255. return this._activeParticles;
  12256. };
  12257. Scene.prototype.getActiveBones = function () {
  12258. return this._activeBones;
  12259. };
  12260. // Stats
  12261. Scene.prototype.getLastFrameDuration = function () {
  12262. return this._lastFrameDuration;
  12263. };
  12264. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12265. return this._evaluateActiveMeshesDuration;
  12266. };
  12267. Scene.prototype.getActiveMeshes = function () {
  12268. return this._activeMeshes;
  12269. };
  12270. Scene.prototype.getRenderTargetsDuration = function () {
  12271. return this._renderTargetsDuration;
  12272. };
  12273. Scene.prototype.getRenderDuration = function () {
  12274. return this._renderDuration;
  12275. };
  12276. Scene.prototype.getParticlesDuration = function () {
  12277. return this._particlesDuration;
  12278. };
  12279. Scene.prototype.getSpritesDuration = function () {
  12280. return this._spritesDuration;
  12281. };
  12282. Scene.prototype.getAnimationRatio = function () {
  12283. return this._animationRatio;
  12284. };
  12285. Scene.prototype.getRenderId = function () {
  12286. return this._renderId;
  12287. };
  12288. Scene.prototype.incrementRenderId = function () {
  12289. this._renderId++;
  12290. };
  12291. Scene.prototype._updatePointerPosition = function (evt) {
  12292. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12293. this._pointerX = evt.clientX - canvasRect.left;
  12294. this._pointerY = evt.clientY - canvasRect.top;
  12295. if (this.cameraToUseForPointers) {
  12296. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12297. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12298. }
  12299. };
  12300. // Pointers handling
  12301. Scene.prototype.attachControl = function () {
  12302. var _this = this;
  12303. this._onPointerMove = function (evt) {
  12304. var canvas = _this._engine.getRenderingCanvas();
  12305. _this._updatePointerPosition(evt);
  12306. 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);
  12307. if (pickResult.hit) {
  12308. _this._meshUnderPointer = pickResult.pickedMesh;
  12309. _this.setPointerOverMesh(pickResult.pickedMesh);
  12310. canvas.style.cursor = "pointer";
  12311. }
  12312. else {
  12313. _this.setPointerOverMesh(null);
  12314. canvas.style.cursor = "";
  12315. _this._meshUnderPointer = null;
  12316. }
  12317. };
  12318. this._onPointerDown = function (evt) {
  12319. var predicate = null;
  12320. if (!_this.onPointerDown) {
  12321. predicate = function (mesh) {
  12322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12323. };
  12324. }
  12325. _this._updatePointerPosition(evt);
  12326. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12327. if (pickResult.hit) {
  12328. if (pickResult.pickedMesh.actionManager) {
  12329. switch (evt.button) {
  12330. case 0:
  12331. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12332. break;
  12333. case 1:
  12334. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12335. break;
  12336. case 2:
  12337. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12338. break;
  12339. }
  12340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12341. }
  12342. }
  12343. if (_this.onPointerDown) {
  12344. _this.onPointerDown(evt, pickResult);
  12345. }
  12346. };
  12347. this._onPointerUp = function (evt) {
  12348. var predicate = null;
  12349. if (!_this.onPointerUp) {
  12350. predicate = function (mesh) {
  12351. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12352. };
  12353. }
  12354. _this._updatePointerPosition(evt);
  12355. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12356. if (pickResult.hit) {
  12357. if (pickResult.pickedMesh.actionManager) {
  12358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12359. }
  12360. }
  12361. if (_this.onPointerUp) {
  12362. _this.onPointerUp(evt, pickResult);
  12363. }
  12364. };
  12365. this._onKeyDown = function (evt) {
  12366. if (_this.actionManager) {
  12367. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12368. }
  12369. };
  12370. this._onKeyUp = function (evt) {
  12371. if (_this.actionManager) {
  12372. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12373. }
  12374. };
  12375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12376. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12377. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12378. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12379. BABYLON.Tools.RegisterTopRootEvents([
  12380. { name: "keydown", handler: this._onKeyDown },
  12381. { name: "keyup", handler: this._onKeyUp }
  12382. ]);
  12383. };
  12384. Scene.prototype.detachControl = function () {
  12385. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12386. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12387. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12388. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12389. BABYLON.Tools.UnregisterTopRootEvents([
  12390. { name: "keydown", handler: this._onKeyDown },
  12391. { name: "keyup", handler: this._onKeyUp }
  12392. ]);
  12393. };
  12394. // Ready
  12395. Scene.prototype.isReady = function () {
  12396. if (this._pendingData.length > 0) {
  12397. return false;
  12398. }
  12399. for (var index = 0; index < this._geometries.length; index++) {
  12400. var geometry = this._geometries[index];
  12401. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12402. return false;
  12403. }
  12404. }
  12405. for (index = 0; index < this.meshes.length; index++) {
  12406. var mesh = this.meshes[index];
  12407. if (!mesh.isReady()) {
  12408. return false;
  12409. }
  12410. var mat = mesh.material;
  12411. if (mat) {
  12412. if (!mat.isReady(mesh)) {
  12413. return false;
  12414. }
  12415. }
  12416. }
  12417. return true;
  12418. };
  12419. Scene.prototype.resetCachedMaterial = function () {
  12420. this._cachedMaterial = null;
  12421. };
  12422. Scene.prototype.registerBeforeRender = function (func) {
  12423. this._onBeforeRenderCallbacks.push(func);
  12424. };
  12425. Scene.prototype.unregisterBeforeRender = function (func) {
  12426. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12427. if (index > -1) {
  12428. this._onBeforeRenderCallbacks.splice(index, 1);
  12429. }
  12430. };
  12431. Scene.prototype.registerAfterRender = function (func) {
  12432. this._onAfterRenderCallbacks.push(func);
  12433. };
  12434. Scene.prototype.unregisterAfterRender = function (func) {
  12435. var index = this._onAfterRenderCallbacks.indexOf(func);
  12436. if (index > -1) {
  12437. this._onAfterRenderCallbacks.splice(index, 1);
  12438. }
  12439. };
  12440. Scene.prototype._addPendingData = function (data) {
  12441. this._pendingData.push(data);
  12442. };
  12443. Scene.prototype._removePendingData = function (data) {
  12444. var index = this._pendingData.indexOf(data);
  12445. if (index !== -1) {
  12446. this._pendingData.splice(index, 1);
  12447. }
  12448. };
  12449. Scene.prototype.getWaitingItemsCount = function () {
  12450. return this._pendingData.length;
  12451. };
  12452. /**
  12453. * Registers a function to be executed when the scene is ready.
  12454. * @param {Function} func - the function to be executed.
  12455. */
  12456. Scene.prototype.executeWhenReady = function (func) {
  12457. var _this = this;
  12458. this._onReadyCallbacks.push(func);
  12459. if (this._executeWhenReadyTimeoutId !== -1) {
  12460. return;
  12461. }
  12462. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12463. _this._checkIsReady();
  12464. }, 150);
  12465. };
  12466. Scene.prototype._checkIsReady = function () {
  12467. var _this = this;
  12468. if (this.isReady()) {
  12469. this._onReadyCallbacks.forEach(function (func) {
  12470. func();
  12471. });
  12472. this._onReadyCallbacks = [];
  12473. this._executeWhenReadyTimeoutId = -1;
  12474. return;
  12475. }
  12476. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12477. _this._checkIsReady();
  12478. }, 150);
  12479. };
  12480. // Animations
  12481. /**
  12482. * Will start the animation sequence of a given target
  12483. * @param target - the target
  12484. * @param {number} from - from which frame should animation start
  12485. * @param {number} to - till which frame should animation run.
  12486. * @param {boolean} [loop] - should the animation loop
  12487. * @param {number} [speedRatio] - the speed in which to run the animation
  12488. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12489. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12490. * @return {BABYLON.Animatable} the animatable object created for this animation
  12491. * @see BABYLON.Animatable
  12492. * @see http://doc.babylonjs.com/page.php?p=22081
  12493. */
  12494. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12495. if (speedRatio === undefined) {
  12496. speedRatio = 1.0;
  12497. }
  12498. this.stopAnimation(target);
  12499. if (!animatable) {
  12500. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12501. }
  12502. // Local animations
  12503. if (target.animations) {
  12504. animatable.appendAnimations(target, target.animations);
  12505. }
  12506. // Children animations
  12507. if (target.getAnimatables) {
  12508. var animatables = target.getAnimatables();
  12509. for (var index = 0; index < animatables.length; index++) {
  12510. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12511. }
  12512. }
  12513. return animatable;
  12514. };
  12515. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12516. if (speedRatio === undefined) {
  12517. speedRatio = 1.0;
  12518. }
  12519. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12520. return animatable;
  12521. };
  12522. Scene.prototype.getAnimatableByTarget = function (target) {
  12523. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12524. if (this._activeAnimatables[index].target === target) {
  12525. return this._activeAnimatables[index];
  12526. }
  12527. }
  12528. return null;
  12529. };
  12530. /**
  12531. * Will stop the animation of the given target
  12532. * @param target - the target
  12533. * @see beginAnimation
  12534. */
  12535. Scene.prototype.stopAnimation = function (target) {
  12536. var animatable = this.getAnimatableByTarget(target);
  12537. if (animatable) {
  12538. animatable.stop();
  12539. }
  12540. };
  12541. Scene.prototype._animate = function () {
  12542. if (!this.animationsEnabled) {
  12543. return;
  12544. }
  12545. if (!this._animationStartDate) {
  12546. this._animationStartDate = BABYLON.Tools.Now;
  12547. }
  12548. // Getting time
  12549. var now = BABYLON.Tools.Now;
  12550. var delay = now - this._animationStartDate;
  12551. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12552. this._activeAnimatables[index]._animate(delay);
  12553. }
  12554. };
  12555. // Matrix
  12556. Scene.prototype.getViewMatrix = function () {
  12557. return this._viewMatrix;
  12558. };
  12559. Scene.prototype.getProjectionMatrix = function () {
  12560. return this._projectionMatrix;
  12561. };
  12562. Scene.prototype.getTransformMatrix = function () {
  12563. return this._transformMatrix;
  12564. };
  12565. Scene.prototype.setTransformMatrix = function (view, projection) {
  12566. this._viewMatrix = view;
  12567. this._projectionMatrix = projection;
  12568. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12569. };
  12570. // Methods
  12571. Scene.prototype.addMesh = function (newMesh) {
  12572. newMesh.uniqueId = this._uniqueIdCounter++;
  12573. var position = this.meshes.push(newMesh);
  12574. //notify the collision coordinator
  12575. this.collisionCoordinator.onMeshAdded(newMesh);
  12576. if (this.onNewMeshAdded) {
  12577. this.onNewMeshAdded(newMesh, position, this);
  12578. }
  12579. };
  12580. Scene.prototype.removeMesh = function (toRemove) {
  12581. var index = this.meshes.indexOf(toRemove);
  12582. if (index !== -1) {
  12583. // Remove from the scene if mesh found
  12584. this.meshes.splice(index, 1);
  12585. }
  12586. //notify the collision coordinator
  12587. this.collisionCoordinator.onMeshRemoved(toRemove);
  12588. if (this.onMeshRemoved) {
  12589. this.onMeshRemoved(toRemove);
  12590. }
  12591. return index;
  12592. };
  12593. Scene.prototype.removeLight = function (toRemove) {
  12594. var index = this.lights.indexOf(toRemove);
  12595. if (index !== -1) {
  12596. // Remove from the scene if mesh found
  12597. this.lights.splice(index, 1);
  12598. }
  12599. if (this.onLightRemoved) {
  12600. this.onLightRemoved(toRemove);
  12601. }
  12602. return index;
  12603. };
  12604. Scene.prototype.removeCamera = function (toRemove) {
  12605. var index = this.cameras.indexOf(toRemove);
  12606. if (index !== -1) {
  12607. // Remove from the scene if mesh found
  12608. this.cameras.splice(index, 1);
  12609. }
  12610. // Remove from activeCameras
  12611. var index2 = this.activeCameras.indexOf(toRemove);
  12612. if (index2 !== -1) {
  12613. // Remove from the scene if mesh found
  12614. this.activeCameras.splice(index2, 1);
  12615. }
  12616. // Reset the activeCamera
  12617. if (this.activeCamera === toRemove) {
  12618. if (this.cameras.length > 0) {
  12619. this.activeCamera = this.cameras[0];
  12620. }
  12621. else {
  12622. this.activeCamera = null;
  12623. }
  12624. }
  12625. if (this.onCameraRemoved) {
  12626. this.onCameraRemoved(toRemove);
  12627. }
  12628. return index;
  12629. };
  12630. Scene.prototype.addLight = function (newLight) {
  12631. newLight.uniqueId = this._uniqueIdCounter++;
  12632. var position = this.lights.push(newLight);
  12633. if (this.onNewLightAdded) {
  12634. this.onNewLightAdded(newLight, position, this);
  12635. }
  12636. };
  12637. Scene.prototype.addCamera = function (newCamera) {
  12638. newCamera.uniqueId = this._uniqueIdCounter++;
  12639. var position = this.cameras.push(newCamera);
  12640. if (this.onNewCameraAdded) {
  12641. this.onNewCameraAdded(newCamera, position, this);
  12642. }
  12643. };
  12644. /**
  12645. * sets the active camera of the scene using its ID
  12646. * @param {string} id - the camera's ID
  12647. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12648. * @see activeCamera
  12649. */
  12650. Scene.prototype.setActiveCameraByID = function (id) {
  12651. var camera = this.getCameraByID(id);
  12652. if (camera) {
  12653. this.activeCamera = camera;
  12654. return camera;
  12655. }
  12656. return null;
  12657. };
  12658. /**
  12659. * sets the active camera of the scene using its name
  12660. * @param {string} name - the camera's name
  12661. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12662. * @see activeCamera
  12663. */
  12664. Scene.prototype.setActiveCameraByName = function (name) {
  12665. var camera = this.getCameraByName(name);
  12666. if (camera) {
  12667. this.activeCamera = camera;
  12668. return camera;
  12669. }
  12670. return null;
  12671. };
  12672. /**
  12673. * get a material using its id
  12674. * @param {string} the material's ID
  12675. * @return {BABYLON.Material|null} the material or null if none found.
  12676. */
  12677. Scene.prototype.getMaterialByID = function (id) {
  12678. for (var index = 0; index < this.materials.length; index++) {
  12679. if (this.materials[index].id === id) {
  12680. return this.materials[index];
  12681. }
  12682. }
  12683. return null;
  12684. };
  12685. /**
  12686. * get a material using its name
  12687. * @param {string} the material's name
  12688. * @return {BABYLON.Material|null} the material or null if none found.
  12689. */
  12690. Scene.prototype.getMaterialByName = function (name) {
  12691. for (var index = 0; index < this.materials.length; index++) {
  12692. if (this.materials[index].name === name) {
  12693. return this.materials[index];
  12694. }
  12695. }
  12696. return null;
  12697. };
  12698. Scene.prototype.getCameraByID = function (id) {
  12699. for (var index = 0; index < this.cameras.length; index++) {
  12700. if (this.cameras[index].id === id) {
  12701. return this.cameras[index];
  12702. }
  12703. }
  12704. return null;
  12705. };
  12706. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12707. for (var index = 0; index < this.cameras.length; index++) {
  12708. if (this.cameras[index].uniqueId === uniqueId) {
  12709. return this.cameras[index];
  12710. }
  12711. }
  12712. return null;
  12713. };
  12714. /**
  12715. * get a camera using its name
  12716. * @param {string} the camera's name
  12717. * @return {BABYLON.Camera|null} the camera or null if none found.
  12718. */
  12719. Scene.prototype.getCameraByName = function (name) {
  12720. for (var index = 0; index < this.cameras.length; index++) {
  12721. if (this.cameras[index].name === name) {
  12722. return this.cameras[index];
  12723. }
  12724. }
  12725. return null;
  12726. };
  12727. /**
  12728. * get a light node using its name
  12729. * @param {string} the light's name
  12730. * @return {BABYLON.Light|null} the light or null if none found.
  12731. */
  12732. Scene.prototype.getLightByName = function (name) {
  12733. for (var index = 0; index < this.lights.length; index++) {
  12734. if (this.lights[index].name === name) {
  12735. return this.lights[index];
  12736. }
  12737. }
  12738. return null;
  12739. };
  12740. /**
  12741. * get a light node using its ID
  12742. * @param {string} the light's id
  12743. * @return {BABYLON.Light|null} the light or null if none found.
  12744. */
  12745. Scene.prototype.getLightByID = function (id) {
  12746. for (var index = 0; index < this.lights.length; index++) {
  12747. if (this.lights[index].id === id) {
  12748. return this.lights[index];
  12749. }
  12750. }
  12751. return null;
  12752. };
  12753. /**
  12754. * get a light node using its scene-generated unique ID
  12755. * @param {number} the light's unique id
  12756. * @return {BABYLON.Light|null} the light or null if none found.
  12757. */
  12758. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12759. for (var index = 0; index < this.lights.length; index++) {
  12760. if (this.lights[index].uniqueId === uniqueId) {
  12761. return this.lights[index];
  12762. }
  12763. }
  12764. return null;
  12765. };
  12766. /**
  12767. * get a geometry using its ID
  12768. * @param {string} the geometry's id
  12769. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12770. */
  12771. Scene.prototype.getGeometryByID = function (id) {
  12772. for (var index = 0; index < this._geometries.length; index++) {
  12773. if (this._geometries[index].id === id) {
  12774. return this._geometries[index];
  12775. }
  12776. }
  12777. return null;
  12778. };
  12779. /**
  12780. * add a new geometry to this scene.
  12781. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12782. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12783. * @return {boolean} was the geometry added or not
  12784. */
  12785. Scene.prototype.pushGeometry = function (geometry, force) {
  12786. if (!force && this.getGeometryByID(geometry.id)) {
  12787. return false;
  12788. }
  12789. this._geometries.push(geometry);
  12790. //notify the collision coordinator
  12791. this.collisionCoordinator.onGeometryAdded(geometry);
  12792. if (this.onGeometryAdded) {
  12793. this.onGeometryAdded(geometry);
  12794. }
  12795. return true;
  12796. };
  12797. /**
  12798. * Removes an existing geometry
  12799. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12800. * @return {boolean} was the geometry removed or not
  12801. */
  12802. Scene.prototype.removeGeometry = function (geometry) {
  12803. var index = this._geometries.indexOf(geometry);
  12804. if (index > -1) {
  12805. this._geometries.splice(index, 1);
  12806. //notify the collision coordinator
  12807. this.collisionCoordinator.onGeometryDeleted(geometry);
  12808. if (this.onGeometryRemoved) {
  12809. this.onGeometryRemoved(geometry);
  12810. }
  12811. return true;
  12812. }
  12813. return false;
  12814. };
  12815. Scene.prototype.getGeometries = function () {
  12816. return this._geometries;
  12817. };
  12818. /**
  12819. * Get the first added mesh found of a given ID
  12820. * @param {string} id - the id to search for
  12821. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12822. */
  12823. Scene.prototype.getMeshByID = function (id) {
  12824. for (var index = 0; index < this.meshes.length; index++) {
  12825. if (this.meshes[index].id === id) {
  12826. return this.meshes[index];
  12827. }
  12828. }
  12829. return null;
  12830. };
  12831. /**
  12832. * Get a mesh with its auto-generated unique id
  12833. * @param {number} uniqueId - the unique id to search for
  12834. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12835. */
  12836. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12837. for (var index = 0; index < this.meshes.length; index++) {
  12838. if (this.meshes[index].uniqueId === uniqueId) {
  12839. return this.meshes[index];
  12840. }
  12841. }
  12842. return null;
  12843. };
  12844. /**
  12845. * Get a the last added mesh found of a given ID
  12846. * @param {string} id - the id to search for
  12847. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12848. */
  12849. Scene.prototype.getLastMeshByID = function (id) {
  12850. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12851. if (this.meshes[index].id === id) {
  12852. return this.meshes[index];
  12853. }
  12854. }
  12855. return null;
  12856. };
  12857. /**
  12858. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12859. * @param {string} id - the id to search for
  12860. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12861. */
  12862. Scene.prototype.getLastEntryByID = function (id) {
  12863. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12864. if (this.meshes[index].id === id) {
  12865. return this.meshes[index];
  12866. }
  12867. }
  12868. for (index = this.cameras.length - 1; index >= 0; index--) {
  12869. if (this.cameras[index].id === id) {
  12870. return this.cameras[index];
  12871. }
  12872. }
  12873. for (index = this.lights.length - 1; index >= 0; index--) {
  12874. if (this.lights[index].id === id) {
  12875. return this.lights[index];
  12876. }
  12877. }
  12878. return null;
  12879. };
  12880. Scene.prototype.getNodeByName = function (name) {
  12881. var mesh = this.getMeshByName(name);
  12882. if (mesh) {
  12883. return mesh;
  12884. }
  12885. var light = this.getLightByName(name);
  12886. if (light) {
  12887. return light;
  12888. }
  12889. return this.getCameraByName(name);
  12890. };
  12891. Scene.prototype.getMeshByName = function (name) {
  12892. for (var index = 0; index < this.meshes.length; index++) {
  12893. if (this.meshes[index].name === name) {
  12894. return this.meshes[index];
  12895. }
  12896. }
  12897. return null;
  12898. };
  12899. Scene.prototype.getSoundByName = function (name) {
  12900. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12901. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12902. return this.mainSoundTrack.soundCollection[index];
  12903. }
  12904. }
  12905. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12906. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12907. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12908. return this.soundTracks[sdIndex].soundCollection[index];
  12909. }
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. Scene.prototype.getLastSkeletonByID = function (id) {
  12915. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12916. if (this.skeletons[index].id === id) {
  12917. return this.skeletons[index];
  12918. }
  12919. }
  12920. return null;
  12921. };
  12922. Scene.prototype.getSkeletonById = function (id) {
  12923. for (var index = 0; index < this.skeletons.length; index++) {
  12924. if (this.skeletons[index].id === id) {
  12925. return this.skeletons[index];
  12926. }
  12927. }
  12928. return null;
  12929. };
  12930. Scene.prototype.getSkeletonByName = function (name) {
  12931. for (var index = 0; index < this.skeletons.length; index++) {
  12932. if (this.skeletons[index].name === name) {
  12933. return this.skeletons[index];
  12934. }
  12935. }
  12936. return null;
  12937. };
  12938. Scene.prototype.isActiveMesh = function (mesh) {
  12939. return (this._activeMeshes.indexOf(mesh) !== -1);
  12940. };
  12941. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12942. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12943. var material = subMesh.getMaterial();
  12944. if (mesh.showSubMeshesBoundingBox) {
  12945. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12946. }
  12947. if (material) {
  12948. // Render targets
  12949. if (material.getRenderTargetTextures) {
  12950. if (this._processedMaterials.indexOf(material) === -1) {
  12951. this._processedMaterials.push(material);
  12952. this._renderTargets.concat(material.getRenderTargetTextures());
  12953. }
  12954. }
  12955. // Dispatch
  12956. this._activeIndices += subMesh.indexCount;
  12957. this._renderingManager.dispatch(subMesh);
  12958. }
  12959. }
  12960. };
  12961. Scene.prototype._evaluateActiveMeshes = function () {
  12962. this.activeCamera._activeMeshes.reset();
  12963. this._activeMeshes.reset();
  12964. this._renderingManager.reset();
  12965. this._processedMaterials.reset();
  12966. this._activeParticleSystems.reset();
  12967. this._activeSkeletons.reset();
  12968. this._boundingBoxRenderer.reset();
  12969. if (!this._frustumPlanes) {
  12970. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12971. }
  12972. else {
  12973. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12974. }
  12975. // Meshes
  12976. var meshes;
  12977. var len;
  12978. if (this._selectionOctree) {
  12979. var selection = this._selectionOctree.select(this._frustumPlanes);
  12980. meshes = selection.data;
  12981. len = selection.length;
  12982. }
  12983. else {
  12984. len = this.meshes.length;
  12985. meshes = this.meshes;
  12986. }
  12987. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12988. var mesh = meshes[meshIndex];
  12989. if (mesh.isBlocked) {
  12990. continue;
  12991. }
  12992. this._totalVertices += mesh.getTotalVertices();
  12993. if (!mesh.isReady() || !mesh.isEnabled()) {
  12994. continue;
  12995. }
  12996. mesh.computeWorldMatrix();
  12997. // Intersections
  12998. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12999. this._meshesForIntersections.pushNoDuplicate(mesh);
  13000. }
  13001. // Switch to current LOD
  13002. var meshLOD = mesh.getLOD(this.activeCamera);
  13003. if (!meshLOD) {
  13004. continue;
  13005. }
  13006. mesh._preActivate();
  13007. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13008. this._activeMeshes.push(mesh);
  13009. this.activeCamera._activeMeshes.push(mesh);
  13010. mesh._activate(this._renderId);
  13011. this._activeMesh(meshLOD);
  13012. }
  13013. }
  13014. // Particle systems
  13015. var beforeParticlesDate = BABYLON.Tools.Now;
  13016. if (this.particlesEnabled) {
  13017. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13018. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13019. var particleSystem = this.particleSystems[particleIndex];
  13020. if (!particleSystem.isStarted()) {
  13021. continue;
  13022. }
  13023. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13024. this._activeParticleSystems.push(particleSystem);
  13025. particleSystem.animate();
  13026. }
  13027. }
  13028. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13029. }
  13030. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13031. };
  13032. Scene.prototype._activeMesh = function (mesh) {
  13033. if (mesh.skeleton && this.skeletonsEnabled) {
  13034. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13035. }
  13036. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13037. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13038. }
  13039. if (mesh && mesh.subMeshes) {
  13040. // Submeshes Octrees
  13041. var len;
  13042. var subMeshes;
  13043. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13044. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13045. len = intersections.length;
  13046. subMeshes = intersections.data;
  13047. }
  13048. else {
  13049. subMeshes = mesh.subMeshes;
  13050. len = subMeshes.length;
  13051. }
  13052. for (var subIndex = 0; subIndex < len; subIndex++) {
  13053. var subMesh = subMeshes[subIndex];
  13054. this._evaluateSubMesh(subMesh, mesh);
  13055. }
  13056. }
  13057. };
  13058. Scene.prototype.updateTransformMatrix = function (force) {
  13059. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13060. };
  13061. Scene.prototype._renderForCamera = function (camera) {
  13062. var engine = this._engine;
  13063. this.activeCamera = camera;
  13064. if (!this.activeCamera)
  13065. throw new Error("Active camera not set");
  13066. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13067. // Viewport
  13068. engine.setViewport(this.activeCamera.viewport);
  13069. // Camera
  13070. this._renderId++;
  13071. this.updateTransformMatrix();
  13072. if (this.beforeCameraRender) {
  13073. this.beforeCameraRender(this.activeCamera);
  13074. }
  13075. // Meshes
  13076. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13077. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13078. this._evaluateActiveMeshes();
  13079. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13080. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13081. // Skeletons
  13082. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13083. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13084. skeleton.prepare();
  13085. }
  13086. // Render targets
  13087. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13088. if (this.renderTargetsEnabled) {
  13089. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13090. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13091. var renderTarget = this._renderTargets.data[renderIndex];
  13092. if (renderTarget._shouldRender()) {
  13093. this._renderId++;
  13094. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13095. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13096. }
  13097. }
  13098. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13099. this._renderId++;
  13100. }
  13101. if (this._renderTargets.length > 0) {
  13102. engine.restoreDefaultFramebuffer();
  13103. }
  13104. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13105. // Prepare Frame
  13106. this.postProcessManager._prepareFrame();
  13107. var beforeRenderDate = BABYLON.Tools.Now;
  13108. // Backgrounds
  13109. if (this.layers.length) {
  13110. engine.setDepthBuffer(false);
  13111. var layerIndex;
  13112. var layer;
  13113. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13114. layer = this.layers[layerIndex];
  13115. if (layer.isBackground) {
  13116. layer.render();
  13117. }
  13118. }
  13119. engine.setDepthBuffer(true);
  13120. }
  13121. // Render
  13122. BABYLON.Tools.StartPerformanceCounter("Main render");
  13123. this._renderingManager.render(null, null, true, true);
  13124. BABYLON.Tools.EndPerformanceCounter("Main render");
  13125. // Bounding boxes
  13126. this._boundingBoxRenderer.render();
  13127. // Lens flares
  13128. if (this.lensFlaresEnabled) {
  13129. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13130. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13131. this.lensFlareSystems[lensFlareSystemIndex].render();
  13132. }
  13133. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13134. }
  13135. // Foregrounds
  13136. if (this.layers.length) {
  13137. engine.setDepthBuffer(false);
  13138. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13139. layer = this.layers[layerIndex];
  13140. if (!layer.isBackground) {
  13141. layer.render();
  13142. }
  13143. }
  13144. engine.setDepthBuffer(true);
  13145. }
  13146. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13147. // Finalize frame
  13148. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13149. // Update camera
  13150. this.activeCamera._updateFromScene();
  13151. // Reset some special arrays
  13152. this._renderTargets.reset();
  13153. if (this.afterCameraRender) {
  13154. this.afterCameraRender(this.activeCamera);
  13155. }
  13156. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13157. };
  13158. Scene.prototype._processSubCameras = function (camera) {
  13159. if (camera.subCameras.length === 0) {
  13160. this._renderForCamera(camera);
  13161. return;
  13162. }
  13163. // Sub-cameras
  13164. for (var index = 0; index < camera.subCameras.length; index++) {
  13165. this._renderForCamera(camera.subCameras[index]);
  13166. }
  13167. this.activeCamera = camera;
  13168. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13169. // Update camera
  13170. this.activeCamera._updateFromScene();
  13171. };
  13172. Scene.prototype._checkIntersections = function () {
  13173. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13174. var sourceMesh = this._meshesForIntersections.data[index];
  13175. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13176. var action = sourceMesh.actionManager.actions[actionIndex];
  13177. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13178. var parameters = action.getTriggerParameter();
  13179. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13180. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13181. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13182. if (areIntersecting && currentIntersectionInProgress === -1) {
  13183. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13184. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13185. sourceMesh._intersectionsInProgress.push(otherMesh);
  13186. }
  13187. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13188. sourceMesh._intersectionsInProgress.push(otherMesh);
  13189. }
  13190. }
  13191. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13192. //They intersected, and now they don't.
  13193. //is this trigger an exit trigger? execute an event.
  13194. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13195. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13196. }
  13197. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13198. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13199. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13200. }
  13201. }
  13202. }
  13203. }
  13204. }
  13205. };
  13206. Scene.prototype.render = function () {
  13207. var startDate = BABYLON.Tools.Now;
  13208. this._particlesDuration = 0;
  13209. this._spritesDuration = 0;
  13210. this._activeParticles = 0;
  13211. this._renderDuration = 0;
  13212. this._renderTargetsDuration = 0;
  13213. this._evaluateActiveMeshesDuration = 0;
  13214. this._totalVertices = 0;
  13215. this._activeIndices = 0;
  13216. this._activeBones = 0;
  13217. this.getEngine().resetDrawCalls();
  13218. this._meshesForIntersections.reset();
  13219. this.resetCachedMaterial();
  13220. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13221. // Actions
  13222. if (this.actionManager) {
  13223. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13224. }
  13225. //Simplification Queue
  13226. if (!this.simplificationQueue.running) {
  13227. this.simplificationQueue.executeNext();
  13228. }
  13229. // Before render
  13230. if (this.beforeRender) {
  13231. this.beforeRender();
  13232. }
  13233. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13234. this._onBeforeRenderCallbacks[callbackIndex]();
  13235. }
  13236. // Animations
  13237. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13238. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13239. this._animate();
  13240. // Physics
  13241. if (this._physicsEngine) {
  13242. BABYLON.Tools.StartPerformanceCounter("Physics");
  13243. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13244. BABYLON.Tools.EndPerformanceCounter("Physics");
  13245. }
  13246. // Customs render targets
  13247. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13248. var engine = this.getEngine();
  13249. var currentActiveCamera = this.activeCamera;
  13250. if (this.renderTargetsEnabled) {
  13251. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13252. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13253. var renderTarget = this.customRenderTargets[customIndex];
  13254. if (renderTarget._shouldRender()) {
  13255. this._renderId++;
  13256. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13257. if (!this.activeCamera)
  13258. throw new Error("Active camera not set");
  13259. // Viewport
  13260. engine.setViewport(this.activeCamera.viewport);
  13261. // Camera
  13262. this.updateTransformMatrix();
  13263. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13264. }
  13265. }
  13266. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13267. this._renderId++;
  13268. }
  13269. if (this.customRenderTargets.length > 0) {
  13270. engine.restoreDefaultFramebuffer();
  13271. }
  13272. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13273. this.activeCamera = currentActiveCamera;
  13274. // Procedural textures
  13275. if (this.proceduralTexturesEnabled) {
  13276. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13277. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13278. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13279. if (proceduralTexture._shouldRender()) {
  13280. proceduralTexture.render();
  13281. }
  13282. }
  13283. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13284. }
  13285. // Clear
  13286. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13287. // Shadows
  13288. if (this.shadowsEnabled) {
  13289. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13290. var light = this.lights[lightIndex];
  13291. var shadowGenerator = light.getShadowGenerator();
  13292. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13293. this._renderTargets.push(shadowGenerator.getShadowMap());
  13294. }
  13295. }
  13296. }
  13297. // Depth renderer
  13298. if (this._depthRenderer) {
  13299. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13300. }
  13301. // RenderPipeline
  13302. this.postProcessRenderPipelineManager.update();
  13303. // Multi-cameras?
  13304. if (this.activeCameras.length > 0) {
  13305. var currentRenderId = this._renderId;
  13306. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13307. this._renderId = currentRenderId;
  13308. this._processSubCameras(this.activeCameras[cameraIndex]);
  13309. }
  13310. }
  13311. else {
  13312. if (!this.activeCamera) {
  13313. throw new Error("No camera defined");
  13314. }
  13315. this._processSubCameras(this.activeCamera);
  13316. }
  13317. // Intersection checks
  13318. this._checkIntersections();
  13319. // Update the audio listener attached to the camera
  13320. this._updateAudioParameters();
  13321. // After render
  13322. if (this.afterRender) {
  13323. this.afterRender();
  13324. }
  13325. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13326. this._onAfterRenderCallbacks[callbackIndex]();
  13327. }
  13328. // Cleaning
  13329. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13330. this._toBeDisposed.data[index].dispose();
  13331. this._toBeDisposed[index] = null;
  13332. }
  13333. this._toBeDisposed.reset();
  13334. if (this.dumpNextRenderTargets) {
  13335. this.dumpNextRenderTargets = false;
  13336. }
  13337. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13338. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13339. };
  13340. Scene.prototype._updateAudioParameters = function () {
  13341. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13342. return;
  13343. }
  13344. var listeningCamera;
  13345. var audioEngine = BABYLON.Engine.audioEngine;
  13346. if (this.activeCameras.length > 0) {
  13347. listeningCamera = this.activeCameras[0];
  13348. }
  13349. else {
  13350. listeningCamera = this.activeCamera;
  13351. }
  13352. if (listeningCamera && audioEngine.canUseWebAudio) {
  13353. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13354. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13355. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13356. cameraDirection.normalize();
  13357. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13358. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13359. var sound = this.mainSoundTrack.soundCollection[i];
  13360. if (sound.useCustomAttenuation) {
  13361. sound.updateDistanceFromListener();
  13362. }
  13363. }
  13364. for (i = 0; i < this.soundTracks.length; i++) {
  13365. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13366. sound = this.soundTracks[i].soundCollection[j];
  13367. if (sound.useCustomAttenuation) {
  13368. sound.updateDistanceFromListener();
  13369. }
  13370. }
  13371. }
  13372. }
  13373. };
  13374. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13375. // Audio
  13376. get: function () {
  13377. return this._audioEnabled;
  13378. },
  13379. set: function (value) {
  13380. this._audioEnabled = value;
  13381. if (this._audioEnabled) {
  13382. this._enableAudio();
  13383. }
  13384. else {
  13385. this._disableAudio();
  13386. }
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Scene.prototype._disableAudio = function () {
  13392. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13393. this.mainSoundTrack.soundCollection[i].pause();
  13394. }
  13395. for (i = 0; i < this.soundTracks.length; i++) {
  13396. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13397. this.soundTracks[i].soundCollection[j].pause();
  13398. }
  13399. }
  13400. };
  13401. Scene.prototype._enableAudio = function () {
  13402. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13403. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13404. this.mainSoundTrack.soundCollection[i].play();
  13405. }
  13406. }
  13407. for (i = 0; i < this.soundTracks.length; i++) {
  13408. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13409. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13410. this.soundTracks[i].soundCollection[j].play();
  13411. }
  13412. }
  13413. }
  13414. };
  13415. Object.defineProperty(Scene.prototype, "headphone", {
  13416. get: function () {
  13417. return this._headphone;
  13418. },
  13419. set: function (value) {
  13420. this._headphone = value;
  13421. if (this._headphone) {
  13422. this._switchAudioModeForHeadphones();
  13423. }
  13424. else {
  13425. this._switchAudioModeForNormalSpeakers();
  13426. }
  13427. },
  13428. enumerable: true,
  13429. configurable: true
  13430. });
  13431. Scene.prototype._switchAudioModeForHeadphones = function () {
  13432. this.mainSoundTrack.switchPanningModelToHRTF();
  13433. for (var i = 0; i < this.soundTracks.length; i++) {
  13434. this.soundTracks[i].switchPanningModelToHRTF();
  13435. }
  13436. };
  13437. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13438. this.mainSoundTrack.switchPanningModelToEqualPower();
  13439. for (var i = 0; i < this.soundTracks.length; i++) {
  13440. this.soundTracks[i].switchPanningModelToEqualPower();
  13441. }
  13442. };
  13443. Scene.prototype.enableDepthRenderer = function () {
  13444. if (this._depthRenderer) {
  13445. return this._depthRenderer;
  13446. }
  13447. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13448. return this._depthRenderer;
  13449. };
  13450. Scene.prototype.disableDepthRenderer = function () {
  13451. if (!this._depthRenderer) {
  13452. return;
  13453. }
  13454. this._depthRenderer.dispose();
  13455. this._depthRenderer = null;
  13456. };
  13457. Scene.prototype.dispose = function () {
  13458. this.beforeRender = null;
  13459. this.afterRender = null;
  13460. this.skeletons = [];
  13461. this._boundingBoxRenderer.dispose();
  13462. if (this._depthRenderer) {
  13463. this._depthRenderer.dispose();
  13464. }
  13465. // Debug layer
  13466. this.debugLayer.hide();
  13467. // Events
  13468. if (this.onDispose) {
  13469. this.onDispose();
  13470. }
  13471. this._onBeforeRenderCallbacks = [];
  13472. this._onAfterRenderCallbacks = [];
  13473. this.detachControl();
  13474. // Release sounds & sounds tracks
  13475. this.disposeSounds();
  13476. // Detach cameras
  13477. var canvas = this._engine.getRenderingCanvas();
  13478. var index;
  13479. for (index = 0; index < this.cameras.length; index++) {
  13480. this.cameras[index].detachControl(canvas);
  13481. }
  13482. // Release lights
  13483. while (this.lights.length) {
  13484. this.lights[0].dispose();
  13485. }
  13486. // Release meshes
  13487. while (this.meshes.length) {
  13488. this.meshes[0].dispose(true);
  13489. }
  13490. // Release cameras
  13491. while (this.cameras.length) {
  13492. this.cameras[0].dispose();
  13493. }
  13494. // Release materials
  13495. while (this.materials.length) {
  13496. this.materials[0].dispose();
  13497. }
  13498. // Release particles
  13499. while (this.particleSystems.length) {
  13500. this.particleSystems[0].dispose();
  13501. }
  13502. // Release sprites
  13503. while (this.spriteManagers.length) {
  13504. this.spriteManagers[0].dispose();
  13505. }
  13506. // Release layers
  13507. while (this.layers.length) {
  13508. this.layers[0].dispose();
  13509. }
  13510. // Release textures
  13511. while (this.textures.length) {
  13512. this.textures[0].dispose();
  13513. }
  13514. // Post-processes
  13515. this.postProcessManager.dispose();
  13516. // Physics
  13517. if (this._physicsEngine) {
  13518. this.disablePhysicsEngine();
  13519. }
  13520. // Remove from engine
  13521. index = this._engine.scenes.indexOf(this);
  13522. if (index > -1) {
  13523. this._engine.scenes.splice(index, 1);
  13524. }
  13525. this._engine.wipeCaches();
  13526. };
  13527. // Release sounds & sounds tracks
  13528. Scene.prototype.disposeSounds = function () {
  13529. this.mainSoundTrack.dispose();
  13530. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13531. this.soundTracks[scIndex].dispose();
  13532. }
  13533. };
  13534. // Octrees
  13535. Scene.prototype.getWorldExtends = function () {
  13536. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13537. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13538. for (var index = 0; index < this.meshes.length; index++) {
  13539. var mesh = this.meshes[index];
  13540. mesh.computeWorldMatrix(true);
  13541. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13542. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13543. BABYLON.Tools.CheckExtends(minBox, min, max);
  13544. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13545. }
  13546. return {
  13547. min: min,
  13548. max: max
  13549. };
  13550. };
  13551. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13552. if (maxCapacity === void 0) { maxCapacity = 64; }
  13553. if (maxDepth === void 0) { maxDepth = 2; }
  13554. if (!this._selectionOctree) {
  13555. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13556. }
  13557. var worldExtends = this.getWorldExtends();
  13558. // Update octree
  13559. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13560. return this._selectionOctree;
  13561. };
  13562. // Picking
  13563. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13564. var engine = this._engine;
  13565. if (!camera) {
  13566. if (!this.activeCamera)
  13567. throw new Error("Active camera not set");
  13568. camera = this.activeCamera;
  13569. }
  13570. var cameraViewport = camera.viewport;
  13571. var viewport = cameraViewport.toGlobal(engine);
  13572. // Moving coordinates to local viewport world
  13573. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13574. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13575. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13576. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13577. };
  13578. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13579. var pickingInfo = null;
  13580. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13581. var mesh = this.meshes[meshIndex];
  13582. if (predicate) {
  13583. if (!predicate(mesh)) {
  13584. continue;
  13585. }
  13586. }
  13587. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13588. continue;
  13589. }
  13590. var world = mesh.getWorldMatrix();
  13591. var ray = rayFunction(world);
  13592. var result = mesh.intersects(ray, fastCheck);
  13593. if (!result || !result.hit)
  13594. continue;
  13595. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13596. continue;
  13597. pickingInfo = result;
  13598. if (fastCheck) {
  13599. break;
  13600. }
  13601. }
  13602. return pickingInfo || new BABYLON.PickingInfo();
  13603. };
  13604. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13605. var _this = this;
  13606. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13607. /// <param name="x">X position on screen</param>
  13608. /// <param name="y">Y position on screen</param>
  13609. /// <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>
  13610. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13611. /// <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>
  13612. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13613. };
  13614. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13615. var _this = this;
  13616. return this._internalPick(function (world) {
  13617. if (!_this._pickWithRayInverseMatrix) {
  13618. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13619. }
  13620. world.invertToRef(_this._pickWithRayInverseMatrix);
  13621. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13622. }, predicate, fastCheck);
  13623. };
  13624. Scene.prototype.setPointerOverMesh = function (mesh) {
  13625. if (this._pointerOverMesh === mesh) {
  13626. return;
  13627. }
  13628. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13629. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13630. }
  13631. this._pointerOverMesh = mesh;
  13632. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13633. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13634. }
  13635. };
  13636. Scene.prototype.getPointerOverMesh = function () {
  13637. return this._pointerOverMesh;
  13638. };
  13639. // Physics
  13640. Scene.prototype.getPhysicsEngine = function () {
  13641. return this._physicsEngine;
  13642. };
  13643. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13644. if (this._physicsEngine) {
  13645. return true;
  13646. }
  13647. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13648. if (!this._physicsEngine.isSupported()) {
  13649. this._physicsEngine = null;
  13650. return false;
  13651. }
  13652. this._physicsEngine._initialize(gravity);
  13653. return true;
  13654. };
  13655. Scene.prototype.disablePhysicsEngine = function () {
  13656. if (!this._physicsEngine) {
  13657. return;
  13658. }
  13659. this._physicsEngine.dispose();
  13660. this._physicsEngine = undefined;
  13661. };
  13662. Scene.prototype.isPhysicsEnabled = function () {
  13663. return this._physicsEngine !== undefined;
  13664. };
  13665. Scene.prototype.setGravity = function (gravity) {
  13666. if (!this._physicsEngine) {
  13667. return;
  13668. }
  13669. this._physicsEngine._setGravity(gravity);
  13670. };
  13671. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13672. if (parts.parts) {
  13673. options = parts;
  13674. parts = parts.parts;
  13675. }
  13676. if (!this._physicsEngine) {
  13677. return null;
  13678. }
  13679. for (var index = 0; index < parts.length; index++) {
  13680. var mesh = parts[index].mesh;
  13681. mesh._physicImpostor = parts[index].impostor;
  13682. mesh._physicsMass = options.mass / parts.length;
  13683. mesh._physicsFriction = options.friction;
  13684. mesh._physicRestitution = options.restitution;
  13685. }
  13686. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13687. };
  13688. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13689. for (var index = 0; index < compound.parts.length; index++) {
  13690. var mesh = compound.parts[index].mesh;
  13691. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13692. this._physicsEngine._unregisterMesh(mesh);
  13693. }
  13694. };
  13695. // Misc.
  13696. Scene.prototype.createDefaultCameraOrLight = function () {
  13697. // Light
  13698. if (this.lights.length === 0) {
  13699. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13700. }
  13701. // Camera
  13702. if (!this.activeCamera) {
  13703. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13704. // Compute position
  13705. var worldExtends = this.getWorldExtends();
  13706. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13707. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13708. camera.setTarget(worldCenter);
  13709. this.activeCamera = camera;
  13710. }
  13711. };
  13712. // Tags
  13713. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13714. if (tagsQuery === undefined) {
  13715. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13716. return list;
  13717. }
  13718. var listByTags = [];
  13719. forEach = forEach || (function (item) { return; });
  13720. for (var i in list) {
  13721. var item = list[i];
  13722. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13723. listByTags.push(item);
  13724. forEach(item);
  13725. }
  13726. }
  13727. return listByTags;
  13728. };
  13729. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13730. return this._getByTags(this.meshes, tagsQuery, forEach);
  13731. };
  13732. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13733. return this._getByTags(this.cameras, tagsQuery, forEach);
  13734. };
  13735. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13736. return this._getByTags(this.lights, tagsQuery, forEach);
  13737. };
  13738. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13739. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13740. };
  13741. // Statics
  13742. Scene._FOGMODE_NONE = 0;
  13743. Scene._FOGMODE_EXP = 1;
  13744. Scene._FOGMODE_EXP2 = 2;
  13745. Scene._FOGMODE_LINEAR = 3;
  13746. Scene.MinDeltaTime = 1.0;
  13747. Scene.MaxDeltaTime = 1000.0;
  13748. return Scene;
  13749. })();
  13750. BABYLON.Scene = Scene;
  13751. })(BABYLON || (BABYLON = {}));
  13752. //# sourceMappingURL=babylon.scene.js.map
  13753. var BABYLON;
  13754. (function (BABYLON) {
  13755. var VertexBuffer = (function () {
  13756. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13757. if (engine instanceof BABYLON.Mesh) {
  13758. this._engine = engine.getScene().getEngine();
  13759. }
  13760. else {
  13761. this._engine = engine;
  13762. }
  13763. this._updatable = updatable;
  13764. this._data = data;
  13765. if (!postponeInternalCreation) {
  13766. this.create();
  13767. }
  13768. this._kind = kind;
  13769. if (stride) {
  13770. this._strideSize = stride;
  13771. return;
  13772. }
  13773. // Deduce stride from kind
  13774. switch (kind) {
  13775. case VertexBuffer.PositionKind:
  13776. this._strideSize = 3;
  13777. break;
  13778. case VertexBuffer.NormalKind:
  13779. this._strideSize = 3;
  13780. break;
  13781. case VertexBuffer.UVKind:
  13782. this._strideSize = 2;
  13783. break;
  13784. case VertexBuffer.UV2Kind:
  13785. this._strideSize = 2;
  13786. break;
  13787. case VertexBuffer.ColorKind:
  13788. this._strideSize = 4;
  13789. break;
  13790. case VertexBuffer.MatricesIndicesKind:
  13791. this._strideSize = 4;
  13792. break;
  13793. case VertexBuffer.MatricesWeightsKind:
  13794. this._strideSize = 4;
  13795. break;
  13796. }
  13797. }
  13798. // Properties
  13799. VertexBuffer.prototype.isUpdatable = function () {
  13800. return this._updatable;
  13801. };
  13802. VertexBuffer.prototype.getData = function () {
  13803. return this._data;
  13804. };
  13805. VertexBuffer.prototype.getBuffer = function () {
  13806. return this._buffer;
  13807. };
  13808. VertexBuffer.prototype.getStrideSize = function () {
  13809. return this._strideSize;
  13810. };
  13811. // Methods
  13812. VertexBuffer.prototype.create = function (data) {
  13813. if (!data && this._buffer) {
  13814. return; // nothing to do
  13815. }
  13816. data = data || this._data;
  13817. if (!this._buffer) {
  13818. if (this._updatable) {
  13819. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13820. }
  13821. else {
  13822. this._buffer = this._engine.createVertexBuffer(data);
  13823. }
  13824. }
  13825. if (this._updatable) {
  13826. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13827. this._data = data;
  13828. }
  13829. };
  13830. VertexBuffer.prototype.update = function (data) {
  13831. this.create(data);
  13832. };
  13833. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13834. if (!this._buffer) {
  13835. return;
  13836. }
  13837. if (this._updatable) {
  13838. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13839. this._data = null;
  13840. }
  13841. };
  13842. VertexBuffer.prototype.dispose = function () {
  13843. if (!this._buffer) {
  13844. return;
  13845. }
  13846. if (this._engine._releaseBuffer(this._buffer)) {
  13847. this._buffer = null;
  13848. }
  13849. };
  13850. Object.defineProperty(VertexBuffer, "PositionKind", {
  13851. get: function () {
  13852. return VertexBuffer._PositionKind;
  13853. },
  13854. enumerable: true,
  13855. configurable: true
  13856. });
  13857. Object.defineProperty(VertexBuffer, "NormalKind", {
  13858. get: function () {
  13859. return VertexBuffer._NormalKind;
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. Object.defineProperty(VertexBuffer, "UVKind", {
  13865. get: function () {
  13866. return VertexBuffer._UVKind;
  13867. },
  13868. enumerable: true,
  13869. configurable: true
  13870. });
  13871. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13872. get: function () {
  13873. return VertexBuffer._UV2Kind;
  13874. },
  13875. enumerable: true,
  13876. configurable: true
  13877. });
  13878. Object.defineProperty(VertexBuffer, "ColorKind", {
  13879. get: function () {
  13880. return VertexBuffer._ColorKind;
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13886. get: function () {
  13887. return VertexBuffer._MatricesIndicesKind;
  13888. },
  13889. enumerable: true,
  13890. configurable: true
  13891. });
  13892. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13893. get: function () {
  13894. return VertexBuffer._MatricesWeightsKind;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. // Enums
  13900. VertexBuffer._PositionKind = "position";
  13901. VertexBuffer._NormalKind = "normal";
  13902. VertexBuffer._UVKind = "uv";
  13903. VertexBuffer._UV2Kind = "uv2";
  13904. VertexBuffer._ColorKind = "color";
  13905. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13906. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13907. return VertexBuffer;
  13908. })();
  13909. BABYLON.VertexBuffer = VertexBuffer;
  13910. })(BABYLON || (BABYLON = {}));
  13911. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13912. var __extends = this.__extends || function (d, b) {
  13913. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13914. function __() { this.constructor = d; }
  13915. __.prototype = b.prototype;
  13916. d.prototype = new __();
  13917. };
  13918. var BABYLON;
  13919. (function (BABYLON) {
  13920. /**
  13921. * Creates an instance based on a source mesh.
  13922. */
  13923. var InstancedMesh = (function (_super) {
  13924. __extends(InstancedMesh, _super);
  13925. function InstancedMesh(name, source) {
  13926. _super.call(this, name, source.getScene());
  13927. source.instances.push(this);
  13928. this._sourceMesh = source;
  13929. this.position.copyFrom(source.position);
  13930. this.rotation.copyFrom(source.rotation);
  13931. this.scaling.copyFrom(source.scaling);
  13932. if (source.rotationQuaternion) {
  13933. this.rotationQuaternion = source.rotationQuaternion.clone();
  13934. }
  13935. this.infiniteDistance = source.infiniteDistance;
  13936. this.setPivotMatrix(source.getPivotMatrix());
  13937. this.refreshBoundingInfo();
  13938. this._syncSubMeshes();
  13939. }
  13940. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13941. // Methods
  13942. get: function () {
  13943. return this._sourceMesh.receiveShadows;
  13944. },
  13945. enumerable: true,
  13946. configurable: true
  13947. });
  13948. Object.defineProperty(InstancedMesh.prototype, "material", {
  13949. get: function () {
  13950. return this._sourceMesh.material;
  13951. },
  13952. enumerable: true,
  13953. configurable: true
  13954. });
  13955. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13956. get: function () {
  13957. return this._sourceMesh.visibility;
  13958. },
  13959. enumerable: true,
  13960. configurable: true
  13961. });
  13962. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13963. get: function () {
  13964. return this._sourceMesh.skeleton;
  13965. },
  13966. enumerable: true,
  13967. configurable: true
  13968. });
  13969. InstancedMesh.prototype.getTotalVertices = function () {
  13970. return this._sourceMesh.getTotalVertices();
  13971. };
  13972. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13973. get: function () {
  13974. return this._sourceMesh;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. InstancedMesh.prototype.getVerticesData = function (kind) {
  13980. return this._sourceMesh.getVerticesData(kind);
  13981. };
  13982. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13983. return this._sourceMesh.isVerticesDataPresent(kind);
  13984. };
  13985. InstancedMesh.prototype.getIndices = function () {
  13986. return this._sourceMesh.getIndices();
  13987. };
  13988. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13989. get: function () {
  13990. return this._sourceMesh._positions;
  13991. },
  13992. enumerable: true,
  13993. configurable: true
  13994. });
  13995. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13996. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13997. if (data) {
  13998. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13999. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14000. }
  14001. this._updateBoundingInfo();
  14002. };
  14003. InstancedMesh.prototype._preActivate = function () {
  14004. if (this._currentLOD) {
  14005. this._currentLOD._preActivate();
  14006. }
  14007. };
  14008. InstancedMesh.prototype._activate = function (renderId) {
  14009. if (this._currentLOD) {
  14010. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14011. }
  14012. };
  14013. InstancedMesh.prototype.getLOD = function (camera) {
  14014. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14015. if (this._currentLOD === this.sourceMesh) {
  14016. return this;
  14017. }
  14018. return this._currentLOD;
  14019. };
  14020. InstancedMesh.prototype._syncSubMeshes = function () {
  14021. this.releaseSubMeshes();
  14022. if (this._sourceMesh.subMeshes) {
  14023. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14024. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14025. }
  14026. }
  14027. };
  14028. InstancedMesh.prototype._generatePointsArray = function () {
  14029. return this._sourceMesh._generatePointsArray();
  14030. };
  14031. // Clone
  14032. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14033. var result = this._sourceMesh.createInstance(name);
  14034. // Deep copy
  14035. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14036. // Bounding info
  14037. this.refreshBoundingInfo();
  14038. // Parent
  14039. if (newParent) {
  14040. result.parent = newParent;
  14041. }
  14042. if (!doNotCloneChildren) {
  14043. // Children
  14044. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14045. var mesh = this.getScene().meshes[index];
  14046. if (mesh.parent === this) {
  14047. mesh.clone(mesh.name, result);
  14048. }
  14049. }
  14050. }
  14051. result.computeWorldMatrix(true);
  14052. return result;
  14053. };
  14054. // Dispoe
  14055. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14056. // Remove from mesh
  14057. var index = this._sourceMesh.instances.indexOf(this);
  14058. this._sourceMesh.instances.splice(index, 1);
  14059. _super.prototype.dispose.call(this, doNotRecurse);
  14060. };
  14061. return InstancedMesh;
  14062. })(BABYLON.AbstractMesh);
  14063. BABYLON.InstancedMesh = InstancedMesh;
  14064. })(BABYLON || (BABYLON = {}));
  14065. //# sourceMappingURL=babylon.instancedMesh.js.map
  14066. var __extends = this.__extends || function (d, b) {
  14067. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14068. function __() { this.constructor = d; }
  14069. __.prototype = b.prototype;
  14070. d.prototype = new __();
  14071. };
  14072. var BABYLON;
  14073. (function (BABYLON) {
  14074. var _InstancesBatch = (function () {
  14075. function _InstancesBatch() {
  14076. this.mustReturn = false;
  14077. this.visibleInstances = new Array();
  14078. this.renderSelf = new Array();
  14079. }
  14080. return _InstancesBatch;
  14081. })();
  14082. BABYLON._InstancesBatch = _InstancesBatch;
  14083. var Mesh = (function (_super) {
  14084. __extends(Mesh, _super);
  14085. /**
  14086. * @constructor
  14087. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14088. * @param {Scene} scene - The scene to add this mesh to.
  14089. * @param {Node} parent - The parent of this mesh, if it has one
  14090. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14091. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14092. * When false, achieved by calling a clone(), also passing False.
  14093. * This will make creation of children, recursive.
  14094. */
  14095. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14096. if (parent === void 0) { parent = null; }
  14097. _super.call(this, name, scene);
  14098. // Members
  14099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14100. this.instances = new Array();
  14101. this._LODLevels = new Array();
  14102. this._onBeforeRenderCallbacks = new Array();
  14103. this._onAfterRenderCallbacks = new Array();
  14104. this._visibleInstances = {};
  14105. this._renderIdForInstances = new Array();
  14106. this._batchCache = new _InstancesBatch();
  14107. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14108. this._sideOrientation = Mesh._DEFAULTSIDE;
  14109. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14110. if (source) {
  14111. // Geometry
  14112. if (source._geometry) {
  14113. source._geometry.applyToMesh(this);
  14114. }
  14115. // Deep copy
  14116. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14117. // Material
  14118. this.material = source.material;
  14119. if (!doNotCloneChildren) {
  14120. // Children
  14121. for (var index = 0; index < scene.meshes.length; index++) {
  14122. var mesh = scene.meshes[index];
  14123. if (mesh.parent === source) {
  14124. // doNotCloneChildren is always going to be False
  14125. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14126. }
  14127. }
  14128. }
  14129. // Particles
  14130. for (index = 0; index < scene.particleSystems.length; index++) {
  14131. var system = scene.particleSystems[index];
  14132. if (system.emitter === source) {
  14133. system.clone(system.name, this);
  14134. }
  14135. }
  14136. this.computeWorldMatrix(true);
  14137. }
  14138. // Parent
  14139. if (parent !== null) {
  14140. this.parent = parent;
  14141. }
  14142. }
  14143. Object.defineProperty(Mesh, "FRONTSIDE", {
  14144. get: function () {
  14145. return Mesh._FRONTSIDE;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. Object.defineProperty(Mesh, "BACKSIDE", {
  14151. get: function () {
  14152. return Mesh._BACKSIDE;
  14153. },
  14154. enumerable: true,
  14155. configurable: true
  14156. });
  14157. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14158. get: function () {
  14159. return Mesh._DOUBLESIDE;
  14160. },
  14161. enumerable: true,
  14162. configurable: true
  14163. });
  14164. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14165. get: function () {
  14166. return Mesh._DEFAULTSIDE;
  14167. },
  14168. enumerable: true,
  14169. configurable: true
  14170. });
  14171. Object.defineProperty(Mesh, "NO_CAP", {
  14172. get: function () {
  14173. return Mesh._NO_CAP;
  14174. },
  14175. enumerable: true,
  14176. configurable: true
  14177. });
  14178. Object.defineProperty(Mesh, "CAP_START", {
  14179. get: function () {
  14180. return Mesh._CAP_START;
  14181. },
  14182. enumerable: true,
  14183. configurable: true
  14184. });
  14185. Object.defineProperty(Mesh, "CAP_END", {
  14186. get: function () {
  14187. return Mesh._CAP_END;
  14188. },
  14189. enumerable: true,
  14190. configurable: true
  14191. });
  14192. Object.defineProperty(Mesh, "CAP_ALL", {
  14193. get: function () {
  14194. return Mesh._CAP_ALL;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14200. // Methods
  14201. get: function () {
  14202. return this._LODLevels.length > 0;
  14203. },
  14204. enumerable: true,
  14205. configurable: true
  14206. });
  14207. Mesh.prototype._sortLODLevels = function () {
  14208. this._LODLevels.sort(function (a, b) {
  14209. if (a.distance < b.distance) {
  14210. return 1;
  14211. }
  14212. if (a.distance > b.distance) {
  14213. return -1;
  14214. }
  14215. return 0;
  14216. });
  14217. };
  14218. /**
  14219. * Add a mesh as LOD level triggered at the given distance.
  14220. * @param {number} distance - the distance from the center of the object to show this level
  14221. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14222. * @return {BABYLON.Mesh} this mesh (for chaining)
  14223. */
  14224. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14225. if (mesh && mesh._masterMesh) {
  14226. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14227. return this;
  14228. }
  14229. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14230. this._LODLevels.push(level);
  14231. if (mesh) {
  14232. mesh._masterMesh = this;
  14233. }
  14234. this._sortLODLevels();
  14235. return this;
  14236. };
  14237. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14238. for (var index = 0; index < this._LODLevels.length; index++) {
  14239. var level = this._LODLevels[index];
  14240. if (level.distance === distance) {
  14241. return level.mesh;
  14242. }
  14243. }
  14244. return null;
  14245. };
  14246. /**
  14247. * Remove a mesh from the LOD array
  14248. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14249. * @return {BABYLON.Mesh} this mesh (for chaining)
  14250. */
  14251. Mesh.prototype.removeLODLevel = function (mesh) {
  14252. for (var index = 0; index < this._LODLevels.length; index++) {
  14253. if (this._LODLevels[index].mesh === mesh) {
  14254. this._LODLevels.splice(index, 1);
  14255. if (mesh) {
  14256. mesh._masterMesh = null;
  14257. }
  14258. }
  14259. }
  14260. this._sortLODLevels();
  14261. return this;
  14262. };
  14263. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14264. if (!this._LODLevels || this._LODLevels.length === 0) {
  14265. return this;
  14266. }
  14267. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14268. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14269. if (this.onLODLevelSelection) {
  14270. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14271. }
  14272. return this;
  14273. }
  14274. for (var index = 0; index < this._LODLevels.length; index++) {
  14275. var level = this._LODLevels[index];
  14276. if (level.distance < distanceToCamera) {
  14277. if (level.mesh) {
  14278. level.mesh._preActivate();
  14279. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14280. }
  14281. if (this.onLODLevelSelection) {
  14282. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14283. }
  14284. return level.mesh;
  14285. }
  14286. }
  14287. if (this.onLODLevelSelection) {
  14288. this.onLODLevelSelection(distanceToCamera, this, this);
  14289. }
  14290. return this;
  14291. };
  14292. Object.defineProperty(Mesh.prototype, "geometry", {
  14293. get: function () {
  14294. return this._geometry;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Mesh.prototype.getTotalVertices = function () {
  14300. if (!this._geometry) {
  14301. return 0;
  14302. }
  14303. return this._geometry.getTotalVertices();
  14304. };
  14305. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14306. if (!this._geometry) {
  14307. return null;
  14308. }
  14309. return this._geometry.getVerticesData(kind, copyWhenShared);
  14310. };
  14311. Mesh.prototype.getVertexBuffer = function (kind) {
  14312. if (!this._geometry) {
  14313. return undefined;
  14314. }
  14315. return this._geometry.getVertexBuffer(kind);
  14316. };
  14317. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14318. if (!this._geometry) {
  14319. if (this._delayInfo) {
  14320. return this._delayInfo.indexOf(kind) !== -1;
  14321. }
  14322. return false;
  14323. }
  14324. return this._geometry.isVerticesDataPresent(kind);
  14325. };
  14326. Mesh.prototype.getVerticesDataKinds = function () {
  14327. if (!this._geometry) {
  14328. var result = [];
  14329. if (this._delayInfo) {
  14330. for (var kind in this._delayInfo) {
  14331. result.push(kind);
  14332. }
  14333. }
  14334. return result;
  14335. }
  14336. return this._geometry.getVerticesDataKinds();
  14337. };
  14338. Mesh.prototype.getTotalIndices = function () {
  14339. if (!this._geometry) {
  14340. return 0;
  14341. }
  14342. return this._geometry.getTotalIndices();
  14343. };
  14344. Mesh.prototype.getIndices = function (copyWhenShared) {
  14345. if (!this._geometry) {
  14346. return [];
  14347. }
  14348. return this._geometry.getIndices(copyWhenShared);
  14349. };
  14350. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14351. get: function () {
  14352. return this._masterMesh !== null && this._masterMesh !== undefined;
  14353. },
  14354. enumerable: true,
  14355. configurable: true
  14356. });
  14357. Mesh.prototype.isReady = function () {
  14358. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14359. return false;
  14360. }
  14361. return _super.prototype.isReady.call(this);
  14362. };
  14363. Mesh.prototype.isDisposed = function () {
  14364. return this._isDisposed;
  14365. };
  14366. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14367. get: function () {
  14368. return this._sideOrientation;
  14369. },
  14370. set: function (sideO) {
  14371. this._sideOrientation = sideO;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14377. get: function () {
  14378. return this._areNormalsFrozen;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14384. Mesh.prototype.freezeNormals = function () {
  14385. this._areNormalsFrozen = true;
  14386. };
  14387. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14388. Mesh.prototype.unfreezeNormals = function () {
  14389. this._areNormalsFrozen = false;
  14390. };
  14391. // Methods
  14392. Mesh.prototype._preActivate = function () {
  14393. var sceneRenderId = this.getScene().getRenderId();
  14394. if (this._preActivateId === sceneRenderId) {
  14395. return;
  14396. }
  14397. this._preActivateId = sceneRenderId;
  14398. this._visibleInstances = null;
  14399. };
  14400. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14401. if (!this._visibleInstances) {
  14402. this._visibleInstances = {};
  14403. this._visibleInstances.defaultRenderId = renderId;
  14404. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14405. }
  14406. if (!this._visibleInstances[renderId]) {
  14407. this._visibleInstances[renderId] = new Array();
  14408. }
  14409. this._visibleInstances[renderId].push(instance);
  14410. };
  14411. Mesh.prototype.refreshBoundingInfo = function () {
  14412. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14413. if (data) {
  14414. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14415. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14416. }
  14417. if (this.subMeshes) {
  14418. for (var index = 0; index < this.subMeshes.length; index++) {
  14419. this.subMeshes[index].refreshBoundingInfo();
  14420. }
  14421. }
  14422. this._updateBoundingInfo();
  14423. };
  14424. Mesh.prototype._createGlobalSubMesh = function () {
  14425. var totalVertices = this.getTotalVertices();
  14426. if (!totalVertices || !this.getIndices()) {
  14427. return null;
  14428. }
  14429. this.releaseSubMeshes();
  14430. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14431. };
  14432. Mesh.prototype.subdivide = function (count) {
  14433. if (count < 1) {
  14434. return;
  14435. }
  14436. var totalIndices = this.getTotalIndices();
  14437. var subdivisionSize = (totalIndices / count) | 0;
  14438. var offset = 0;
  14439. // Ensure that subdivisionSize is a multiple of 3
  14440. while (subdivisionSize % 3 !== 0) {
  14441. subdivisionSize++;
  14442. }
  14443. this.releaseSubMeshes();
  14444. for (var index = 0; index < count; index++) {
  14445. if (offset >= totalIndices) {
  14446. break;
  14447. }
  14448. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14449. offset += subdivisionSize;
  14450. }
  14451. this.synchronizeInstances();
  14452. };
  14453. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14454. if (kind instanceof Array) {
  14455. var temp = data;
  14456. data = kind;
  14457. kind = temp;
  14458. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14459. }
  14460. if (!this._geometry) {
  14461. var vertexData = new BABYLON.VertexData();
  14462. vertexData.set(data, kind);
  14463. var scene = this.getScene();
  14464. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14465. }
  14466. else {
  14467. this._geometry.setVerticesData(kind, data, updatable, stride);
  14468. }
  14469. };
  14470. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14471. if (!this._geometry) {
  14472. return;
  14473. }
  14474. if (!makeItUnique) {
  14475. this._geometry.updateVerticesData(kind, data, updateExtends);
  14476. }
  14477. else {
  14478. this.makeGeometryUnique();
  14479. this.updateVerticesData(kind, data, updateExtends, false);
  14480. }
  14481. };
  14482. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14483. if (!this._geometry) {
  14484. return;
  14485. }
  14486. if (!makeItUnique) {
  14487. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14488. }
  14489. else {
  14490. this.makeGeometryUnique();
  14491. this.updateVerticesDataDirectly(kind, data, offset, false);
  14492. }
  14493. };
  14494. // Mesh positions update function :
  14495. // updates the mesh positions according to the positionFunction returned values.
  14496. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14497. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14498. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14499. if (computeNormals === void 0) { computeNormals = true; }
  14500. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14501. positionFunction(positions);
  14502. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14503. if (computeNormals) {
  14504. var indices = this.getIndices();
  14505. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14506. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14507. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14508. }
  14509. };
  14510. Mesh.prototype.makeGeometryUnique = function () {
  14511. if (!this._geometry) {
  14512. return;
  14513. }
  14514. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14515. geometry.applyToMesh(this);
  14516. };
  14517. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14518. if (!this._geometry) {
  14519. var vertexData = new BABYLON.VertexData();
  14520. vertexData.indices = indices;
  14521. var scene = this.getScene();
  14522. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14523. }
  14524. else {
  14525. this._geometry.setIndices(indices, totalVertices);
  14526. }
  14527. };
  14528. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14529. var engine = this.getScene().getEngine();
  14530. // Wireframe
  14531. var indexToBind;
  14532. switch (fillMode) {
  14533. case BABYLON.Material.PointFillMode:
  14534. indexToBind = null;
  14535. break;
  14536. case BABYLON.Material.WireFrameFillMode:
  14537. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14538. break;
  14539. default:
  14540. case BABYLON.Material.TriangleFillMode:
  14541. indexToBind = this._geometry.getIndexBuffer();
  14542. break;
  14543. }
  14544. // VBOs
  14545. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14546. };
  14547. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14548. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14549. return;
  14550. }
  14551. var engine = this.getScene().getEngine();
  14552. // Draw order
  14553. switch (fillMode) {
  14554. case BABYLON.Material.PointFillMode:
  14555. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14556. break;
  14557. case BABYLON.Material.WireFrameFillMode:
  14558. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14559. break;
  14560. default:
  14561. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14562. }
  14563. };
  14564. Mesh.prototype.registerBeforeRender = function (func) {
  14565. this._onBeforeRenderCallbacks.push(func);
  14566. };
  14567. Mesh.prototype.unregisterBeforeRender = function (func) {
  14568. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14569. if (index > -1) {
  14570. this._onBeforeRenderCallbacks.splice(index, 1);
  14571. }
  14572. };
  14573. Mesh.prototype.registerAfterRender = function (func) {
  14574. this._onAfterRenderCallbacks.push(func);
  14575. };
  14576. Mesh.prototype.unregisterAfterRender = function (func) {
  14577. var index = this._onAfterRenderCallbacks.indexOf(func);
  14578. if (index > -1) {
  14579. this._onAfterRenderCallbacks.splice(index, 1);
  14580. }
  14581. };
  14582. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14583. var scene = this.getScene();
  14584. this._batchCache.mustReturn = false;
  14585. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14586. this._batchCache.visibleInstances[subMeshId] = null;
  14587. if (this._visibleInstances) {
  14588. var currentRenderId = scene.getRenderId();
  14589. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14590. var selfRenderId = this._renderId;
  14591. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14592. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14593. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14594. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14595. }
  14596. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14597. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14598. this._batchCache.mustReturn = true;
  14599. return this._batchCache;
  14600. }
  14601. if (currentRenderId !== selfRenderId) {
  14602. this._batchCache.renderSelf[subMeshId] = false;
  14603. }
  14604. }
  14605. this._renderIdForInstances[subMeshId] = currentRenderId;
  14606. }
  14607. return this._batchCache;
  14608. };
  14609. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14610. var visibleInstances = batch.visibleInstances[subMesh._id];
  14611. var matricesCount = visibleInstances.length + 1;
  14612. var bufferSize = matricesCount * 16 * 4;
  14613. while (this._instancesBufferSize < bufferSize) {
  14614. this._instancesBufferSize *= 2;
  14615. }
  14616. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14617. if (this._worldMatricesInstancesBuffer) {
  14618. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14619. }
  14620. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14621. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14622. }
  14623. var offset = 0;
  14624. var instancesCount = 0;
  14625. var world = this.getWorldMatrix();
  14626. if (batch.renderSelf[subMesh._id]) {
  14627. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14628. offset += 16;
  14629. instancesCount++;
  14630. }
  14631. if (visibleInstances) {
  14632. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14633. var instance = visibleInstances[instanceIndex];
  14634. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14635. offset += 16;
  14636. instancesCount++;
  14637. }
  14638. }
  14639. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14640. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14641. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14642. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14643. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14644. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14645. this._draw(subMesh, fillMode, instancesCount);
  14646. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14647. };
  14648. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14649. var scene = this.getScene();
  14650. var engine = scene.getEngine();
  14651. if (hardwareInstancedRendering) {
  14652. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14653. }
  14654. else {
  14655. if (batch.renderSelf[subMesh._id]) {
  14656. // Draw
  14657. if (onBeforeDraw) {
  14658. onBeforeDraw(false, this.getWorldMatrix());
  14659. }
  14660. this._draw(subMesh, fillMode);
  14661. }
  14662. if (batch.visibleInstances[subMesh._id]) {
  14663. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14664. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14665. // World
  14666. var world = instance.getWorldMatrix();
  14667. if (onBeforeDraw) {
  14668. onBeforeDraw(true, world);
  14669. }
  14670. // Draw
  14671. this._draw(subMesh, fillMode);
  14672. }
  14673. }
  14674. }
  14675. };
  14676. Mesh.prototype.render = function (subMesh) {
  14677. var scene = this.getScene();
  14678. // Managing instances
  14679. var batch = this._getInstancesRenderList(subMesh._id);
  14680. if (batch.mustReturn) {
  14681. return;
  14682. }
  14683. // Checking geometry state
  14684. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14685. return;
  14686. }
  14687. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14688. this._onBeforeRenderCallbacks[callbackIndex](this);
  14689. }
  14690. var engine = scene.getEngine();
  14691. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14692. // Material
  14693. var effectiveMaterial = subMesh.getMaterial();
  14694. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14695. return;
  14696. }
  14697. // Outline - step 1
  14698. var savedDepthWrite = engine.getDepthWrite();
  14699. if (this.renderOutline) {
  14700. engine.setDepthWrite(false);
  14701. scene.getOutlineRenderer().render(subMesh, batch);
  14702. engine.setDepthWrite(savedDepthWrite);
  14703. }
  14704. effectiveMaterial._preBind();
  14705. var effect = effectiveMaterial.getEffect();
  14706. // Bind
  14707. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14708. this._bind(subMesh, effect, fillMode);
  14709. var world = this.getWorldMatrix();
  14710. effectiveMaterial.bind(world, this);
  14711. // Draw
  14712. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14713. if (isInstance) {
  14714. effectiveMaterial.bindOnlyWorldMatrix(world);
  14715. }
  14716. });
  14717. // Unbind
  14718. effectiveMaterial.unbind();
  14719. // Outline - step 2
  14720. if (this.renderOutline && savedDepthWrite) {
  14721. engine.setDepthWrite(true);
  14722. engine.setColorWrite(false);
  14723. scene.getOutlineRenderer().render(subMesh, batch);
  14724. engine.setColorWrite(true);
  14725. }
  14726. // Overlay
  14727. if (this.renderOverlay) {
  14728. var currentMode = engine.getAlphaMode();
  14729. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14730. scene.getOutlineRenderer().render(subMesh, batch, true);
  14731. engine.setAlphaMode(currentMode);
  14732. }
  14733. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14734. this._onAfterRenderCallbacks[callbackIndex](this);
  14735. }
  14736. };
  14737. Mesh.prototype.getEmittedParticleSystems = function () {
  14738. var results = new Array();
  14739. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14740. var particleSystem = this.getScene().particleSystems[index];
  14741. if (particleSystem.emitter === this) {
  14742. results.push(particleSystem);
  14743. }
  14744. }
  14745. return results;
  14746. };
  14747. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14748. var results = new Array();
  14749. var descendants = this.getDescendants();
  14750. descendants.push(this);
  14751. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14752. var particleSystem = this.getScene().particleSystems[index];
  14753. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14754. results.push(particleSystem);
  14755. }
  14756. }
  14757. return results;
  14758. };
  14759. Mesh.prototype.getChildren = function () {
  14760. var results = [];
  14761. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14762. var mesh = this.getScene().meshes[index];
  14763. if (mesh.parent === this) {
  14764. results.push(mesh);
  14765. }
  14766. }
  14767. return results;
  14768. };
  14769. Mesh.prototype._checkDelayState = function () {
  14770. var _this = this;
  14771. var that = this;
  14772. var scene = this.getScene();
  14773. if (this._geometry) {
  14774. this._geometry.load(scene);
  14775. }
  14776. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14777. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14778. scene._addPendingData(that);
  14779. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14780. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14781. if (data instanceof ArrayBuffer) {
  14782. _this._delayLoadingFunction(data, _this);
  14783. }
  14784. else {
  14785. _this._delayLoadingFunction(JSON.parse(data), _this);
  14786. }
  14787. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14788. scene._removePendingData(_this);
  14789. }, function () { }, scene.database, getBinaryData);
  14790. }
  14791. };
  14792. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14793. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14794. return false;
  14795. }
  14796. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14797. return false;
  14798. }
  14799. this._checkDelayState();
  14800. return true;
  14801. };
  14802. Mesh.prototype.setMaterialByID = function (id) {
  14803. var materials = this.getScene().materials;
  14804. for (var index = 0; index < materials.length; index++) {
  14805. if (materials[index].id === id) {
  14806. this.material = materials[index];
  14807. return;
  14808. }
  14809. }
  14810. // Multi
  14811. var multiMaterials = this.getScene().multiMaterials;
  14812. for (index = 0; index < multiMaterials.length; index++) {
  14813. if (multiMaterials[index].id === id) {
  14814. this.material = multiMaterials[index];
  14815. return;
  14816. }
  14817. }
  14818. };
  14819. Mesh.prototype.getAnimatables = function () {
  14820. var results = [];
  14821. if (this.material) {
  14822. results.push(this.material);
  14823. }
  14824. if (this.skeleton) {
  14825. results.push(this.skeleton);
  14826. }
  14827. return results;
  14828. };
  14829. // Geometry
  14830. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14831. // Position
  14832. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14833. return;
  14834. }
  14835. this._resetPointsArrayCache();
  14836. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14837. var temp = [];
  14838. for (var index = 0; index < data.length; index += 3) {
  14839. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14840. }
  14841. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14842. // Normals
  14843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14844. return;
  14845. }
  14846. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14847. temp = [];
  14848. for (index = 0; index < data.length; index += 3) {
  14849. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14850. }
  14851. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14852. };
  14853. // Cache
  14854. Mesh.prototype._resetPointsArrayCache = function () {
  14855. this._positions = null;
  14856. };
  14857. Mesh.prototype._generatePointsArray = function () {
  14858. if (this._positions)
  14859. return true;
  14860. this._positions = [];
  14861. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14862. if (!data) {
  14863. return false;
  14864. }
  14865. for (var index = 0; index < data.length; index += 3) {
  14866. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14867. }
  14868. return true;
  14869. };
  14870. // Clone
  14871. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14872. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14873. };
  14874. // Dispose
  14875. Mesh.prototype.dispose = function (doNotRecurse) {
  14876. if (this._geometry) {
  14877. this._geometry.releaseForMesh(this, true);
  14878. }
  14879. // Instances
  14880. if (this._worldMatricesInstancesBuffer) {
  14881. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14882. this._worldMatricesInstancesBuffer = null;
  14883. }
  14884. while (this.instances.length) {
  14885. this.instances[0].dispose();
  14886. }
  14887. _super.prototype.dispose.call(this, doNotRecurse);
  14888. };
  14889. // Geometric tools
  14890. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14891. var _this = this;
  14892. var scene = this.getScene();
  14893. var onload = function (img) {
  14894. // Getting height map data
  14895. var canvas = document.createElement("canvas");
  14896. var context = canvas.getContext("2d");
  14897. var heightMapWidth = img.width;
  14898. var heightMapHeight = img.height;
  14899. canvas.width = heightMapWidth;
  14900. canvas.height = heightMapHeight;
  14901. context.drawImage(img, 0, 0);
  14902. // Create VertexData from map data
  14903. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14904. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14905. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14906. //execute success callback, if set
  14907. if (onSuccess) {
  14908. onSuccess(_this);
  14909. }
  14910. };
  14911. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14912. };
  14913. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14914. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14915. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14916. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14917. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14918. return;
  14919. }
  14920. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14921. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14922. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14923. var position = BABYLON.Vector3.Zero();
  14924. var normal = BABYLON.Vector3.Zero();
  14925. var uv = BABYLON.Vector2.Zero();
  14926. for (var index = 0; index < positions.length; index += 3) {
  14927. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14928. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14929. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14930. // Compute height
  14931. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14932. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14933. var pos = (u + v * heightMapWidth) * 4;
  14934. var r = buffer[pos] / 255.0;
  14935. var g = buffer[pos + 1] / 255.0;
  14936. var b = buffer[pos + 2] / 255.0;
  14937. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14938. normal.normalize();
  14939. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14940. position = position.add(normal);
  14941. position.toArray(positions, index);
  14942. }
  14943. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14944. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14945. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14946. };
  14947. Mesh.prototype.convertToFlatShadedMesh = function () {
  14948. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14949. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14950. var kinds = this.getVerticesDataKinds();
  14951. var vbs = [];
  14952. var data = [];
  14953. var newdata = [];
  14954. var updatableNormals = false;
  14955. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14956. var kind = kinds[kindIndex];
  14957. var vertexBuffer = this.getVertexBuffer(kind);
  14958. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14959. updatableNormals = vertexBuffer.isUpdatable();
  14960. kinds.splice(kindIndex, 1);
  14961. kindIndex--;
  14962. continue;
  14963. }
  14964. vbs[kind] = vertexBuffer;
  14965. data[kind] = vbs[kind].getData();
  14966. newdata[kind] = [];
  14967. }
  14968. // Save previous submeshes
  14969. var previousSubmeshes = this.subMeshes.slice(0);
  14970. var indices = this.getIndices();
  14971. var totalIndices = this.getTotalIndices();
  14972. // Generating unique vertices per face
  14973. for (var index = 0; index < totalIndices; index++) {
  14974. var vertexIndex = indices[index];
  14975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14976. kind = kinds[kindIndex];
  14977. var stride = vbs[kind].getStrideSize();
  14978. for (var offset = 0; offset < stride; offset++) {
  14979. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14980. }
  14981. }
  14982. }
  14983. // Updating faces & normal
  14984. var normals = [];
  14985. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14986. for (index = 0; index < totalIndices; index += 3) {
  14987. indices[index] = index;
  14988. indices[index + 1] = index + 1;
  14989. indices[index + 2] = index + 2;
  14990. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14991. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14992. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14993. var p1p2 = p1.subtract(p2);
  14994. var p3p2 = p3.subtract(p2);
  14995. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14996. // Store same normals for every vertex
  14997. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14998. normals.push(normal.x);
  14999. normals.push(normal.y);
  15000. normals.push(normal.z);
  15001. }
  15002. }
  15003. this.setIndices(indices);
  15004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15005. // Updating vertex buffers
  15006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15007. kind = kinds[kindIndex];
  15008. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15009. }
  15010. // Updating submeshes
  15011. this.releaseSubMeshes();
  15012. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15013. var previousOne = previousSubmeshes[submeshIndex];
  15014. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15015. }
  15016. this.synchronizeInstances();
  15017. };
  15018. // Instances
  15019. Mesh.prototype.createInstance = function (name) {
  15020. return new BABYLON.InstancedMesh(name, this);
  15021. };
  15022. Mesh.prototype.synchronizeInstances = function () {
  15023. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15024. var instance = this.instances[instanceIndex];
  15025. instance._syncSubMeshes();
  15026. }
  15027. };
  15028. /**
  15029. * Simplify the mesh according to the given array of settings.
  15030. * Function will return immediately and will simplify async.
  15031. * @param settings a collection of simplification settings.
  15032. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15033. * @param type the type of simplification to run.
  15034. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15035. */
  15036. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15037. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15038. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15039. this.getScene().simplificationQueue.addTask({
  15040. settings: settings,
  15041. parallelProcessing: parallelProcessing,
  15042. mesh: this,
  15043. simplificationType: simplificationType,
  15044. successCallback: successCallback
  15045. });
  15046. };
  15047. /**
  15048. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15049. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15050. * This should be used together with the simplification to avoid disappearing triangles.
  15051. * @param successCallback an optional success callback to be called after the optimization finished.
  15052. */
  15053. Mesh.prototype.optimizeIndices = function (successCallback) {
  15054. var _this = this;
  15055. var indices = this.getIndices();
  15056. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15057. var vectorPositions = [];
  15058. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15059. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15060. }
  15061. var dupes = [];
  15062. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15063. var realPos = vectorPositions.length - 1 - iteration;
  15064. var testedPosition = vectorPositions[realPos];
  15065. for (var j = 0; j < realPos; ++j) {
  15066. var againstPosition = vectorPositions[j];
  15067. if (testedPosition.equals(againstPosition)) {
  15068. dupes[realPos] = j;
  15069. break;
  15070. }
  15071. }
  15072. }, function () {
  15073. for (var i = 0; i < indices.length; ++i) {
  15074. indices[i] = dupes[indices[i]] || indices[i];
  15075. }
  15076. //indices are now reordered
  15077. var originalSubMeshes = _this.subMeshes.slice(0);
  15078. _this.setIndices(indices);
  15079. _this.subMeshes = originalSubMeshes;
  15080. if (successCallback) {
  15081. successCallback(_this);
  15082. }
  15083. });
  15084. };
  15085. // Statics
  15086. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15087. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15088. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15089. if (ribbonInstance) {
  15090. // positionFunction : ribbon case
  15091. // only pathArray and sideOrientation parameters are taken into account for positions update
  15092. var positionFunction = function (positions) {
  15093. var minlg = pathArray[0].length;
  15094. var i = 0;
  15095. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15096. for (var si = 1; si <= ns; si++) {
  15097. for (var p = 0; p < pathArray.length; p++) {
  15098. var path = pathArray[p];
  15099. var l = path.length;
  15100. minlg = (minlg < l) ? minlg : l;
  15101. var j = 0;
  15102. while (j < minlg) {
  15103. positions[i] = path[j].x;
  15104. positions[i + 1] = path[j].y;
  15105. positions[i + 2] = path[j].z;
  15106. j++;
  15107. i += 3;
  15108. }
  15109. }
  15110. }
  15111. };
  15112. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15113. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15114. return ribbonInstance;
  15115. }
  15116. else {
  15117. var ribbon = new Mesh(name, scene);
  15118. ribbon.sideOrientation = sideOrientation;
  15119. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15120. vertexData.applyToMesh(ribbon, updatable);
  15121. return ribbon;
  15122. }
  15123. };
  15124. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15125. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15126. var disc = new Mesh(name, scene);
  15127. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15128. vertexData.applyToMesh(disc, updatable);
  15129. return disc;
  15130. };
  15131. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15132. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15133. var box = new Mesh(name, scene);
  15134. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15135. vertexData.applyToMesh(box, updatable);
  15136. return box;
  15137. };
  15138. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15139. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15140. var sphere = new Mesh(name, scene);
  15141. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15142. vertexData.applyToMesh(sphere, updatable);
  15143. return sphere;
  15144. };
  15145. // Cylinder and cone (Code inspired by SharpDX.org)
  15146. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15147. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15148. // subdivisions is a new parameter, we need to support old signature
  15149. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15150. if (scene !== undefined) {
  15151. updatable = scene;
  15152. }
  15153. scene = subdivisions;
  15154. subdivisions = 1;
  15155. }
  15156. var cylinder = new Mesh(name, scene);
  15157. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15158. vertexData.applyToMesh(cylinder, updatable);
  15159. return cylinder;
  15160. };
  15161. // Torus (Code from SharpDX.org)
  15162. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15163. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15164. var torus = new Mesh(name, scene);
  15165. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15166. vertexData.applyToMesh(torus, updatable);
  15167. return torus;
  15168. };
  15169. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15170. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15171. var torusKnot = new Mesh(name, scene);
  15172. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15173. vertexData.applyToMesh(torusKnot, updatable);
  15174. return torusKnot;
  15175. };
  15176. // Lines
  15177. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15178. if (linesInstance === void 0) { linesInstance = null; }
  15179. if (linesInstance) {
  15180. var positionsOfLines = function (points) {
  15181. var positionFunction = function (positions) {
  15182. var i = 0;
  15183. for (var p = 0; p < points.length; p++) {
  15184. positions[i] = points[p].x;
  15185. positions[i + 1] = points[p].y;
  15186. positions[i + 2] = points[p].z;
  15187. i += 3;
  15188. }
  15189. };
  15190. return positionFunction;
  15191. };
  15192. var positionFunction = positionsOfLines(points);
  15193. linesInstance.updateMeshPositions(positionFunction, false);
  15194. return linesInstance;
  15195. }
  15196. // lines creation
  15197. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15198. var vertexData = BABYLON.VertexData.CreateLines(points);
  15199. vertexData.applyToMesh(lines, updatable);
  15200. return lines;
  15201. };
  15202. // Dashed Lines
  15203. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15204. if (linesInstance === void 0) { linesInstance = null; }
  15205. if (linesInstance) {
  15206. var positionFunction = function (positions) {
  15207. var curvect = BABYLON.Vector3.Zero();
  15208. var nbSeg = positions.length / 6;
  15209. var lg = 0;
  15210. var nb = 0;
  15211. var shft = 0;
  15212. var dashshft = 0;
  15213. var curshft = 0;
  15214. var p = 0;
  15215. var i = 0;
  15216. var j = 0;
  15217. for (i = 0; i < points.length - 1; i++) {
  15218. points[i + 1].subtractToRef(points[i], curvect);
  15219. lg += curvect.length();
  15220. }
  15221. shft = lg / nbSeg;
  15222. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15223. for (i = 0; i < points.length - 1; i++) {
  15224. points[i + 1].subtractToRef(points[i], curvect);
  15225. curvect.normalize();
  15226. nb = Math.floor(curvect.length() / shft);
  15227. j = 0;
  15228. while (j < nb && p < positions.length) {
  15229. curshft = shft * j;
  15230. positions[p] = points[i].x + curshft * curvect.x;
  15231. positions[p + 1] = points[i].y + curshft * curvect.y;
  15232. positions[p + 2] = points[i].z + curshft * curvect.z;
  15233. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15234. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15235. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15236. p += 6;
  15237. j++;
  15238. }
  15239. }
  15240. while (p < positions.length) {
  15241. positions[p] = points[i].x;
  15242. positions[p + 1] = points[i].y;
  15243. positions[p + 2] = points[i].z;
  15244. p += 3;
  15245. }
  15246. };
  15247. linesInstance.updateMeshPositions(positionFunction, false);
  15248. return linesInstance;
  15249. }
  15250. // dashed lines creation
  15251. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15252. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15253. vertexData.applyToMesh(dashedLines, updatable);
  15254. dashedLines.dashSize = dashSize;
  15255. dashedLines.gapSize = gapSize;
  15256. return dashedLines;
  15257. };
  15258. // Extrusion
  15259. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15260. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15261. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15262. scale = scale || 1;
  15263. rotation = rotation || 0;
  15264. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15265. return extruded;
  15266. };
  15267. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15268. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15269. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15270. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15271. return extrudedCustom;
  15272. };
  15273. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15274. // extrusion geometry
  15275. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15276. var tangents = path3D.getTangents();
  15277. var normals = path3D.getNormals();
  15278. var binormals = path3D.getBinormals();
  15279. var distances = path3D.getDistances();
  15280. var angle = 0;
  15281. var returnScale = function (i, distance) { return scale; };
  15282. var returnRotation = function (i, distance) { return rotation; };
  15283. var rotate = custom ? rotateFunction : returnRotation;
  15284. var scl = custom ? scaleFunction : returnScale;
  15285. var index = 0;
  15286. for (var i = 0; i < curve.length; i++) {
  15287. var shapePath = new Array();
  15288. var angleStep = rotate(i, distances[i]);
  15289. var scaleRatio = scl(i, distances[i]);
  15290. for (var p = 0; p < shape.length; p++) {
  15291. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15292. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15293. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15294. shapePath.push(rotated);
  15295. }
  15296. shapePaths[index] = shapePath;
  15297. angle += angleStep;
  15298. index++;
  15299. }
  15300. // cap
  15301. var capPath = function (shapePath) {
  15302. var pointCap = Array();
  15303. var barycenter = BABYLON.Vector3.Zero();
  15304. var i;
  15305. for (i = 0; i < shapePath.length; i++) {
  15306. barycenter.addInPlace(shapePath[i]);
  15307. }
  15308. barycenter.scaleInPlace(1 / shapePath.length);
  15309. for (i = 0; i < shapePath.length; i++) {
  15310. pointCap.push(barycenter);
  15311. }
  15312. return pointCap;
  15313. };
  15314. switch (cap) {
  15315. case BABYLON.Mesh.NO_CAP:
  15316. break;
  15317. case BABYLON.Mesh.CAP_START:
  15318. shapePaths.unshift(capPath(shapePaths[0]));
  15319. break;
  15320. case BABYLON.Mesh.CAP_END:
  15321. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15322. break;
  15323. case BABYLON.Mesh.CAP_ALL:
  15324. shapePaths.unshift(capPath(shapePaths[0]));
  15325. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15326. break;
  15327. default:
  15328. break;
  15329. }
  15330. return shapePaths;
  15331. };
  15332. if (instance) {
  15333. var path3D = (instance.path3D).update(curve);
  15334. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15335. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15336. return instance;
  15337. }
  15338. // extruded shape creation
  15339. var path3D = new BABYLON.Path3D(curve);
  15340. var newShapePaths = new Array();
  15341. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15342. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15343. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15344. extrudedGeneric.pathArray = pathArray;
  15345. extrudedGeneric.path3D = path3D;
  15346. extrudedGeneric.cap = cap;
  15347. return extrudedGeneric;
  15348. };
  15349. // Plane & ground
  15350. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15351. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15352. var plane = new Mesh(name, scene);
  15353. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15354. vertexData.applyToMesh(plane, updatable);
  15355. return plane;
  15356. };
  15357. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15358. var ground = new BABYLON.GroundMesh(name, scene);
  15359. ground._setReady(false);
  15360. ground._subdivisions = subdivisions;
  15361. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15362. vertexData.applyToMesh(ground, updatable);
  15363. ground._setReady(true);
  15364. return ground;
  15365. };
  15366. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15367. var tiledGround = new Mesh(name, scene);
  15368. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15369. vertexData.applyToMesh(tiledGround, updatable);
  15370. return tiledGround;
  15371. };
  15372. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15373. var ground = new BABYLON.GroundMesh(name, scene);
  15374. ground._subdivisions = subdivisions;
  15375. ground._setReady(false);
  15376. var onload = function (img) {
  15377. // Getting height map data
  15378. var canvas = document.createElement("canvas");
  15379. var context = canvas.getContext("2d");
  15380. var heightMapWidth = img.width;
  15381. var heightMapHeight = img.height;
  15382. canvas.width = heightMapWidth;
  15383. canvas.height = heightMapHeight;
  15384. context.drawImage(img, 0, 0);
  15385. // Create VertexData from map data
  15386. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15387. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15388. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15389. vertexData.applyToMesh(ground, updatable);
  15390. ground._setReady(true);
  15391. //execute ready callback, if set
  15392. if (onReady) {
  15393. onReady(ground);
  15394. }
  15395. };
  15396. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15397. return ground;
  15398. };
  15399. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15400. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15401. if (tubeInstance === void 0) { tubeInstance = null; }
  15402. // tube geometry
  15403. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15404. var tangents = path3D.getTangents();
  15405. var normals = path3D.getNormals();
  15406. var distances = path3D.getDistances();
  15407. var pi2 = Math.PI * 2;
  15408. var step = pi2 / tessellation;
  15409. var returnRadius = function (i, distance) { return radius; };
  15410. var radiusFunctionFinal = radiusFunction || returnRadius;
  15411. var circlePath;
  15412. var rad;
  15413. var normal;
  15414. var rotated;
  15415. var rotationMatrix;
  15416. var index = 0;
  15417. for (var i = 0; i < path.length; i++) {
  15418. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15419. circlePath = Array(); // current circle array
  15420. normal = normals[i]; // current normal
  15421. for (var t = 0; t < tessellation; t++) {
  15422. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15423. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15424. circlePath.push(rotated);
  15425. }
  15426. circlePath.push(circlePath[0]);
  15427. circlePaths[index] = circlePath;
  15428. index++;
  15429. }
  15430. // cap
  15431. var capPath = function (nbPoints, pathIndex) {
  15432. var pointCap = Array();
  15433. for (var i = 0; i < nbPoints; i++) {
  15434. pointCap.push(path[pathIndex]);
  15435. }
  15436. return pointCap;
  15437. };
  15438. switch (cap) {
  15439. case BABYLON.Mesh.NO_CAP:
  15440. break;
  15441. case BABYLON.Mesh.CAP_START:
  15442. circlePaths.unshift(capPath(tessellation + 1, 0));
  15443. break;
  15444. case BABYLON.Mesh.CAP_END:
  15445. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15446. break;
  15447. case BABYLON.Mesh.CAP_ALL:
  15448. circlePaths.unshift(capPath(tessellation + 1, 0));
  15449. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15450. break;
  15451. default:
  15452. break;
  15453. }
  15454. return circlePaths;
  15455. };
  15456. if (tubeInstance) {
  15457. var path3D = (tubeInstance.path3D).update(path);
  15458. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15459. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15460. return tubeInstance;
  15461. }
  15462. // tube creation
  15463. var path3D = new BABYLON.Path3D(path);
  15464. var newPathArray = new Array();
  15465. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15466. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15467. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15468. tube.pathArray = pathArray;
  15469. tube.path3D = path3D;
  15470. tube.tessellation = tessellation;
  15471. tube.cap = cap;
  15472. return tube;
  15473. };
  15474. // Decals
  15475. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15476. if (angle === void 0) { angle = 0; }
  15477. var indices = sourceMesh.getIndices();
  15478. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15479. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15480. // Getting correct rotation
  15481. if (!normal) {
  15482. var target = new BABYLON.Vector3(0, 0, 1);
  15483. var camera = sourceMesh.getScene().activeCamera;
  15484. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15485. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15486. }
  15487. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15488. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15489. var pitch = Math.atan2(normal.y, len);
  15490. // Matrix
  15491. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15492. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15493. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15494. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15495. var vertexData = new BABYLON.VertexData();
  15496. vertexData.indices = [];
  15497. vertexData.positions = [];
  15498. vertexData.normals = [];
  15499. vertexData.uvs = [];
  15500. var currentVertexDataIndex = 0;
  15501. var extractDecalVector3 = function (indexId) {
  15502. var vertexId = indices[indexId];
  15503. var result = new BABYLON.PositionNormalVertex();
  15504. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15505. // Send vector to decal local world
  15506. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15507. // Get normal
  15508. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15509. return result;
  15510. };
  15511. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15512. var clip = function (vertices, axis) {
  15513. if (vertices.length === 0) {
  15514. return vertices;
  15515. }
  15516. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15517. var clipVertices = function (v0, v1) {
  15518. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15519. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15520. };
  15521. var result = new Array();
  15522. for (var index = 0; index < vertices.length; index += 3) {
  15523. var v1Out;
  15524. var v2Out;
  15525. var v3Out;
  15526. var total = 0;
  15527. var nV1, nV2, nV3, nV4;
  15528. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15529. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15530. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15531. v1Out = d1 > 0;
  15532. v2Out = d2 > 0;
  15533. v3Out = d3 > 0;
  15534. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15535. switch (total) {
  15536. case 0:
  15537. result.push(vertices[index]);
  15538. result.push(vertices[index + 1]);
  15539. result.push(vertices[index + 2]);
  15540. break;
  15541. case 1:
  15542. if (v1Out) {
  15543. nV1 = vertices[index + 1];
  15544. nV2 = vertices[index + 2];
  15545. nV3 = clipVertices(vertices[index], nV1);
  15546. nV4 = clipVertices(vertices[index], nV2);
  15547. }
  15548. if (v2Out) {
  15549. nV1 = vertices[index];
  15550. nV2 = vertices[index + 2];
  15551. nV3 = clipVertices(vertices[index + 1], nV1);
  15552. nV4 = clipVertices(vertices[index + 1], nV2);
  15553. result.push(nV3);
  15554. result.push(nV2.clone());
  15555. result.push(nV1.clone());
  15556. result.push(nV2.clone());
  15557. result.push(nV3.clone());
  15558. result.push(nV4);
  15559. break;
  15560. }
  15561. if (v3Out) {
  15562. nV1 = vertices[index];
  15563. nV2 = vertices[index + 1];
  15564. nV3 = clipVertices(vertices[index + 2], nV1);
  15565. nV4 = clipVertices(vertices[index + 2], nV2);
  15566. }
  15567. result.push(nV1.clone());
  15568. result.push(nV2.clone());
  15569. result.push(nV3);
  15570. result.push(nV4);
  15571. result.push(nV3.clone());
  15572. result.push(nV2.clone());
  15573. break;
  15574. case 2:
  15575. if (!v1Out) {
  15576. nV1 = vertices[index].clone();
  15577. nV2 = clipVertices(nV1, vertices[index + 1]);
  15578. nV3 = clipVertices(nV1, vertices[index + 2]);
  15579. result.push(nV1);
  15580. result.push(nV2);
  15581. result.push(nV3);
  15582. }
  15583. if (!v2Out) {
  15584. nV1 = vertices[index + 1].clone();
  15585. nV2 = clipVertices(nV1, vertices[index + 2]);
  15586. nV3 = clipVertices(nV1, vertices[index]);
  15587. result.push(nV1);
  15588. result.push(nV2);
  15589. result.push(nV3);
  15590. }
  15591. if (!v3Out) {
  15592. nV1 = vertices[index + 2].clone();
  15593. nV2 = clipVertices(nV1, vertices[index]);
  15594. nV3 = clipVertices(nV1, vertices[index + 1]);
  15595. result.push(nV1);
  15596. result.push(nV2);
  15597. result.push(nV3);
  15598. }
  15599. break;
  15600. case 3:
  15601. break;
  15602. }
  15603. }
  15604. return result;
  15605. };
  15606. for (var index = 0; index < indices.length; index += 3) {
  15607. var faceVertices = new Array();
  15608. faceVertices.push(extractDecalVector3(index));
  15609. faceVertices.push(extractDecalVector3(index + 1));
  15610. faceVertices.push(extractDecalVector3(index + 2));
  15611. // Clip
  15612. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15613. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15616. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15617. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15618. if (faceVertices.length === 0) {
  15619. continue;
  15620. }
  15621. // Add UVs and get back to world
  15622. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15623. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15624. var vertex = faceVertices[vIndex];
  15625. vertexData.indices.push(currentVertexDataIndex);
  15626. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15627. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15628. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15629. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15630. currentVertexDataIndex++;
  15631. }
  15632. }
  15633. // Return mesh
  15634. var decal = new Mesh(name, sourceMesh.getScene());
  15635. vertexData.applyToMesh(decal);
  15636. decal.position = position.clone();
  15637. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15638. return decal;
  15639. };
  15640. // Tools
  15641. Mesh.MinMax = function (meshes) {
  15642. var minVector = null;
  15643. var maxVector = null;
  15644. for (var i in meshes) {
  15645. var mesh = meshes[i];
  15646. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15647. if (!minVector) {
  15648. minVector = boundingBox.minimumWorld;
  15649. maxVector = boundingBox.maximumWorld;
  15650. continue;
  15651. }
  15652. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15653. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15654. }
  15655. return {
  15656. min: minVector,
  15657. max: maxVector
  15658. };
  15659. };
  15660. Mesh.Center = function (meshesOrMinMaxVector) {
  15661. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15662. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15663. };
  15664. /**
  15665. * Merge the array of meshes into a single mesh for performance reasons.
  15666. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15667. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15668. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15669. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15670. */
  15671. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15672. if (disposeSource === void 0) { disposeSource = true; }
  15673. if (!allow32BitsIndices) {
  15674. var totalVertices = 0;
  15675. // Counting vertices
  15676. for (var index = 0; index < meshes.length; index++) {
  15677. if (meshes[index]) {
  15678. totalVertices += meshes[index].getTotalVertices();
  15679. if (totalVertices > 65536) {
  15680. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15681. return null;
  15682. }
  15683. }
  15684. }
  15685. }
  15686. // Merge
  15687. var vertexData;
  15688. var otherVertexData;
  15689. var source;
  15690. for (index = 0; index < meshes.length; index++) {
  15691. if (meshes[index]) {
  15692. meshes[index].computeWorldMatrix(true);
  15693. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15694. otherVertexData.transform(meshes[index].getWorldMatrix());
  15695. if (vertexData) {
  15696. vertexData.merge(otherVertexData);
  15697. }
  15698. else {
  15699. vertexData = otherVertexData;
  15700. source = meshes[index];
  15701. }
  15702. }
  15703. }
  15704. if (!meshSubclass) {
  15705. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15706. }
  15707. vertexData.applyToMesh(meshSubclass);
  15708. // Setting properties
  15709. meshSubclass.material = source.material;
  15710. meshSubclass.checkCollisions = source.checkCollisions;
  15711. // Cleaning
  15712. if (disposeSource) {
  15713. for (index = 0; index < meshes.length; index++) {
  15714. if (meshes[index]) {
  15715. meshes[index].dispose();
  15716. }
  15717. }
  15718. }
  15719. return meshSubclass;
  15720. };
  15721. // Consts
  15722. Mesh._FRONTSIDE = 0;
  15723. Mesh._BACKSIDE = 1;
  15724. Mesh._DOUBLESIDE = 2;
  15725. Mesh._DEFAULTSIDE = 0;
  15726. Mesh._NO_CAP = 0;
  15727. Mesh._CAP_START = 1;
  15728. Mesh._CAP_END = 2;
  15729. Mesh._CAP_ALL = 3;
  15730. return Mesh;
  15731. })(BABYLON.AbstractMesh);
  15732. BABYLON.Mesh = Mesh;
  15733. })(BABYLON || (BABYLON = {}));
  15734. //# sourceMappingURL=babylon.mesh.js.map
  15735. var BABYLON;
  15736. (function (BABYLON) {
  15737. var SubMesh = (function () {
  15738. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15739. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15740. this.materialIndex = materialIndex;
  15741. this.verticesStart = verticesStart;
  15742. this.verticesCount = verticesCount;
  15743. this.indexStart = indexStart;
  15744. this.indexCount = indexCount;
  15745. this._renderId = 0;
  15746. this._mesh = mesh;
  15747. this._renderingMesh = renderingMesh || mesh;
  15748. mesh.subMeshes.push(this);
  15749. this._trianglePlanes = [];
  15750. this._id = mesh.subMeshes.length - 1;
  15751. if (createBoundingBox) {
  15752. this.refreshBoundingInfo();
  15753. mesh.computeWorldMatrix(true);
  15754. }
  15755. }
  15756. SubMesh.prototype.getBoundingInfo = function () {
  15757. return this._boundingInfo;
  15758. };
  15759. SubMesh.prototype.getMesh = function () {
  15760. return this._mesh;
  15761. };
  15762. SubMesh.prototype.getRenderingMesh = function () {
  15763. return this._renderingMesh;
  15764. };
  15765. SubMesh.prototype.getMaterial = function () {
  15766. var rootMaterial = this._renderingMesh.material;
  15767. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15768. var multiMaterial = rootMaterial;
  15769. return multiMaterial.getSubMaterial(this.materialIndex);
  15770. }
  15771. if (!rootMaterial) {
  15772. return this._mesh.getScene().defaultMaterial;
  15773. }
  15774. return rootMaterial;
  15775. };
  15776. // Methods
  15777. SubMesh.prototype.refreshBoundingInfo = function () {
  15778. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15779. if (!data) {
  15780. this._boundingInfo = this._mesh._boundingInfo;
  15781. return;
  15782. }
  15783. var indices = this._renderingMesh.getIndices();
  15784. var extend;
  15785. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15786. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15787. }
  15788. else {
  15789. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15790. }
  15791. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15792. };
  15793. SubMesh.prototype._checkCollision = function (collider) {
  15794. return this._boundingInfo._checkCollision(collider);
  15795. };
  15796. SubMesh.prototype.updateBoundingInfo = function (world) {
  15797. if (!this._boundingInfo) {
  15798. this.refreshBoundingInfo();
  15799. }
  15800. this._boundingInfo._update(world);
  15801. };
  15802. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15803. return this._boundingInfo.isInFrustum(frustumPlanes);
  15804. };
  15805. SubMesh.prototype.render = function () {
  15806. this._renderingMesh.render(this);
  15807. };
  15808. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15809. if (!this._linesIndexBuffer) {
  15810. var linesIndices = [];
  15811. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15812. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15813. }
  15814. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15815. this.linesIndexCount = linesIndices.length;
  15816. }
  15817. return this._linesIndexBuffer;
  15818. };
  15819. SubMesh.prototype.canIntersects = function (ray) {
  15820. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15821. };
  15822. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15823. var intersectInfo = null;
  15824. // Triangles test
  15825. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15826. var p0 = positions[indices[index]];
  15827. var p1 = positions[indices[index + 1]];
  15828. var p2 = positions[indices[index + 2]];
  15829. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15830. if (currentIntersectInfo) {
  15831. if (currentIntersectInfo.distance < 0) {
  15832. continue;
  15833. }
  15834. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15835. intersectInfo = currentIntersectInfo;
  15836. intersectInfo.faceId = index / 3;
  15837. if (fastCheck) {
  15838. break;
  15839. }
  15840. }
  15841. }
  15842. }
  15843. return intersectInfo;
  15844. };
  15845. // Clone
  15846. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15847. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15848. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15849. return result;
  15850. };
  15851. // Dispose
  15852. SubMesh.prototype.dispose = function () {
  15853. if (this._linesIndexBuffer) {
  15854. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15855. this._linesIndexBuffer = null;
  15856. }
  15857. // Remove from mesh
  15858. var index = this._mesh.subMeshes.indexOf(this);
  15859. this._mesh.subMeshes.splice(index, 1);
  15860. };
  15861. // Statics
  15862. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15863. var minVertexIndex = Number.MAX_VALUE;
  15864. var maxVertexIndex = -Number.MAX_VALUE;
  15865. renderingMesh = renderingMesh || mesh;
  15866. var indices = renderingMesh.getIndices();
  15867. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15868. var vertexIndex = indices[index];
  15869. if (vertexIndex < minVertexIndex)
  15870. minVertexIndex = vertexIndex;
  15871. if (vertexIndex > maxVertexIndex)
  15872. maxVertexIndex = vertexIndex;
  15873. }
  15874. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15875. };
  15876. return SubMesh;
  15877. })();
  15878. BABYLON.SubMesh = SubMesh;
  15879. })(BABYLON || (BABYLON = {}));
  15880. //# sourceMappingURL=babylon.subMesh.js.map
  15881. var BABYLON;
  15882. (function (BABYLON) {
  15883. var BaseTexture = (function () {
  15884. function BaseTexture(scene) {
  15885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15886. this.hasAlpha = false;
  15887. this.getAlphaFromRGB = false;
  15888. this.level = 1;
  15889. this.isCube = false;
  15890. this.isRenderTarget = false;
  15891. this.animations = new Array();
  15892. this.coordinatesIndex = 0;
  15893. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15894. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15895. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15896. this.anisotropicFilteringLevel = 4;
  15897. this._scene = scene;
  15898. this._scene.textures.push(this);
  15899. }
  15900. BaseTexture.prototype.getScene = function () {
  15901. return this._scene;
  15902. };
  15903. BaseTexture.prototype.getTextureMatrix = function () {
  15904. return null;
  15905. };
  15906. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15907. return null;
  15908. };
  15909. BaseTexture.prototype.getInternalTexture = function () {
  15910. return this._texture;
  15911. };
  15912. BaseTexture.prototype.isReady = function () {
  15913. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15914. return true;
  15915. }
  15916. if (this._texture) {
  15917. return this._texture.isReady;
  15918. }
  15919. return false;
  15920. };
  15921. BaseTexture.prototype.getSize = function () {
  15922. if (this._texture._width) {
  15923. return { width: this._texture._width, height: this._texture._height };
  15924. }
  15925. if (this._texture._size) {
  15926. return { width: this._texture._size, height: this._texture._size };
  15927. }
  15928. return { width: 0, height: 0 };
  15929. };
  15930. BaseTexture.prototype.getBaseSize = function () {
  15931. if (!this.isReady())
  15932. return { width: 0, height: 0 };
  15933. if (this._texture._size) {
  15934. return { width: this._texture._size, height: this._texture._size };
  15935. }
  15936. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15937. };
  15938. BaseTexture.prototype.scale = function (ratio) {
  15939. };
  15940. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15941. get: function () {
  15942. return false;
  15943. },
  15944. enumerable: true,
  15945. configurable: true
  15946. });
  15947. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15948. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15949. for (var index = 0; index < texturesCache.length; index++) {
  15950. var texturesCacheEntry = texturesCache[index];
  15951. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15952. texturesCache.splice(index, 1);
  15953. return;
  15954. }
  15955. }
  15956. };
  15957. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15958. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15959. for (var index = 0; index < texturesCache.length; index++) {
  15960. var texturesCacheEntry = texturesCache[index];
  15961. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15962. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15963. texturesCacheEntry.references++;
  15964. return texturesCacheEntry;
  15965. }
  15966. }
  15967. }
  15968. return null;
  15969. };
  15970. BaseTexture.prototype.delayLoad = function () {
  15971. };
  15972. BaseTexture.prototype.releaseInternalTexture = function () {
  15973. if (!this._texture) {
  15974. return;
  15975. }
  15976. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15977. this._texture.references--;
  15978. // Final reference ?
  15979. if (this._texture.references === 0) {
  15980. var index = texturesCache.indexOf(this._texture);
  15981. texturesCache.splice(index, 1);
  15982. this._scene.getEngine()._releaseTexture(this._texture);
  15983. delete this._texture;
  15984. }
  15985. };
  15986. BaseTexture.prototype.clone = function () {
  15987. return null;
  15988. };
  15989. BaseTexture.prototype.dispose = function () {
  15990. // Remove from scene
  15991. var index = this._scene.textures.indexOf(this);
  15992. if (index >= 0) {
  15993. this._scene.textures.splice(index, 1);
  15994. }
  15995. if (this._texture === undefined) {
  15996. return;
  15997. }
  15998. this.releaseInternalTexture();
  15999. // Callback
  16000. if (this.onDispose) {
  16001. this.onDispose();
  16002. }
  16003. };
  16004. return BaseTexture;
  16005. })();
  16006. BABYLON.BaseTexture = BaseTexture;
  16007. })(BABYLON || (BABYLON = {}));
  16008. //# sourceMappingURL=babylon.baseTexture.js.map
  16009. var __extends = this.__extends || function (d, b) {
  16010. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16011. function __() { this.constructor = d; }
  16012. __.prototype = b.prototype;
  16013. d.prototype = new __();
  16014. };
  16015. var BABYLON;
  16016. (function (BABYLON) {
  16017. var Texture = (function (_super) {
  16018. __extends(Texture, _super);
  16019. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16020. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16021. if (onLoad === void 0) { onLoad = null; }
  16022. if (onError === void 0) { onError = null; }
  16023. if (buffer === void 0) { buffer = null; }
  16024. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16025. _super.call(this, scene);
  16026. this.uOffset = 0;
  16027. this.vOffset = 0;
  16028. this.uScale = 1.0;
  16029. this.vScale = 1.0;
  16030. this.uAng = 0;
  16031. this.vAng = 0;
  16032. this.wAng = 0;
  16033. this.name = url;
  16034. this.url = url;
  16035. this._noMipmap = noMipmap;
  16036. this._invertY = invertY;
  16037. this._samplingMode = samplingMode;
  16038. this._buffer = buffer;
  16039. this._deleteBuffer = deleteBuffer;
  16040. if (!url) {
  16041. return;
  16042. }
  16043. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16044. if (!this._texture) {
  16045. if (!scene.useDelayedTextureLoading) {
  16046. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16047. if (deleteBuffer) {
  16048. delete this._buffer;
  16049. }
  16050. }
  16051. else {
  16052. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16053. }
  16054. }
  16055. else {
  16056. BABYLON.Tools.SetImmediate(function () {
  16057. if (onLoad) {
  16058. onLoad();
  16059. }
  16060. });
  16061. }
  16062. }
  16063. Texture.prototype.delayLoad = function () {
  16064. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16065. return;
  16066. }
  16067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16068. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16069. if (!this._texture) {
  16070. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16071. if (this._deleteBuffer) {
  16072. delete this._buffer;
  16073. }
  16074. }
  16075. };
  16076. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16077. if (!this._texture) {
  16078. return;
  16079. }
  16080. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16081. };
  16082. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16083. x -= this.uOffset + 0.5;
  16084. y -= this.vOffset + 0.5;
  16085. z -= 0.5;
  16086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16087. t.x *= this.uScale;
  16088. t.y *= this.vScale;
  16089. t.x += 0.5;
  16090. t.y += 0.5;
  16091. t.z += 0.5;
  16092. };
  16093. Texture.prototype.getTextureMatrix = function () {
  16094. if (this.uOffset === this._cachedUOffset &&
  16095. this.vOffset === this._cachedVOffset &&
  16096. this.uScale === this._cachedUScale &&
  16097. this.vScale === this._cachedVScale &&
  16098. this.uAng === this._cachedUAng &&
  16099. this.vAng === this._cachedVAng &&
  16100. this.wAng === this._cachedWAng) {
  16101. return this._cachedTextureMatrix;
  16102. }
  16103. this._cachedUOffset = this.uOffset;
  16104. this._cachedVOffset = this.vOffset;
  16105. this._cachedUScale = this.uScale;
  16106. this._cachedVScale = this.vScale;
  16107. this._cachedUAng = this.uAng;
  16108. this._cachedVAng = this.vAng;
  16109. this._cachedWAng = this.wAng;
  16110. if (!this._cachedTextureMatrix) {
  16111. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16112. this._rowGenerationMatrix = new BABYLON.Matrix();
  16113. this._t0 = BABYLON.Vector3.Zero();
  16114. this._t1 = BABYLON.Vector3.Zero();
  16115. this._t2 = BABYLON.Vector3.Zero();
  16116. }
  16117. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16118. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16119. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16120. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16121. this._t1.subtractInPlace(this._t0);
  16122. this._t2.subtractInPlace(this._t0);
  16123. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16124. this._cachedTextureMatrix.m[0] = this._t1.x;
  16125. this._cachedTextureMatrix.m[1] = this._t1.y;
  16126. this._cachedTextureMatrix.m[2] = this._t1.z;
  16127. this._cachedTextureMatrix.m[4] = this._t2.x;
  16128. this._cachedTextureMatrix.m[5] = this._t2.y;
  16129. this._cachedTextureMatrix.m[6] = this._t2.z;
  16130. this._cachedTextureMatrix.m[8] = this._t0.x;
  16131. this._cachedTextureMatrix.m[9] = this._t0.y;
  16132. this._cachedTextureMatrix.m[10] = this._t0.z;
  16133. return this._cachedTextureMatrix;
  16134. };
  16135. Texture.prototype.getReflectionTextureMatrix = function () {
  16136. if (this.uOffset === this._cachedUOffset &&
  16137. this.vOffset === this._cachedVOffset &&
  16138. this.uScale === this._cachedUScale &&
  16139. this.vScale === this._cachedVScale &&
  16140. this.coordinatesMode === this._cachedCoordinatesMode) {
  16141. return this._cachedTextureMatrix;
  16142. }
  16143. if (!this._cachedTextureMatrix) {
  16144. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16145. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16146. }
  16147. this._cachedCoordinatesMode = this.coordinatesMode;
  16148. switch (this.coordinatesMode) {
  16149. case Texture.SPHERICAL_MODE:
  16150. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16151. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16152. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16153. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16154. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16155. break;
  16156. case Texture.PLANAR_MODE:
  16157. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16158. this._cachedTextureMatrix[0] = this.uScale;
  16159. this._cachedTextureMatrix[5] = this.vScale;
  16160. this._cachedTextureMatrix[12] = this.uOffset;
  16161. this._cachedTextureMatrix[13] = this.vOffset;
  16162. break;
  16163. case Texture.PROJECTION_MODE:
  16164. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16165. this._projectionModeMatrix.m[0] = 0.5;
  16166. this._projectionModeMatrix.m[5] = -0.5;
  16167. this._projectionModeMatrix.m[10] = 0.0;
  16168. this._projectionModeMatrix.m[12] = 0.5;
  16169. this._projectionModeMatrix.m[13] = 0.5;
  16170. this._projectionModeMatrix.m[14] = 1.0;
  16171. this._projectionModeMatrix.m[15] = 1.0;
  16172. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16173. break;
  16174. default:
  16175. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16176. break;
  16177. }
  16178. return this._cachedTextureMatrix;
  16179. };
  16180. Texture.prototype.clone = function () {
  16181. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16182. // Base texture
  16183. newTexture.hasAlpha = this.hasAlpha;
  16184. newTexture.level = this.level;
  16185. newTexture.wrapU = this.wrapU;
  16186. newTexture.wrapV = this.wrapV;
  16187. newTexture.coordinatesIndex = this.coordinatesIndex;
  16188. newTexture.coordinatesMode = this.coordinatesMode;
  16189. // Texture
  16190. newTexture.uOffset = this.uOffset;
  16191. newTexture.vOffset = this.vOffset;
  16192. newTexture.uScale = this.uScale;
  16193. newTexture.vScale = this.vScale;
  16194. newTexture.uAng = this.uAng;
  16195. newTexture.vAng = this.vAng;
  16196. newTexture.wAng = this.wAng;
  16197. return newTexture;
  16198. };
  16199. // Statics
  16200. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16201. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16202. if (onLoad === void 0) { onLoad = null; }
  16203. if (onError === void 0) { onError = null; }
  16204. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16205. };
  16206. // Constants
  16207. Texture.NEAREST_SAMPLINGMODE = 1;
  16208. Texture.BILINEAR_SAMPLINGMODE = 2;
  16209. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16210. Texture.EXPLICIT_MODE = 0;
  16211. Texture.SPHERICAL_MODE = 1;
  16212. Texture.PLANAR_MODE = 2;
  16213. Texture.CUBIC_MODE = 3;
  16214. Texture.PROJECTION_MODE = 4;
  16215. Texture.SKYBOX_MODE = 5;
  16216. Texture.CLAMP_ADDRESSMODE = 0;
  16217. Texture.WRAP_ADDRESSMODE = 1;
  16218. Texture.MIRROR_ADDRESSMODE = 2;
  16219. return Texture;
  16220. })(BABYLON.BaseTexture);
  16221. BABYLON.Texture = Texture;
  16222. })(BABYLON || (BABYLON = {}));
  16223. //# sourceMappingURL=babylon.texture.js.map
  16224. var __extends = this.__extends || function (d, b) {
  16225. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16226. function __() { this.constructor = d; }
  16227. __.prototype = b.prototype;
  16228. d.prototype = new __();
  16229. };
  16230. var BABYLON;
  16231. (function (BABYLON) {
  16232. var CubeTexture = (function (_super) {
  16233. __extends(CubeTexture, _super);
  16234. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16235. _super.call(this, scene);
  16236. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16237. this.name = rootUrl;
  16238. this.url = rootUrl;
  16239. this._noMipmap = noMipmap;
  16240. this.hasAlpha = false;
  16241. this._texture = this._getFromCache(rootUrl, noMipmap);
  16242. if (!extensions) {
  16243. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16244. }
  16245. this._extensions = extensions;
  16246. if (!this._texture) {
  16247. if (!scene.useDelayedTextureLoading) {
  16248. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16249. }
  16250. else {
  16251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16252. }
  16253. }
  16254. this.isCube = true;
  16255. this._textureMatrix = BABYLON.Matrix.Identity();
  16256. }
  16257. CubeTexture.prototype.clone = function () {
  16258. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16259. // Base texture
  16260. newTexture.level = this.level;
  16261. newTexture.wrapU = this.wrapU;
  16262. newTexture.wrapV = this.wrapV;
  16263. newTexture.coordinatesIndex = this.coordinatesIndex;
  16264. newTexture.coordinatesMode = this.coordinatesMode;
  16265. return newTexture;
  16266. };
  16267. // Methods
  16268. CubeTexture.prototype.delayLoad = function () {
  16269. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16270. return;
  16271. }
  16272. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16273. this._texture = this._getFromCache(this.url, this._noMipmap);
  16274. if (!this._texture) {
  16275. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16276. }
  16277. };
  16278. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16279. return this._textureMatrix;
  16280. };
  16281. return CubeTexture;
  16282. })(BABYLON.BaseTexture);
  16283. BABYLON.CubeTexture = CubeTexture;
  16284. })(BABYLON || (BABYLON = {}));
  16285. //# sourceMappingURL=babylon.cubeTexture.js.map
  16286. var __extends = this.__extends || function (d, b) {
  16287. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16288. function __() { this.constructor = d; }
  16289. __.prototype = b.prototype;
  16290. d.prototype = new __();
  16291. };
  16292. var BABYLON;
  16293. (function (BABYLON) {
  16294. var RenderTargetTexture = (function (_super) {
  16295. __extends(RenderTargetTexture, _super);
  16296. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16297. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16298. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16299. _super.call(this, null, scene, !generateMipMaps);
  16300. this.renderList = new Array();
  16301. this.renderParticles = true;
  16302. this.renderSprites = false;
  16303. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16304. this._currentRefreshId = -1;
  16305. this._refreshRate = 1;
  16306. this.name = name;
  16307. this.isRenderTarget = true;
  16308. this._size = size;
  16309. this._generateMipMaps = generateMipMaps;
  16310. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16311. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16312. // Rendering groups
  16313. this._renderingManager = new BABYLON.RenderingManager(scene);
  16314. }
  16315. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16316. this._currentRefreshId = -1;
  16317. };
  16318. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16319. get: function () {
  16320. return this._refreshRate;
  16321. },
  16322. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16323. set: function (value) {
  16324. this._refreshRate = value;
  16325. this.resetRefreshCounter();
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. RenderTargetTexture.prototype._shouldRender = function () {
  16331. if (this._currentRefreshId === -1) {
  16332. this._currentRefreshId = 1;
  16333. return true;
  16334. }
  16335. if (this.refreshRate === this._currentRefreshId) {
  16336. this._currentRefreshId = 1;
  16337. return true;
  16338. }
  16339. this._currentRefreshId++;
  16340. return false;
  16341. };
  16342. RenderTargetTexture.prototype.isReady = function () {
  16343. if (!this.getScene().renderTargetsEnabled) {
  16344. return false;
  16345. }
  16346. return _super.prototype.isReady.call(this);
  16347. };
  16348. RenderTargetTexture.prototype.getRenderSize = function () {
  16349. return this._size;
  16350. };
  16351. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16352. get: function () {
  16353. return true;
  16354. },
  16355. enumerable: true,
  16356. configurable: true
  16357. });
  16358. RenderTargetTexture.prototype.scale = function (ratio) {
  16359. var newSize = this._size * ratio;
  16360. this.resize(newSize, this._generateMipMaps);
  16361. };
  16362. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16363. this.releaseInternalTexture();
  16364. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16365. };
  16366. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16367. var scene = this.getScene();
  16368. var engine = scene.getEngine();
  16369. if (this._waitingRenderList) {
  16370. this.renderList = [];
  16371. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16372. var id = this._waitingRenderList[index];
  16373. this.renderList.push(scene.getMeshByID(id));
  16374. }
  16375. delete this._waitingRenderList;
  16376. }
  16377. if (this.renderList && this.renderList.length === 0) {
  16378. return;
  16379. }
  16380. // Bind
  16381. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16382. engine.bindFramebuffer(this._texture);
  16383. }
  16384. this._renderingManager.reset();
  16385. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16386. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16387. var mesh = currentRenderList[meshIndex];
  16388. if (mesh) {
  16389. if (!mesh.isReady()) {
  16390. // Reset _currentRefreshId
  16391. this.resetRefreshCounter();
  16392. continue;
  16393. }
  16394. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16395. mesh._activate(scene.getRenderId());
  16396. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16397. var subMesh = mesh.subMeshes[subIndex];
  16398. scene._activeIndices += subMesh.indexCount;
  16399. this._renderingManager.dispatch(subMesh);
  16400. }
  16401. }
  16402. }
  16403. }
  16404. if (this.onBeforeRender) {
  16405. this.onBeforeRender();
  16406. }
  16407. // Clear
  16408. if (this.onClear) {
  16409. this.onClear(engine);
  16410. }
  16411. else {
  16412. engine.clear(scene.clearColor, true, true);
  16413. }
  16414. if (!this._doNotChangeAspectRatio) {
  16415. scene.updateTransformMatrix(true);
  16416. }
  16417. // Render
  16418. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16419. if (useCameraPostProcess) {
  16420. scene.postProcessManager._finalizeFrame(false, this._texture);
  16421. }
  16422. if (!this._doNotChangeAspectRatio) {
  16423. scene.updateTransformMatrix(true);
  16424. }
  16425. if (this.onAfterRender) {
  16426. this.onAfterRender();
  16427. }
  16428. // Dump ?
  16429. if (dumpForDebug) {
  16430. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16431. }
  16432. // Unbind
  16433. engine.unBindFramebuffer(this._texture);
  16434. if (this.onAfterUnbind) {
  16435. this.onAfterUnbind();
  16436. }
  16437. };
  16438. RenderTargetTexture.prototype.clone = function () {
  16439. var textureSize = this.getSize();
  16440. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16441. // Base texture
  16442. newTexture.hasAlpha = this.hasAlpha;
  16443. newTexture.level = this.level;
  16444. // RenderTarget Texture
  16445. newTexture.coordinatesMode = this.coordinatesMode;
  16446. newTexture.renderList = this.renderList.slice(0);
  16447. return newTexture;
  16448. };
  16449. return RenderTargetTexture;
  16450. })(BABYLON.Texture);
  16451. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16452. })(BABYLON || (BABYLON = {}));
  16453. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16454. var __extends = this.__extends || function (d, b) {
  16455. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16456. function __() { this.constructor = d; }
  16457. __.prototype = b.prototype;
  16458. d.prototype = new __();
  16459. };
  16460. var BABYLON;
  16461. (function (BABYLON) {
  16462. var ProceduralTexture = (function (_super) {
  16463. __extends(ProceduralTexture, _super);
  16464. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16466. _super.call(this, null, scene, !generateMipMaps);
  16467. this._currentRefreshId = -1;
  16468. this._refreshRate = 1;
  16469. this._vertexDeclaration = [2];
  16470. this._vertexStrideSize = 2 * 4;
  16471. this._uniforms = new Array();
  16472. this._samplers = new Array();
  16473. this._textures = new Array();
  16474. this._floats = new Array();
  16475. this._floatsArrays = {};
  16476. this._colors3 = new Array();
  16477. this._colors4 = new Array();
  16478. this._vectors2 = new Array();
  16479. this._vectors3 = new Array();
  16480. this._matrices = new Array();
  16481. this._fallbackTextureUsed = false;
  16482. scene._proceduralTextures.push(this);
  16483. this.name = name;
  16484. this.isRenderTarget = true;
  16485. this._size = size;
  16486. this._generateMipMaps = generateMipMaps;
  16487. this.setFragment(fragment);
  16488. this._fallbackTexture = fallbackTexture;
  16489. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16490. // VBO
  16491. var vertices = [];
  16492. vertices.push(1, 1);
  16493. vertices.push(-1, 1);
  16494. vertices.push(-1, -1);
  16495. vertices.push(1, -1);
  16496. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16497. // Indices
  16498. var indices = [];
  16499. indices.push(0);
  16500. indices.push(1);
  16501. indices.push(2);
  16502. indices.push(0);
  16503. indices.push(2);
  16504. indices.push(3);
  16505. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16506. }
  16507. ProceduralTexture.prototype.reset = function () {
  16508. if (this._effect === undefined) {
  16509. return;
  16510. }
  16511. var engine = this.getScene().getEngine();
  16512. engine._releaseEffect(this._effect);
  16513. };
  16514. ProceduralTexture.prototype.isReady = function () {
  16515. var _this = this;
  16516. var engine = this.getScene().getEngine();
  16517. var shaders;
  16518. if (!this._fragment) {
  16519. return false;
  16520. }
  16521. if (this._fallbackTextureUsed) {
  16522. return true;
  16523. }
  16524. if (this._fragment.fragmentElement !== undefined) {
  16525. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16526. }
  16527. else {
  16528. shaders = { vertex: "procedural", fragment: this._fragment };
  16529. }
  16530. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16531. _this.releaseInternalTexture();
  16532. if (_this._fallbackTexture) {
  16533. _this._texture = _this._fallbackTexture._texture;
  16534. _this._texture.references++;
  16535. }
  16536. _this._fallbackTextureUsed = true;
  16537. });
  16538. return this._effect.isReady();
  16539. };
  16540. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16541. this._currentRefreshId = -1;
  16542. };
  16543. ProceduralTexture.prototype.setFragment = function (fragment) {
  16544. this._fragment = fragment;
  16545. };
  16546. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16547. get: function () {
  16548. return this._refreshRate;
  16549. },
  16550. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16551. set: function (value) {
  16552. this._refreshRate = value;
  16553. this.resetRefreshCounter();
  16554. },
  16555. enumerable: true,
  16556. configurable: true
  16557. });
  16558. ProceduralTexture.prototype._shouldRender = function () {
  16559. if (!this.isReady() || !this._texture) {
  16560. return false;
  16561. }
  16562. if (this._fallbackTextureUsed) {
  16563. return false;
  16564. }
  16565. if (this._currentRefreshId === -1) {
  16566. this._currentRefreshId = 1;
  16567. return true;
  16568. }
  16569. if (this.refreshRate === this._currentRefreshId) {
  16570. this._currentRefreshId = 1;
  16571. return true;
  16572. }
  16573. this._currentRefreshId++;
  16574. return false;
  16575. };
  16576. ProceduralTexture.prototype.getRenderSize = function () {
  16577. return this._size;
  16578. };
  16579. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16580. if (this._fallbackTextureUsed) {
  16581. return;
  16582. }
  16583. this.releaseInternalTexture();
  16584. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16585. };
  16586. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16587. if (this._uniforms.indexOf(uniformName) === -1) {
  16588. this._uniforms.push(uniformName);
  16589. }
  16590. };
  16591. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16592. if (this._samplers.indexOf(name) === -1) {
  16593. this._samplers.push(name);
  16594. }
  16595. this._textures[name] = texture;
  16596. return this;
  16597. };
  16598. ProceduralTexture.prototype.setFloat = function (name, value) {
  16599. this._checkUniform(name);
  16600. this._floats[name] = value;
  16601. return this;
  16602. };
  16603. ProceduralTexture.prototype.setFloats = function (name, value) {
  16604. this._checkUniform(name);
  16605. this._floatsArrays[name] = value;
  16606. return this;
  16607. };
  16608. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16609. this._checkUniform(name);
  16610. this._colors3[name] = value;
  16611. return this;
  16612. };
  16613. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16614. this._checkUniform(name);
  16615. this._colors4[name] = value;
  16616. return this;
  16617. };
  16618. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16619. this._checkUniform(name);
  16620. this._vectors2[name] = value;
  16621. return this;
  16622. };
  16623. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16624. this._checkUniform(name);
  16625. this._vectors3[name] = value;
  16626. return this;
  16627. };
  16628. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16629. this._checkUniform(name);
  16630. this._matrices[name] = value;
  16631. return this;
  16632. };
  16633. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16634. var scene = this.getScene();
  16635. var engine = scene.getEngine();
  16636. engine.bindFramebuffer(this._texture);
  16637. // Clear
  16638. engine.clear(scene.clearColor, true, true);
  16639. // Render
  16640. engine.enableEffect(this._effect);
  16641. engine.setState(false);
  16642. // Texture
  16643. for (var name in this._textures) {
  16644. this._effect.setTexture(name, this._textures[name]);
  16645. }
  16646. // Float
  16647. for (name in this._floats) {
  16648. this._effect.setFloat(name, this._floats[name]);
  16649. }
  16650. // Floats
  16651. for (name in this._floatsArrays) {
  16652. this._effect.setArray(name, this._floatsArrays[name]);
  16653. }
  16654. // Color3
  16655. for (name in this._colors3) {
  16656. this._effect.setColor3(name, this._colors3[name]);
  16657. }
  16658. // Color4
  16659. for (name in this._colors4) {
  16660. var color = this._colors4[name];
  16661. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16662. }
  16663. // Vector2
  16664. for (name in this._vectors2) {
  16665. this._effect.setVector2(name, this._vectors2[name]);
  16666. }
  16667. // Vector3
  16668. for (name in this._vectors3) {
  16669. this._effect.setVector3(name, this._vectors3[name]);
  16670. }
  16671. // Matrix
  16672. for (name in this._matrices) {
  16673. this._effect.setMatrix(name, this._matrices[name]);
  16674. }
  16675. // VBOs
  16676. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16677. // Draw order
  16678. engine.draw(true, 0, 6);
  16679. // Unbind
  16680. engine.unBindFramebuffer(this._texture);
  16681. };
  16682. ProceduralTexture.prototype.clone = function () {
  16683. var textureSize = this.getSize();
  16684. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16685. // Base texture
  16686. newTexture.hasAlpha = this.hasAlpha;
  16687. newTexture.level = this.level;
  16688. // RenderTarget Texture
  16689. newTexture.coordinatesMode = this.coordinatesMode;
  16690. return newTexture;
  16691. };
  16692. ProceduralTexture.prototype.dispose = function () {
  16693. var index = this.getScene()._proceduralTextures.indexOf(this);
  16694. if (index >= 0) {
  16695. this.getScene()._proceduralTextures.splice(index, 1);
  16696. }
  16697. _super.prototype.dispose.call(this);
  16698. };
  16699. return ProceduralTexture;
  16700. })(BABYLON.Texture);
  16701. BABYLON.ProceduralTexture = ProceduralTexture;
  16702. })(BABYLON || (BABYLON = {}));
  16703. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16704. var __extends = this.__extends || function (d, b) {
  16705. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16706. function __() { this.constructor = d; }
  16707. __.prototype = b.prototype;
  16708. d.prototype = new __();
  16709. };
  16710. var BABYLON;
  16711. (function (BABYLON) {
  16712. var MirrorTexture = (function (_super) {
  16713. __extends(MirrorTexture, _super);
  16714. function MirrorTexture(name, size, scene, generateMipMaps) {
  16715. var _this = this;
  16716. _super.call(this, name, size, scene, generateMipMaps, true);
  16717. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16718. this._transformMatrix = BABYLON.Matrix.Zero();
  16719. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16720. this.onBeforeRender = function () {
  16721. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16722. _this._savedViewMatrix = scene.getViewMatrix();
  16723. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16724. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16725. scene.clipPlane = _this.mirrorPlane;
  16726. scene.getEngine().cullBackFaces = false;
  16727. };
  16728. this.onAfterRender = function () {
  16729. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16730. scene.getEngine().cullBackFaces = true;
  16731. delete scene.clipPlane;
  16732. };
  16733. }
  16734. MirrorTexture.prototype.clone = function () {
  16735. var textureSize = this.getSize();
  16736. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16737. // Base texture
  16738. newTexture.hasAlpha = this.hasAlpha;
  16739. newTexture.level = this.level;
  16740. // Mirror Texture
  16741. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16742. newTexture.renderList = this.renderList.slice(0);
  16743. return newTexture;
  16744. };
  16745. return MirrorTexture;
  16746. })(BABYLON.RenderTargetTexture);
  16747. BABYLON.MirrorTexture = MirrorTexture;
  16748. })(BABYLON || (BABYLON = {}));
  16749. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16750. var __extends = this.__extends || function (d, b) {
  16751. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16752. function __() { this.constructor = d; }
  16753. __.prototype = b.prototype;
  16754. d.prototype = new __();
  16755. };
  16756. var BABYLON;
  16757. (function (BABYLON) {
  16758. var DynamicTexture = (function (_super) {
  16759. __extends(DynamicTexture, _super);
  16760. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16762. _super.call(this, null, scene, !generateMipMaps);
  16763. this.name = name;
  16764. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16765. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16766. this._generateMipMaps = generateMipMaps;
  16767. if (options.getContext) {
  16768. this._canvas = options;
  16769. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16770. }
  16771. else {
  16772. this._canvas = document.createElement("canvas");
  16773. if (options.width) {
  16774. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16775. }
  16776. else {
  16777. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16778. }
  16779. }
  16780. var textureSize = this.getSize();
  16781. this._canvas.width = textureSize.width;
  16782. this._canvas.height = textureSize.height;
  16783. this._context = this._canvas.getContext("2d");
  16784. }
  16785. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16786. get: function () {
  16787. return true;
  16788. },
  16789. enumerable: true,
  16790. configurable: true
  16791. });
  16792. DynamicTexture.prototype.scale = function (ratio) {
  16793. var textureSize = this.getSize();
  16794. textureSize.width *= ratio;
  16795. textureSize.height *= ratio;
  16796. this._canvas.width = textureSize.width;
  16797. this._canvas.height = textureSize.height;
  16798. this.releaseInternalTexture();
  16799. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16800. };
  16801. DynamicTexture.prototype.getContext = function () {
  16802. return this._context;
  16803. };
  16804. DynamicTexture.prototype.clear = function () {
  16805. var size = this.getSize();
  16806. this._context.fillRect(0, 0, size.width, size.height);
  16807. };
  16808. DynamicTexture.prototype.update = function (invertY) {
  16809. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16810. };
  16811. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16812. if (update === void 0) { update = true; }
  16813. var size = this.getSize();
  16814. if (clearColor) {
  16815. this._context.fillStyle = clearColor;
  16816. this._context.fillRect(0, 0, size.width, size.height);
  16817. }
  16818. this._context.font = font;
  16819. if (x === null) {
  16820. var textSize = this._context.measureText(text);
  16821. x = (size.width - textSize.width) / 2;
  16822. }
  16823. this._context.fillStyle = color;
  16824. this._context.fillText(text, x, y);
  16825. if (update) {
  16826. this.update(invertY);
  16827. }
  16828. };
  16829. DynamicTexture.prototype.clone = function () {
  16830. var textureSize = this.getSize();
  16831. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16832. // Base texture
  16833. newTexture.hasAlpha = this.hasAlpha;
  16834. newTexture.level = this.level;
  16835. // Dynamic Texture
  16836. newTexture.wrapU = this.wrapU;
  16837. newTexture.wrapV = this.wrapV;
  16838. return newTexture;
  16839. };
  16840. return DynamicTexture;
  16841. })(BABYLON.Texture);
  16842. BABYLON.DynamicTexture = DynamicTexture;
  16843. })(BABYLON || (BABYLON = {}));
  16844. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16845. var __extends = this.__extends || function (d, b) {
  16846. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16847. function __() { this.constructor = d; }
  16848. __.prototype = b.prototype;
  16849. d.prototype = new __();
  16850. };
  16851. var BABYLON;
  16852. (function (BABYLON) {
  16853. var VideoTexture = (function (_super) {
  16854. __extends(VideoTexture, _super);
  16855. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16856. var _this = this;
  16857. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16858. if (invertY === void 0) { invertY = true; }
  16859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16860. _super.call(this, null, scene, !generateMipMaps, invertY);
  16861. this._autoLaunch = true;
  16862. this.name = name;
  16863. this.video = document.createElement("video");
  16864. this.video.autoplay = false;
  16865. this.video.loop = true;
  16866. this.video.addEventListener("canplaythrough", function () {
  16867. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16868. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16869. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16870. }
  16871. else {
  16872. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16873. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16874. generateMipMaps = false;
  16875. }
  16876. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16877. _this._texture.isReady = true;
  16878. });
  16879. urls.forEach(function (url) {
  16880. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16881. var source = document.createElement("source");
  16882. source.src = url;
  16883. _this.video.appendChild(source);
  16884. });
  16885. this._lastUpdate = BABYLON.Tools.Now;
  16886. }
  16887. VideoTexture.prototype.update = function () {
  16888. if (this._autoLaunch) {
  16889. this._autoLaunch = false;
  16890. this.video.play();
  16891. }
  16892. var now = BABYLON.Tools.Now;
  16893. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16894. return false;
  16895. }
  16896. this._lastUpdate = now;
  16897. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16898. return true;
  16899. };
  16900. return VideoTexture;
  16901. })(BABYLON.Texture);
  16902. BABYLON.VideoTexture = VideoTexture;
  16903. })(BABYLON || (BABYLON = {}));
  16904. //# sourceMappingURL=babylon.videoTexture.js.map
  16905. var __extends = this.__extends || function (d, b) {
  16906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16907. function __() { this.constructor = d; }
  16908. __.prototype = b.prototype;
  16909. d.prototype = new __();
  16910. };
  16911. var BABYLON;
  16912. (function (BABYLON) {
  16913. var CustomProceduralTexture = (function (_super) {
  16914. __extends(CustomProceduralTexture, _super);
  16915. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16916. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16917. this._animate = true;
  16918. this._time = 0;
  16919. this._texturePath = texturePath;
  16920. //Try to load json
  16921. this.loadJson(texturePath);
  16922. this.refreshRate = 1;
  16923. }
  16924. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16925. var _this = this;
  16926. var that = this;
  16927. function noConfigFile() {
  16928. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16929. try {
  16930. that.setFragment(that._texturePath);
  16931. }
  16932. catch (ex) {
  16933. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16934. }
  16935. }
  16936. var configFileUrl = jsonUrl + "/config.json";
  16937. var xhr = new XMLHttpRequest();
  16938. xhr.open("GET", configFileUrl, true);
  16939. xhr.addEventListener("load", function () {
  16940. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16941. try {
  16942. _this._config = JSON.parse(xhr.response);
  16943. _this.updateShaderUniforms();
  16944. _this.updateTextures();
  16945. _this.setFragment(_this._texturePath + "/custom");
  16946. _this._animate = _this._config.animate;
  16947. _this.refreshRate = _this._config.refreshrate;
  16948. }
  16949. catch (ex) {
  16950. noConfigFile();
  16951. }
  16952. }
  16953. else {
  16954. noConfigFile();
  16955. }
  16956. }, false);
  16957. xhr.addEventListener("error", function () {
  16958. noConfigFile();
  16959. }, false);
  16960. try {
  16961. xhr.send();
  16962. }
  16963. catch (ex) {
  16964. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16965. }
  16966. };
  16967. CustomProceduralTexture.prototype.isReady = function () {
  16968. if (!_super.prototype.isReady.call(this)) {
  16969. return false;
  16970. }
  16971. for (var name in this._textures) {
  16972. var texture = this._textures[name];
  16973. if (!texture.isReady()) {
  16974. return false;
  16975. }
  16976. }
  16977. return true;
  16978. };
  16979. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16980. if (this._animate) {
  16981. this._time += this.getScene().getAnimationRatio() * 0.03;
  16982. this.updateShaderUniforms();
  16983. }
  16984. _super.prototype.render.call(this, useCameraPostProcess);
  16985. };
  16986. CustomProceduralTexture.prototype.updateTextures = function () {
  16987. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16988. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16989. }
  16990. };
  16991. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16992. if (this._config) {
  16993. for (var j = 0; j < this._config.uniforms.length; j++) {
  16994. var uniform = this._config.uniforms[j];
  16995. switch (uniform.type) {
  16996. case "float":
  16997. this.setFloat(uniform.name, uniform.value);
  16998. break;
  16999. case "color3":
  17000. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17001. break;
  17002. case "color4":
  17003. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17004. break;
  17005. case "vector2":
  17006. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17007. break;
  17008. case "vector3":
  17009. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17010. break;
  17011. }
  17012. }
  17013. }
  17014. this.setFloat("time", this._time);
  17015. };
  17016. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17017. get: function () {
  17018. return this._animate;
  17019. },
  17020. set: function (value) {
  17021. this._animate = value;
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. return CustomProceduralTexture;
  17027. })(BABYLON.ProceduralTexture);
  17028. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17029. })(BABYLON || (BABYLON = {}));
  17030. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17031. var __extends = this.__extends || function (d, b) {
  17032. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17033. function __() { this.constructor = d; }
  17034. __.prototype = b.prototype;
  17035. d.prototype = new __();
  17036. };
  17037. var BABYLON;
  17038. (function (BABYLON) {
  17039. var WoodProceduralTexture = (function (_super) {
  17040. __extends(WoodProceduralTexture, _super);
  17041. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17042. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17043. this._ampScale = 100.0;
  17044. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17045. this.updateShaderUniforms();
  17046. this.refreshRate = 0;
  17047. }
  17048. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17049. this.setFloat("ampScale", this._ampScale);
  17050. this.setColor3("woodColor", this._woodColor);
  17051. };
  17052. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17053. get: function () {
  17054. return this._ampScale;
  17055. },
  17056. set: function (value) {
  17057. this._ampScale = value;
  17058. this.updateShaderUniforms();
  17059. },
  17060. enumerable: true,
  17061. configurable: true
  17062. });
  17063. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17064. get: function () {
  17065. return this._woodColor;
  17066. },
  17067. set: function (value) {
  17068. this._woodColor = value;
  17069. this.updateShaderUniforms();
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. return WoodProceduralTexture;
  17075. })(BABYLON.ProceduralTexture);
  17076. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17077. var FireProceduralTexture = (function (_super) {
  17078. __extends(FireProceduralTexture, _super);
  17079. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17080. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17081. this._time = 0.0;
  17082. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17083. this._autoGenerateTime = true;
  17084. this._alphaThreshold = 0.5;
  17085. this._fireColors = FireProceduralTexture.RedFireColors;
  17086. this.updateShaderUniforms();
  17087. this.refreshRate = 1;
  17088. }
  17089. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17090. this.setFloat("time", this._time);
  17091. this.setVector2("speed", this._speed);
  17092. this.setColor3("c1", this._fireColors[0]);
  17093. this.setColor3("c2", this._fireColors[1]);
  17094. this.setColor3("c3", this._fireColors[2]);
  17095. this.setColor3("c4", this._fireColors[3]);
  17096. this.setColor3("c5", this._fireColors[4]);
  17097. this.setColor3("c6", this._fireColors[5]);
  17098. this.setFloat("alphaThreshold", this._alphaThreshold);
  17099. };
  17100. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17101. if (this._autoGenerateTime) {
  17102. this._time += this.getScene().getAnimationRatio() * 0.03;
  17103. this.updateShaderUniforms();
  17104. }
  17105. _super.prototype.render.call(this, useCameraPostProcess);
  17106. };
  17107. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17108. get: function () {
  17109. return [
  17110. new BABYLON.Color3(0.5, 0.0, 1.0),
  17111. new BABYLON.Color3(0.9, 0.0, 1.0),
  17112. new BABYLON.Color3(0.2, 0.0, 1.0),
  17113. new BABYLON.Color3(1.0, 0.9, 1.0),
  17114. new BABYLON.Color3(0.1, 0.1, 1.0),
  17115. new BABYLON.Color3(0.9, 0.9, 1.0)
  17116. ];
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17122. get: function () {
  17123. return [
  17124. new BABYLON.Color3(0.5, 1.0, 0.0),
  17125. new BABYLON.Color3(0.5, 1.0, 0.0),
  17126. new BABYLON.Color3(0.3, 0.4, 0.0),
  17127. new BABYLON.Color3(0.5, 1.0, 0.0),
  17128. new BABYLON.Color3(0.2, 0.0, 0.0),
  17129. new BABYLON.Color3(0.5, 1.0, 0.0)
  17130. ];
  17131. },
  17132. enumerable: true,
  17133. configurable: true
  17134. });
  17135. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17136. get: function () {
  17137. return [
  17138. new BABYLON.Color3(0.5, 0.0, 0.1),
  17139. new BABYLON.Color3(0.9, 0.0, 0.0),
  17140. new BABYLON.Color3(0.2, 0.0, 0.0),
  17141. new BABYLON.Color3(1.0, 0.9, 0.0),
  17142. new BABYLON.Color3(0.1, 0.1, 0.1),
  17143. new BABYLON.Color3(0.9, 0.9, 0.9)
  17144. ];
  17145. },
  17146. enumerable: true,
  17147. configurable: true
  17148. });
  17149. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17150. get: function () {
  17151. return [
  17152. new BABYLON.Color3(0.1, 0.0, 0.5),
  17153. new BABYLON.Color3(0.0, 0.0, 0.5),
  17154. new BABYLON.Color3(0.1, 0.0, 0.2),
  17155. new BABYLON.Color3(0.0, 0.0, 1.0),
  17156. new BABYLON.Color3(0.1, 0.2, 0.3),
  17157. new BABYLON.Color3(0.0, 0.2, 0.9)
  17158. ];
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17164. get: function () {
  17165. return this._fireColors;
  17166. },
  17167. set: function (value) {
  17168. this._fireColors = value;
  17169. this.updateShaderUniforms();
  17170. },
  17171. enumerable: true,
  17172. configurable: true
  17173. });
  17174. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17175. get: function () {
  17176. return this._time;
  17177. },
  17178. set: function (value) {
  17179. this._time = value;
  17180. this.updateShaderUniforms();
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17186. get: function () {
  17187. return this._speed;
  17188. },
  17189. set: function (value) {
  17190. this._speed = value;
  17191. this.updateShaderUniforms();
  17192. },
  17193. enumerable: true,
  17194. configurable: true
  17195. });
  17196. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17197. get: function () {
  17198. return this._alphaThreshold;
  17199. },
  17200. set: function (value) {
  17201. this._alphaThreshold = value;
  17202. this.updateShaderUniforms();
  17203. },
  17204. enumerable: true,
  17205. configurable: true
  17206. });
  17207. return FireProceduralTexture;
  17208. })(BABYLON.ProceduralTexture);
  17209. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17210. var CloudProceduralTexture = (function (_super) {
  17211. __extends(CloudProceduralTexture, _super);
  17212. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17213. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17214. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17215. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17216. this.updateShaderUniforms();
  17217. this.refreshRate = 0;
  17218. }
  17219. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17220. this.setColor3("skyColor", this._skyColor);
  17221. this.setColor3("cloudColor", this._cloudColor);
  17222. };
  17223. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17224. get: function () {
  17225. return this._skyColor;
  17226. },
  17227. set: function (value) {
  17228. this._skyColor = value;
  17229. this.updateShaderUniforms();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17235. get: function () {
  17236. return this._cloudColor;
  17237. },
  17238. set: function (value) {
  17239. this._cloudColor = value;
  17240. this.updateShaderUniforms();
  17241. },
  17242. enumerable: true,
  17243. configurable: true
  17244. });
  17245. return CloudProceduralTexture;
  17246. })(BABYLON.ProceduralTexture);
  17247. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17248. var GrassProceduralTexture = (function (_super) {
  17249. __extends(GrassProceduralTexture, _super);
  17250. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17251. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17252. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17253. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17254. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17255. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17256. this._grassColors = [
  17257. new BABYLON.Color3(0.29, 0.38, 0.02),
  17258. new BABYLON.Color3(0.36, 0.49, 0.09),
  17259. new BABYLON.Color3(0.51, 0.6, 0.28)
  17260. ];
  17261. this.updateShaderUniforms();
  17262. this.refreshRate = 0;
  17263. }
  17264. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17265. this.setColor3("herb1Color", this._grassColors[0]);
  17266. this.setColor3("herb2Color", this._grassColors[1]);
  17267. this.setColor3("herb3Color", this._grassColors[2]);
  17268. this.setColor3("groundColor", this._groundColor);
  17269. };
  17270. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17271. get: function () {
  17272. return this._grassColors;
  17273. },
  17274. set: function (value) {
  17275. this._grassColors = value;
  17276. this.updateShaderUniforms();
  17277. },
  17278. enumerable: true,
  17279. configurable: true
  17280. });
  17281. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17282. get: function () {
  17283. return this._groundColor;
  17284. },
  17285. set: function (value) {
  17286. this.groundColor = value;
  17287. this.updateShaderUniforms();
  17288. },
  17289. enumerable: true,
  17290. configurable: true
  17291. });
  17292. return GrassProceduralTexture;
  17293. })(BABYLON.ProceduralTexture);
  17294. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17295. var RoadProceduralTexture = (function (_super) {
  17296. __extends(RoadProceduralTexture, _super);
  17297. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17298. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17299. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17300. this.updateShaderUniforms();
  17301. this.refreshRate = 0;
  17302. }
  17303. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17304. this.setColor3("roadColor", this._roadColor);
  17305. };
  17306. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17307. get: function () {
  17308. return this._roadColor;
  17309. },
  17310. set: function (value) {
  17311. this._roadColor = value;
  17312. this.updateShaderUniforms();
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. return RoadProceduralTexture;
  17318. })(BABYLON.ProceduralTexture);
  17319. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17320. var BrickProceduralTexture = (function (_super) {
  17321. __extends(BrickProceduralTexture, _super);
  17322. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17323. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17324. this._numberOfBricksHeight = 15;
  17325. this._numberOfBricksWidth = 5;
  17326. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17327. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17328. this.updateShaderUniforms();
  17329. this.refreshRate = 0;
  17330. }
  17331. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17332. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17333. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17334. this.setColor3("brickColor", this._brickColor);
  17335. this.setColor3("jointColor", this._jointColor);
  17336. };
  17337. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17338. get: function () {
  17339. return this._numberOfBricksHeight;
  17340. },
  17341. set: function (value) {
  17342. this._numberOfBricksHeight = value;
  17343. this.updateShaderUniforms();
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17349. get: function () {
  17350. return this._numberOfBricksWidth;
  17351. },
  17352. set: function (value) {
  17353. this._numberOfBricksHeight = value;
  17354. this.updateShaderUniforms();
  17355. },
  17356. enumerable: true,
  17357. configurable: true
  17358. });
  17359. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17360. get: function () {
  17361. return this._jointColor;
  17362. },
  17363. set: function (value) {
  17364. this._jointColor = value;
  17365. this.updateShaderUniforms();
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17371. get: function () {
  17372. return this._brickColor;
  17373. },
  17374. set: function (value) {
  17375. this._brickColor = value;
  17376. this.updateShaderUniforms();
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. return BrickProceduralTexture;
  17382. })(BABYLON.ProceduralTexture);
  17383. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17384. var MarbleProceduralTexture = (function (_super) {
  17385. __extends(MarbleProceduralTexture, _super);
  17386. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17387. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17388. this._numberOfTilesHeight = 3;
  17389. this._numberOfTilesWidth = 3;
  17390. this._amplitude = 9.0;
  17391. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17392. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17393. this.updateShaderUniforms();
  17394. this.refreshRate = 0;
  17395. }
  17396. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17397. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17398. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17399. this.setFloat("amplitude", this._amplitude);
  17400. this.setColor3("marbleColor", this._marbleColor);
  17401. this.setColor3("jointColor", this._jointColor);
  17402. };
  17403. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17404. get: function () {
  17405. return this._numberOfTilesHeight;
  17406. },
  17407. set: function (value) {
  17408. this._numberOfTilesHeight = value;
  17409. this.updateShaderUniforms();
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17415. get: function () {
  17416. return this._numberOfTilesWidth;
  17417. },
  17418. set: function (value) {
  17419. this._numberOfTilesWidth = value;
  17420. this.updateShaderUniforms();
  17421. },
  17422. enumerable: true,
  17423. configurable: true
  17424. });
  17425. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17426. get: function () {
  17427. return this._jointColor;
  17428. },
  17429. set: function (value) {
  17430. this._jointColor = value;
  17431. this.updateShaderUniforms();
  17432. },
  17433. enumerable: true,
  17434. configurable: true
  17435. });
  17436. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17437. get: function () {
  17438. return this._marbleColor;
  17439. },
  17440. set: function (value) {
  17441. this._marbleColor = value;
  17442. this.updateShaderUniforms();
  17443. },
  17444. enumerable: true,
  17445. configurable: true
  17446. });
  17447. return MarbleProceduralTexture;
  17448. })(BABYLON.ProceduralTexture);
  17449. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17450. })(BABYLON || (BABYLON = {}));
  17451. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17452. var BABYLON;
  17453. (function (BABYLON) {
  17454. var EffectFallbacks = (function () {
  17455. function EffectFallbacks() {
  17456. this._defines = {};
  17457. this._currentRank = 32;
  17458. this._maxRank = -1;
  17459. }
  17460. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17461. if (!this._defines[rank]) {
  17462. if (rank < this._currentRank) {
  17463. this._currentRank = rank;
  17464. }
  17465. if (rank > this._maxRank) {
  17466. this._maxRank = rank;
  17467. }
  17468. this._defines[rank] = new Array();
  17469. }
  17470. this._defines[rank].push(define);
  17471. };
  17472. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17473. get: function () {
  17474. return this._currentRank <= this._maxRank;
  17475. },
  17476. enumerable: true,
  17477. configurable: true
  17478. });
  17479. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17480. var currentFallbacks = this._defines[this._currentRank];
  17481. for (var index = 0; index < currentFallbacks.length; index++) {
  17482. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17483. }
  17484. this._currentRank++;
  17485. return currentDefines;
  17486. };
  17487. return EffectFallbacks;
  17488. })();
  17489. BABYLON.EffectFallbacks = EffectFallbacks;
  17490. var Effect = (function () {
  17491. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17492. var _this = this;
  17493. this._isReady = false;
  17494. this._compilationError = "";
  17495. this._valueCache = [];
  17496. this._engine = engine;
  17497. this.name = baseName;
  17498. this.defines = defines;
  17499. this._uniformsNames = uniformsNames.concat(samplers);
  17500. this._samplers = samplers;
  17501. this._attributesNames = attributesNames;
  17502. this.onError = onError;
  17503. this.onCompiled = onCompiled;
  17504. var vertexSource;
  17505. var fragmentSource;
  17506. if (baseName.vertexElement) {
  17507. vertexSource = document.getElementById(baseName.vertexElement);
  17508. if (!vertexSource) {
  17509. vertexSource = baseName.vertexElement;
  17510. }
  17511. }
  17512. else {
  17513. vertexSource = baseName.vertex || baseName;
  17514. }
  17515. if (baseName.fragmentElement) {
  17516. fragmentSource = document.getElementById(baseName.fragmentElement);
  17517. if (!fragmentSource) {
  17518. fragmentSource = baseName.fragmentElement;
  17519. }
  17520. }
  17521. else {
  17522. fragmentSource = baseName.fragment || baseName;
  17523. }
  17524. this._loadVertexShader(vertexSource, function (vertexCode) {
  17525. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17526. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17527. });
  17528. });
  17529. }
  17530. // Properties
  17531. Effect.prototype.isReady = function () {
  17532. return this._isReady;
  17533. };
  17534. Effect.prototype.getProgram = function () {
  17535. return this._program;
  17536. };
  17537. Effect.prototype.getAttributesNames = function () {
  17538. return this._attributesNames;
  17539. };
  17540. Effect.prototype.getAttributeLocation = function (index) {
  17541. return this._attributes[index];
  17542. };
  17543. Effect.prototype.getAttributeLocationByName = function (name) {
  17544. var index = this._attributesNames.indexOf(name);
  17545. return this._attributes[index];
  17546. };
  17547. Effect.prototype.getAttributesCount = function () {
  17548. return this._attributes.length;
  17549. };
  17550. Effect.prototype.getUniformIndex = function (uniformName) {
  17551. return this._uniformsNames.indexOf(uniformName);
  17552. };
  17553. Effect.prototype.getUniform = function (uniformName) {
  17554. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17555. };
  17556. Effect.prototype.getSamplers = function () {
  17557. return this._samplers;
  17558. };
  17559. Effect.prototype.getCompilationError = function () {
  17560. return this._compilationError;
  17561. };
  17562. // Methods
  17563. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17564. // DOM element ?
  17565. if (vertex instanceof HTMLElement) {
  17566. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17567. callback(vertexCode);
  17568. return;
  17569. }
  17570. // Is in local store ?
  17571. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17572. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17573. return;
  17574. }
  17575. var vertexShaderUrl;
  17576. if (vertex[0] === ".") {
  17577. vertexShaderUrl = vertex;
  17578. }
  17579. else {
  17580. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17581. }
  17582. // Vertex shader
  17583. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17584. };
  17585. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17586. // DOM element ?
  17587. if (fragment instanceof HTMLElement) {
  17588. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17589. callback(fragmentCode);
  17590. return;
  17591. }
  17592. // Is in local store ?
  17593. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17594. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17595. return;
  17596. }
  17597. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17598. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17599. return;
  17600. }
  17601. var fragmentShaderUrl;
  17602. if (fragment[0] === ".") {
  17603. fragmentShaderUrl = fragment;
  17604. }
  17605. else {
  17606. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17607. }
  17608. // Fragment shader
  17609. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17610. };
  17611. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17612. try {
  17613. var engine = this._engine;
  17614. if (!engine.getCaps().highPrecisionShaderSupported) {
  17615. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17616. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17617. }
  17618. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17619. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17620. this._attributes = engine.getAttributes(this._program, attributesNames);
  17621. for (var index = 0; index < this._samplers.length; index++) {
  17622. var sampler = this.getUniform(this._samplers[index]);
  17623. if (sampler == null) {
  17624. this._samplers.splice(index, 1);
  17625. index--;
  17626. }
  17627. }
  17628. engine.bindSamplers(this);
  17629. this._isReady = true;
  17630. if (this.onCompiled) {
  17631. this.onCompiled(this);
  17632. }
  17633. }
  17634. catch (e) {
  17635. // Is it a problem with precision?
  17636. if (e.message.indexOf("highp") !== -1) {
  17637. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17638. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17639. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17640. return;
  17641. }
  17642. // Let's go through fallbacks then
  17643. if (fallbacks && fallbacks.isMoreFallbacks) {
  17644. defines = fallbacks.reduce(defines);
  17645. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17646. }
  17647. else {
  17648. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17649. BABYLON.Tools.Error("Defines: " + defines);
  17650. BABYLON.Tools.Error("Error: " + e.message);
  17651. this._compilationError = e.message;
  17652. if (this.onError) {
  17653. this.onError(this, this._compilationError);
  17654. }
  17655. }
  17656. }
  17657. };
  17658. Effect.prototype._bindTexture = function (channel, texture) {
  17659. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17660. };
  17661. Effect.prototype.setTexture = function (channel, texture) {
  17662. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17663. };
  17664. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17665. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17666. };
  17667. //public _cacheMatrix(uniformName, matrix) {
  17668. // if (!this._valueCache[uniformName]) {
  17669. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17670. // }
  17671. // for (var index = 0; index < 16; index++) {
  17672. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17673. // }
  17674. //};
  17675. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17676. if (!this._valueCache[uniformName]) {
  17677. this._valueCache[uniformName] = [x, y];
  17678. return;
  17679. }
  17680. this._valueCache[uniformName][0] = x;
  17681. this._valueCache[uniformName][1] = y;
  17682. };
  17683. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17684. if (!this._valueCache[uniformName]) {
  17685. this._valueCache[uniformName] = [x, y, z];
  17686. return;
  17687. }
  17688. this._valueCache[uniformName][0] = x;
  17689. this._valueCache[uniformName][1] = y;
  17690. this._valueCache[uniformName][2] = z;
  17691. };
  17692. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17693. if (!this._valueCache[uniformName]) {
  17694. this._valueCache[uniformName] = [x, y, z, w];
  17695. return;
  17696. }
  17697. this._valueCache[uniformName][0] = x;
  17698. this._valueCache[uniformName][1] = y;
  17699. this._valueCache[uniformName][2] = z;
  17700. this._valueCache[uniformName][3] = w;
  17701. };
  17702. Effect.prototype.setArray = function (uniformName, array) {
  17703. this._engine.setArray(this.getUniform(uniformName), array);
  17704. return this;
  17705. };
  17706. Effect.prototype.setArray2 = function (uniformName, array) {
  17707. this._engine.setArray2(this.getUniform(uniformName), array);
  17708. return this;
  17709. };
  17710. Effect.prototype.setArray3 = function (uniformName, array) {
  17711. this._engine.setArray3(this.getUniform(uniformName), array);
  17712. return this;
  17713. };
  17714. Effect.prototype.setArray4 = function (uniformName, array) {
  17715. this._engine.setArray4(this.getUniform(uniformName), array);
  17716. return this;
  17717. };
  17718. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17719. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17720. return this;
  17721. };
  17722. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17723. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17724. // return;
  17725. //this._cacheMatrix(uniformName, matrix);
  17726. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17727. return this;
  17728. };
  17729. Effect.prototype.setFloat = function (uniformName, value) {
  17730. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17731. return this;
  17732. this._valueCache[uniformName] = value;
  17733. this._engine.setFloat(this.getUniform(uniformName), value);
  17734. return this;
  17735. };
  17736. Effect.prototype.setBool = function (uniformName, bool) {
  17737. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17738. return this;
  17739. this._valueCache[uniformName] = bool;
  17740. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17741. return this;
  17742. };
  17743. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17744. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17745. return this;
  17746. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17747. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17748. return this;
  17749. };
  17750. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17751. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17752. return this;
  17753. this._cacheFloat2(uniformName, x, y);
  17754. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17755. return this;
  17756. };
  17757. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17758. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17759. return this;
  17760. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17761. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17762. return this;
  17763. };
  17764. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17765. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17766. return this;
  17767. this._cacheFloat3(uniformName, x, y, z);
  17768. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17769. return this;
  17770. };
  17771. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17772. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17773. return this;
  17774. this._cacheFloat4(uniformName, x, y, z, w);
  17775. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17776. return this;
  17777. };
  17778. Effect.prototype.setColor3 = function (uniformName, color3) {
  17779. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17780. return this;
  17781. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17782. this._engine.setColor3(this.getUniform(uniformName), color3);
  17783. return this;
  17784. };
  17785. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17786. 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)
  17787. return this;
  17788. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17789. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17790. return this;
  17791. };
  17792. // Statics
  17793. Effect.ShadersStore = {};
  17794. return Effect;
  17795. })();
  17796. BABYLON.Effect = Effect;
  17797. })(BABYLON || (BABYLON = {}));
  17798. //# sourceMappingURL=babylon.effect.js.map
  17799. var BABYLON;
  17800. (function (BABYLON) {
  17801. var Material = (function () {
  17802. function Material(name, scene, doNotAdd) {
  17803. this.name = name;
  17804. this.checkReadyOnEveryCall = true;
  17805. this.checkReadyOnlyOnce = false;
  17806. this.state = "";
  17807. this.alpha = 1.0;
  17808. this.backFaceCulling = true;
  17809. this._wasPreviouslyReady = false;
  17810. this._fillMode = Material.TriangleFillMode;
  17811. this.pointSize = 1.0;
  17812. this.zOffset = 0;
  17813. this.id = name;
  17814. this._scene = scene;
  17815. if (!doNotAdd) {
  17816. scene.materials.push(this);
  17817. }
  17818. }
  17819. Object.defineProperty(Material, "TriangleFillMode", {
  17820. get: function () {
  17821. return Material._TriangleFillMode;
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. Object.defineProperty(Material, "WireFrameFillMode", {
  17827. get: function () {
  17828. return Material._WireFrameFillMode;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Object.defineProperty(Material, "PointFillMode", {
  17834. get: function () {
  17835. return Material._PointFillMode;
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. Object.defineProperty(Material.prototype, "wireframe", {
  17841. get: function () {
  17842. return this._fillMode === Material.WireFrameFillMode;
  17843. },
  17844. set: function (value) {
  17845. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(Material.prototype, "pointsCloud", {
  17851. get: function () {
  17852. return this._fillMode === Material.PointFillMode;
  17853. },
  17854. set: function (value) {
  17855. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(Material.prototype, "fillMode", {
  17861. get: function () {
  17862. return this._fillMode;
  17863. },
  17864. set: function (value) {
  17865. this._fillMode = value;
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Material.prototype.isReady = function (mesh, useInstances) {
  17871. return true;
  17872. };
  17873. Material.prototype.getEffect = function () {
  17874. return this._effect;
  17875. };
  17876. Material.prototype.getScene = function () {
  17877. return this._scene;
  17878. };
  17879. Material.prototype.needAlphaBlending = function () {
  17880. return (this.alpha < 1.0);
  17881. };
  17882. Material.prototype.needAlphaTesting = function () {
  17883. return false;
  17884. };
  17885. Material.prototype.getAlphaTestTexture = function () {
  17886. return null;
  17887. };
  17888. Material.prototype.trackCreation = function (onCompiled, onError) {
  17889. };
  17890. Material.prototype._preBind = function () {
  17891. var engine = this._scene.getEngine();
  17892. engine.enableEffect(this._effect);
  17893. engine.setState(this.backFaceCulling, this.zOffset);
  17894. };
  17895. Material.prototype.bind = function (world, mesh) {
  17896. this._scene._cachedMaterial = this;
  17897. if (this.onBind) {
  17898. this.onBind(this, mesh);
  17899. }
  17900. };
  17901. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17902. };
  17903. Material.prototype.unbind = function () {
  17904. };
  17905. Material.prototype.dispose = function (forceDisposeEffect) {
  17906. // Remove from scene
  17907. var index = this._scene.materials.indexOf(this);
  17908. this._scene.materials.splice(index, 1);
  17909. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17910. if (forceDisposeEffect && this._effect) {
  17911. this._scene.getEngine()._releaseEffect(this._effect);
  17912. this._effect = null;
  17913. }
  17914. // Callback
  17915. if (this.onDispose) {
  17916. this.onDispose();
  17917. }
  17918. };
  17919. Material._TriangleFillMode = 0;
  17920. Material._WireFrameFillMode = 1;
  17921. Material._PointFillMode = 2;
  17922. return Material;
  17923. })();
  17924. BABYLON.Material = Material;
  17925. })(BABYLON || (BABYLON = {}));
  17926. //# sourceMappingURL=babylon.material.js.map
  17927. var __extends = this.__extends || function (d, b) {
  17928. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17929. function __() { this.constructor = d; }
  17930. __.prototype = b.prototype;
  17931. d.prototype = new __();
  17932. };
  17933. var BABYLON;
  17934. (function (BABYLON) {
  17935. var maxSimultaneousLights = 4;
  17936. var FresnelParameters = (function () {
  17937. function FresnelParameters() {
  17938. this.isEnabled = true;
  17939. this.leftColor = BABYLON.Color3.White();
  17940. this.rightColor = BABYLON.Color3.Black();
  17941. this.bias = 0;
  17942. this.power = 1;
  17943. }
  17944. return FresnelParameters;
  17945. })();
  17946. BABYLON.FresnelParameters = FresnelParameters;
  17947. var StandardMaterial = (function (_super) {
  17948. __extends(StandardMaterial, _super);
  17949. function StandardMaterial(name, scene) {
  17950. var _this = this;
  17951. _super.call(this, name, scene);
  17952. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17953. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17954. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17955. this.specularPower = 64;
  17956. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17957. this.useAlphaFromDiffuseTexture = false;
  17958. this.useSpecularOverAlpha = true;
  17959. this.fogEnabled = true;
  17960. this._cachedDefines = null;
  17961. this._renderTargets = new BABYLON.SmartArray(16);
  17962. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17963. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17964. this._scaledDiffuse = new BABYLON.Color3();
  17965. this._scaledSpecular = new BABYLON.Color3();
  17966. this.getRenderTargetTextures = function () {
  17967. _this._renderTargets.reset();
  17968. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17969. _this._renderTargets.push(_this.reflectionTexture);
  17970. }
  17971. return _this._renderTargets;
  17972. };
  17973. }
  17974. StandardMaterial.prototype.needAlphaBlending = function () {
  17975. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17976. };
  17977. StandardMaterial.prototype.needAlphaTesting = function () {
  17978. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17979. };
  17980. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17981. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17982. };
  17983. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17984. return this.diffuseTexture;
  17985. };
  17986. // Methods
  17987. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17988. if (this.checkReadyOnlyOnce) {
  17989. if (this._wasPreviouslyReady) {
  17990. return true;
  17991. }
  17992. }
  17993. var scene = this.getScene();
  17994. if (!this.checkReadyOnEveryCall) {
  17995. if (this._renderId === scene.getRenderId()) {
  17996. return true;
  17997. }
  17998. }
  17999. var engine = scene.getEngine();
  18000. var defines = [];
  18001. var fallbacks = new BABYLON.EffectFallbacks();
  18002. var needNormals = false;
  18003. var needUVs = false;
  18004. // Textures
  18005. if (scene.texturesEnabled) {
  18006. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18007. if (!this.diffuseTexture.isReady()) {
  18008. return false;
  18009. }
  18010. else {
  18011. needUVs = true;
  18012. defines.push("#define DIFFUSE");
  18013. }
  18014. }
  18015. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18016. if (!this.ambientTexture.isReady()) {
  18017. return false;
  18018. }
  18019. else {
  18020. needUVs = true;
  18021. defines.push("#define AMBIENT");
  18022. }
  18023. }
  18024. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18025. if (!this.opacityTexture.isReady()) {
  18026. return false;
  18027. }
  18028. else {
  18029. needUVs = true;
  18030. defines.push("#define OPACITY");
  18031. if (this.opacityTexture.getAlphaFromRGB) {
  18032. defines.push("#define OPACITYRGB");
  18033. }
  18034. }
  18035. }
  18036. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18037. if (!this.reflectionTexture.isReady()) {
  18038. return false;
  18039. }
  18040. else {
  18041. needNormals = true;
  18042. needUVs = true;
  18043. defines.push("#define REFLECTION");
  18044. fallbacks.addFallback(0, "REFLECTION");
  18045. }
  18046. }
  18047. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18048. if (!this.emissiveTexture.isReady()) {
  18049. return false;
  18050. }
  18051. else {
  18052. needUVs = true;
  18053. defines.push("#define EMISSIVE");
  18054. }
  18055. }
  18056. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18057. if (!this.specularTexture.isReady()) {
  18058. return false;
  18059. }
  18060. else {
  18061. needUVs = true;
  18062. defines.push("#define SPECULAR");
  18063. fallbacks.addFallback(0, "SPECULAR");
  18064. }
  18065. }
  18066. }
  18067. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18068. if (!this.bumpTexture.isReady()) {
  18069. return false;
  18070. }
  18071. else {
  18072. needUVs = true;
  18073. defines.push("#define BUMP");
  18074. fallbacks.addFallback(0, "BUMP");
  18075. }
  18076. }
  18077. // Effect
  18078. if (this.useSpecularOverAlpha) {
  18079. defines.push("#define SPECULAROVERALPHA");
  18080. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18081. }
  18082. if (scene.clipPlane) {
  18083. defines.push("#define CLIPPLANE");
  18084. }
  18085. if (engine.getAlphaTesting()) {
  18086. defines.push("#define ALPHATEST");
  18087. }
  18088. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18089. defines.push("#define ALPHAFROMDIFFUSE");
  18090. }
  18091. // Point size
  18092. if (this.pointsCloud || scene.forcePointsCloud) {
  18093. defines.push("#define POINTSIZE");
  18094. }
  18095. // Fog
  18096. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18097. defines.push("#define FOG");
  18098. fallbacks.addFallback(1, "FOG");
  18099. }
  18100. var shadowsActivated = false;
  18101. var lightIndex = 0;
  18102. if (scene.lightsEnabled) {
  18103. for (var index = 0; index < scene.lights.length; index++) {
  18104. var light = scene.lights[index];
  18105. if (!light.isEnabled()) {
  18106. continue;
  18107. }
  18108. // Excluded check
  18109. if (light._excludedMeshesIds.length > 0) {
  18110. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18111. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18112. if (excludedMesh) {
  18113. light.excludedMeshes.push(excludedMesh);
  18114. }
  18115. }
  18116. light._excludedMeshesIds = [];
  18117. }
  18118. // Included check
  18119. if (light._includedOnlyMeshesIds.length > 0) {
  18120. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18121. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18122. if (includedOnlyMesh) {
  18123. light.includedOnlyMeshes.push(includedOnlyMesh);
  18124. }
  18125. }
  18126. light._includedOnlyMeshesIds = [];
  18127. }
  18128. if (!light.canAffectMesh(mesh)) {
  18129. continue;
  18130. }
  18131. needNormals = true;
  18132. defines.push("#define LIGHT" + lightIndex);
  18133. if (lightIndex > 0) {
  18134. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18135. }
  18136. var type;
  18137. if (light instanceof BABYLON.SpotLight) {
  18138. type = "#define SPOTLIGHT" + lightIndex;
  18139. }
  18140. else if (light instanceof BABYLON.HemisphericLight) {
  18141. type = "#define HEMILIGHT" + lightIndex;
  18142. }
  18143. else {
  18144. type = "#define POINTDIRLIGHT" + lightIndex;
  18145. }
  18146. defines.push(type);
  18147. if (lightIndex > 0) {
  18148. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18149. }
  18150. // Shadows
  18151. if (scene.shadowsEnabled) {
  18152. var shadowGenerator = light.getShadowGenerator();
  18153. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18154. defines.push("#define SHADOW" + lightIndex);
  18155. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18156. if (!shadowsActivated) {
  18157. defines.push("#define SHADOWS");
  18158. shadowsActivated = true;
  18159. }
  18160. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18161. defines.push("#define SHADOWVSM" + lightIndex);
  18162. if (lightIndex > 0) {
  18163. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18164. }
  18165. }
  18166. if (shadowGenerator.usePoissonSampling) {
  18167. defines.push("#define SHADOWPCF" + lightIndex);
  18168. if (lightIndex > 0) {
  18169. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18170. }
  18171. }
  18172. }
  18173. }
  18174. lightIndex++;
  18175. if (lightIndex === maxSimultaneousLights)
  18176. break;
  18177. }
  18178. }
  18179. if (StandardMaterial.FresnelEnabled) {
  18180. // Fresnel
  18181. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18182. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18183. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18184. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18185. var fresnelRank = 1;
  18186. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18187. defines.push("#define DIFFUSEFRESNEL");
  18188. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18189. fresnelRank++;
  18190. }
  18191. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18192. defines.push("#define OPACITYFRESNEL");
  18193. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18194. fresnelRank++;
  18195. }
  18196. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18197. defines.push("#define REFLECTIONFRESNEL");
  18198. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18199. fresnelRank++;
  18200. }
  18201. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18202. defines.push("#define EMISSIVEFRESNEL");
  18203. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18204. fresnelRank++;
  18205. }
  18206. needNormals = true;
  18207. defines.push("#define FRESNEL");
  18208. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18209. }
  18210. }
  18211. // Attribs
  18212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18213. if (mesh) {
  18214. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18215. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18216. defines.push("#define NORMAL");
  18217. }
  18218. if (needUVs) {
  18219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18220. attribs.push(BABYLON.VertexBuffer.UVKind);
  18221. defines.push("#define UV1");
  18222. }
  18223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18225. defines.push("#define UV2");
  18226. }
  18227. }
  18228. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18229. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18230. defines.push("#define VERTEXCOLOR");
  18231. if (mesh.hasVertexAlpha) {
  18232. defines.push("#define VERTEXALPHA");
  18233. }
  18234. }
  18235. if (mesh.useBones) {
  18236. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18237. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18238. defines.push("#define BONES");
  18239. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18240. defines.push("#define BONES4");
  18241. fallbacks.addFallback(0, "BONES4");
  18242. }
  18243. // Instances
  18244. if (useInstances) {
  18245. defines.push("#define INSTANCES");
  18246. attribs.push("world0");
  18247. attribs.push("world1");
  18248. attribs.push("world2");
  18249. attribs.push("world3");
  18250. }
  18251. }
  18252. // Get correct effect
  18253. var join = defines.join("\n");
  18254. if (this._cachedDefines !== join) {
  18255. this._cachedDefines = join;
  18256. scene.resetCachedMaterial();
  18257. // Legacy browser patch
  18258. var shaderName = "default";
  18259. if (!scene.getEngine().getCaps().standardDerivatives) {
  18260. shaderName = "legacydefault";
  18261. }
  18262. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18263. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18264. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18265. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18266. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18267. "vFogInfos", "vFogColor", "pointSize",
  18268. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18269. "mBones",
  18270. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18271. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18272. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18273. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18274. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18275. ], join, fallbacks, this.onCompiled, this.onError);
  18276. }
  18277. if (!this._effect.isReady()) {
  18278. return false;
  18279. }
  18280. this._renderId = scene.getRenderId();
  18281. this._wasPreviouslyReady = true;
  18282. return true;
  18283. };
  18284. StandardMaterial.prototype.unbind = function () {
  18285. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18286. this._effect.setTexture("reflection2DSampler", null);
  18287. }
  18288. };
  18289. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18290. this._effect.setMatrix("world", world);
  18291. };
  18292. StandardMaterial.prototype.bind = function (world, mesh) {
  18293. var scene = this.getScene();
  18294. // Matrices
  18295. this.bindOnlyWorldMatrix(world);
  18296. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18297. // Bones
  18298. if (mesh && mesh.useBones) {
  18299. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18300. }
  18301. if (scene.getCachedMaterial() !== this) {
  18302. if (StandardMaterial.FresnelEnabled) {
  18303. // Fresnel
  18304. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18305. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18306. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18307. }
  18308. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18309. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18310. }
  18311. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18312. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18313. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18314. }
  18315. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18316. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18317. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18318. }
  18319. }
  18320. // Textures
  18321. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18322. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18323. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18324. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18325. }
  18326. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18327. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18328. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18329. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18330. }
  18331. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18332. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18333. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18334. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18335. }
  18336. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18337. if (this.reflectionTexture.isCube) {
  18338. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18339. }
  18340. else {
  18341. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18342. }
  18343. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18344. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18345. }
  18346. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18347. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18348. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18349. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18350. }
  18351. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18352. this._effect.setTexture("specularSampler", this.specularTexture);
  18353. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18354. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18355. }
  18356. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18357. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18358. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18359. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18360. }
  18361. // Clip plane
  18362. if (scene.clipPlane) {
  18363. var clipPlane = scene.clipPlane;
  18364. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18365. }
  18366. // Point size
  18367. if (this.pointsCloud) {
  18368. this._effect.setFloat("pointSize", this.pointSize);
  18369. }
  18370. // Colors
  18371. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18372. // Scaling down color according to emissive
  18373. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18374. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18375. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18376. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18377. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18378. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18379. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18380. }
  18381. // Scaling down color according to emissive
  18382. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18383. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18384. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18385. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18386. if (scene.lightsEnabled) {
  18387. var lightIndex = 0;
  18388. for (var index = 0; index < scene.lights.length; index++) {
  18389. var light = scene.lights[index];
  18390. if (!light.isEnabled()) {
  18391. continue;
  18392. }
  18393. if (!light.canAffectMesh(mesh)) {
  18394. continue;
  18395. }
  18396. if (light instanceof BABYLON.PointLight) {
  18397. // Point Light
  18398. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18399. }
  18400. else if (light instanceof BABYLON.DirectionalLight) {
  18401. // Directional Light
  18402. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18403. }
  18404. else if (light instanceof BABYLON.SpotLight) {
  18405. // Spot Light
  18406. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18407. }
  18408. else if (light instanceof BABYLON.HemisphericLight) {
  18409. // Hemispheric Light
  18410. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18411. }
  18412. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18413. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18414. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18415. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18416. // Shadows
  18417. if (scene.shadowsEnabled) {
  18418. var shadowGenerator = light.getShadowGenerator();
  18419. if (mesh.receiveShadows && shadowGenerator) {
  18420. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18421. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18422. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18423. }
  18424. }
  18425. lightIndex++;
  18426. if (lightIndex === maxSimultaneousLights)
  18427. break;
  18428. }
  18429. }
  18430. // View
  18431. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18432. this._effect.setMatrix("view", scene.getViewMatrix());
  18433. }
  18434. // Fog
  18435. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18436. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18437. this._effect.setColor3("vFogColor", scene.fogColor);
  18438. }
  18439. _super.prototype.bind.call(this, world, mesh);
  18440. };
  18441. StandardMaterial.prototype.getAnimatables = function () {
  18442. var results = [];
  18443. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18444. results.push(this.diffuseTexture);
  18445. }
  18446. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18447. results.push(this.ambientTexture);
  18448. }
  18449. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18450. results.push(this.opacityTexture);
  18451. }
  18452. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18453. results.push(this.reflectionTexture);
  18454. }
  18455. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18456. results.push(this.emissiveTexture);
  18457. }
  18458. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18459. results.push(this.specularTexture);
  18460. }
  18461. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18462. results.push(this.bumpTexture);
  18463. }
  18464. return results;
  18465. };
  18466. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18467. if (this.diffuseTexture) {
  18468. this.diffuseTexture.dispose();
  18469. }
  18470. if (this.ambientTexture) {
  18471. this.ambientTexture.dispose();
  18472. }
  18473. if (this.opacityTexture) {
  18474. this.opacityTexture.dispose();
  18475. }
  18476. if (this.reflectionTexture) {
  18477. this.reflectionTexture.dispose();
  18478. }
  18479. if (this.emissiveTexture) {
  18480. this.emissiveTexture.dispose();
  18481. }
  18482. if (this.specularTexture) {
  18483. this.specularTexture.dispose();
  18484. }
  18485. if (this.bumpTexture) {
  18486. this.bumpTexture.dispose();
  18487. }
  18488. _super.prototype.dispose.call(this, forceDisposeEffect);
  18489. };
  18490. StandardMaterial.prototype.clone = function (name) {
  18491. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18492. // Base material
  18493. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18494. newStandardMaterial.alpha = this.alpha;
  18495. newStandardMaterial.fillMode = this.fillMode;
  18496. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18497. // Standard material
  18498. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18499. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18500. }
  18501. if (this.ambientTexture && this.ambientTexture.clone) {
  18502. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18503. }
  18504. if (this.opacityTexture && this.opacityTexture.clone) {
  18505. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18506. }
  18507. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18508. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18509. }
  18510. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18511. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18512. }
  18513. if (this.specularTexture && this.specularTexture.clone) {
  18514. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18515. }
  18516. if (this.bumpTexture && this.bumpTexture.clone) {
  18517. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18518. }
  18519. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18520. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18521. newStandardMaterial.specularColor = this.specularColor.clone();
  18522. newStandardMaterial.specularPower = this.specularPower;
  18523. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18524. return newStandardMaterial;
  18525. };
  18526. // Statics
  18527. // Flags used to enable or disable a type of texture for all Standard Materials
  18528. StandardMaterial.DiffuseTextureEnabled = true;
  18529. StandardMaterial.AmbientTextureEnabled = true;
  18530. StandardMaterial.OpacityTextureEnabled = true;
  18531. StandardMaterial.ReflectionTextureEnabled = true;
  18532. StandardMaterial.EmissiveTextureEnabled = true;
  18533. StandardMaterial.SpecularTextureEnabled = true;
  18534. StandardMaterial.BumpTextureEnabled = true;
  18535. StandardMaterial.FresnelEnabled = true;
  18536. return StandardMaterial;
  18537. })(BABYLON.Material);
  18538. BABYLON.StandardMaterial = StandardMaterial;
  18539. })(BABYLON || (BABYLON = {}));
  18540. //# sourceMappingURL=babylon.standardMaterial.js.map
  18541. var __extends = this.__extends || function (d, b) {
  18542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18543. function __() { this.constructor = d; }
  18544. __.prototype = b.prototype;
  18545. d.prototype = new __();
  18546. };
  18547. var BABYLON;
  18548. (function (BABYLON) {
  18549. var MultiMaterial = (function (_super) {
  18550. __extends(MultiMaterial, _super);
  18551. function MultiMaterial(name, scene) {
  18552. _super.call(this, name, scene, true);
  18553. this.subMaterials = new Array();
  18554. scene.multiMaterials.push(this);
  18555. }
  18556. // Properties
  18557. MultiMaterial.prototype.getSubMaterial = function (index) {
  18558. if (index < 0 || index >= this.subMaterials.length) {
  18559. return this.getScene().defaultMaterial;
  18560. }
  18561. return this.subMaterials[index];
  18562. };
  18563. // Methods
  18564. MultiMaterial.prototype.isReady = function (mesh) {
  18565. for (var index = 0; index < this.subMaterials.length; index++) {
  18566. var subMaterial = this.subMaterials[index];
  18567. if (subMaterial) {
  18568. if (!this.subMaterials[index].isReady(mesh)) {
  18569. return false;
  18570. }
  18571. }
  18572. }
  18573. return true;
  18574. };
  18575. MultiMaterial.prototype.clone = function (name) {
  18576. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18577. for (var index = 0; index < this.subMaterials.length; index++) {
  18578. var subMaterial = this.subMaterials[index];
  18579. newMultiMaterial.subMaterials.push(subMaterial);
  18580. }
  18581. return newMultiMaterial;
  18582. };
  18583. return MultiMaterial;
  18584. })(BABYLON.Material);
  18585. BABYLON.MultiMaterial = MultiMaterial;
  18586. })(BABYLON || (BABYLON = {}));
  18587. //# sourceMappingURL=babylon.multiMaterial.js.map
  18588. var BABYLON;
  18589. (function (BABYLON) {
  18590. var SceneLoader = (function () {
  18591. function SceneLoader() {
  18592. }
  18593. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18594. get: function () {
  18595. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18596. },
  18597. set: function (value) {
  18598. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18599. },
  18600. enumerable: true,
  18601. configurable: true
  18602. });
  18603. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18604. get: function () {
  18605. return SceneLoader._ShowLoadingScreen;
  18606. },
  18607. set: function (value) {
  18608. SceneLoader._ShowLoadingScreen = value;
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18614. var dotPosition = sceneFilename.lastIndexOf(".");
  18615. var queryStringPosition = sceneFilename.indexOf("?");
  18616. if (queryStringPosition === -1) {
  18617. queryStringPosition = sceneFilename.length;
  18618. }
  18619. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18620. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18621. var plugin = this._registeredPlugins[index];
  18622. if (plugin.extensions.indexOf(extension) !== -1) {
  18623. return plugin;
  18624. }
  18625. }
  18626. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18627. };
  18628. // Public functions
  18629. SceneLoader.RegisterPlugin = function (plugin) {
  18630. plugin.extensions = plugin.extensions.toLowerCase();
  18631. SceneLoader._registeredPlugins.push(plugin);
  18632. };
  18633. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18634. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18635. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18636. return;
  18637. }
  18638. var manifestChecked = function (success) {
  18639. scene.database = database;
  18640. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18641. var importMeshFromData = function (data) {
  18642. var meshes = [];
  18643. var particleSystems = [];
  18644. var skeletons = [];
  18645. try {
  18646. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18647. if (onerror) {
  18648. onerror(scene, 'unable to load the scene');
  18649. }
  18650. return;
  18651. }
  18652. }
  18653. catch (e) {
  18654. if (onerror) {
  18655. onerror(scene, e);
  18656. }
  18657. return;
  18658. }
  18659. if (onsuccess) {
  18660. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18661. onsuccess(meshes, particleSystems, skeletons);
  18662. }
  18663. };
  18664. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18665. // Direct load
  18666. importMeshFromData(sceneFilename.substr(5));
  18667. return;
  18668. }
  18669. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18670. importMeshFromData(data);
  18671. }, progressCallBack, database);
  18672. };
  18673. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18674. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18675. };
  18676. /**
  18677. * Load a scene
  18678. * @param rootUrl a string that defines the root url for scene and resources
  18679. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18680. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18681. */
  18682. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18683. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18684. };
  18685. /**
  18686. * Append a scene
  18687. * @param rootUrl a string that defines the root url for scene and resources
  18688. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18689. * @param scene is the instance of BABYLON.Scene to append to
  18690. */
  18691. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18692. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18693. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18694. return;
  18695. }
  18696. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18697. var database;
  18698. if (SceneLoader.ShowLoadingScreen) {
  18699. scene.getEngine().displayLoadingUI();
  18700. }
  18701. var loadSceneFromData = function (data) {
  18702. scene.database = database;
  18703. if (!plugin.load(scene, data, rootUrl)) {
  18704. if (onerror) {
  18705. onerror(scene);
  18706. }
  18707. scene.getEngine().hideLoadingUI();
  18708. return;
  18709. }
  18710. if (onsuccess) {
  18711. onsuccess(scene);
  18712. }
  18713. if (SceneLoader.ShowLoadingScreen) {
  18714. scene.executeWhenReady(function () {
  18715. scene.getEngine().hideLoadingUI();
  18716. });
  18717. }
  18718. };
  18719. var manifestChecked = function (success) {
  18720. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18721. };
  18722. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18723. // Direct load
  18724. loadSceneFromData(sceneFilename.substr(5));
  18725. return;
  18726. }
  18727. if (rootUrl.indexOf("file:") === -1) {
  18728. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18729. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18730. }
  18731. else {
  18732. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18733. }
  18734. };
  18735. // Flags
  18736. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18737. SceneLoader._ShowLoadingScreen = true;
  18738. // Members
  18739. SceneLoader._registeredPlugins = new Array();
  18740. return SceneLoader;
  18741. })();
  18742. BABYLON.SceneLoader = SceneLoader;
  18743. ;
  18744. })(BABYLON || (BABYLON = {}));
  18745. //# sourceMappingURL=babylon.sceneLoader.js.map
  18746. var BABYLON;
  18747. (function (BABYLON) {
  18748. var Internals;
  18749. (function (Internals) {
  18750. var checkColors4 = function (colors, count) {
  18751. // Check if color3 was used
  18752. if (colors.length === count * 3) {
  18753. var colors4 = [];
  18754. for (var index = 0; index < colors.length; index += 3) {
  18755. var newIndex = (index / 3) * 4;
  18756. colors4[newIndex] = colors[index];
  18757. colors4[newIndex + 1] = colors[index + 1];
  18758. colors4[newIndex + 2] = colors[index + 2];
  18759. colors4[newIndex + 3] = 1.0;
  18760. }
  18761. return colors4;
  18762. }
  18763. return colors;
  18764. };
  18765. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18766. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18767. texture.name = parsedTexture.name;
  18768. texture.hasAlpha = parsedTexture.hasAlpha;
  18769. texture.level = parsedTexture.level;
  18770. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18771. return texture;
  18772. };
  18773. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18774. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18775. return null;
  18776. }
  18777. if (parsedTexture.isCube) {
  18778. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18779. }
  18780. var texture;
  18781. if (parsedTexture.mirrorPlane) {
  18782. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18783. texture._waitingRenderList = parsedTexture.renderList;
  18784. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18785. }
  18786. else if (parsedTexture.isRenderTarget) {
  18787. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18788. texture._waitingRenderList = parsedTexture.renderList;
  18789. }
  18790. else {
  18791. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18792. }
  18793. texture.name = parsedTexture.name;
  18794. texture.hasAlpha = parsedTexture.hasAlpha;
  18795. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18796. texture.level = parsedTexture.level;
  18797. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18798. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18799. texture.uOffset = parsedTexture.uOffset;
  18800. texture.vOffset = parsedTexture.vOffset;
  18801. texture.uScale = parsedTexture.uScale;
  18802. texture.vScale = parsedTexture.vScale;
  18803. texture.uAng = parsedTexture.uAng;
  18804. texture.vAng = parsedTexture.vAng;
  18805. texture.wAng = parsedTexture.wAng;
  18806. texture.wrapU = parsedTexture.wrapU;
  18807. texture.wrapV = parsedTexture.wrapV;
  18808. // Animations
  18809. if (parsedTexture.animations) {
  18810. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18811. var parsedAnimation = parsedTexture.animations[animationIndex];
  18812. texture.animations.push(parseAnimation(parsedAnimation));
  18813. }
  18814. }
  18815. return texture;
  18816. };
  18817. var parseSkeleton = function (parsedSkeleton, scene) {
  18818. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18819. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18820. var parsedBone = parsedSkeleton.bones[index];
  18821. var parentBone = null;
  18822. if (parsedBone.parentBoneIndex > -1) {
  18823. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18824. }
  18825. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18826. if (parsedBone.animation) {
  18827. bone.animations.push(parseAnimation(parsedBone.animation));
  18828. }
  18829. }
  18830. return skeleton;
  18831. };
  18832. var parseFresnelParameters = function (parsedFresnelParameters) {
  18833. var fresnelParameters = new BABYLON.FresnelParameters();
  18834. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18835. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18836. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18837. fresnelParameters.bias = parsedFresnelParameters.bias;
  18838. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18839. return fresnelParameters;
  18840. };
  18841. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18842. var material;
  18843. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18844. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18845. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18846. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18847. material.specularPower = parsedMaterial.specularPower;
  18848. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18849. material.alpha = parsedMaterial.alpha;
  18850. material.id = parsedMaterial.id;
  18851. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18852. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18853. material.wireframe = parsedMaterial.wireframe;
  18854. if (parsedMaterial.diffuseTexture) {
  18855. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18856. }
  18857. if (parsedMaterial.diffuseFresnelParameters) {
  18858. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18859. }
  18860. if (parsedMaterial.ambientTexture) {
  18861. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18862. }
  18863. if (parsedMaterial.opacityTexture) {
  18864. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18865. }
  18866. if (parsedMaterial.opacityFresnelParameters) {
  18867. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18868. }
  18869. if (parsedMaterial.reflectionTexture) {
  18870. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18871. }
  18872. if (parsedMaterial.reflectionFresnelParameters) {
  18873. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18874. }
  18875. if (parsedMaterial.emissiveTexture) {
  18876. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18877. }
  18878. if (parsedMaterial.emissiveFresnelParameters) {
  18879. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18880. }
  18881. if (parsedMaterial.specularTexture) {
  18882. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18883. }
  18884. if (parsedMaterial.bumpTexture) {
  18885. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18886. }
  18887. return material;
  18888. };
  18889. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18890. for (var index = 0; index < parsedData.materials.length; index++) {
  18891. var parsedMaterial = parsedData.materials[index];
  18892. if (parsedMaterial.id === id) {
  18893. return parseMaterial(parsedMaterial, scene, rootUrl);
  18894. }
  18895. }
  18896. return null;
  18897. };
  18898. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18899. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18900. multiMaterial.id = parsedMultiMaterial.id;
  18901. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18902. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18903. var subMatId = parsedMultiMaterial.materials[matIndex];
  18904. if (subMatId) {
  18905. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18906. }
  18907. else {
  18908. multiMaterial.subMaterials.push(null);
  18909. }
  18910. }
  18911. return multiMaterial;
  18912. };
  18913. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18914. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18915. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18916. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18917. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18918. var parsedFlare = parsedLensFlareSystem.flares[index];
  18919. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18920. }
  18921. return lensFlareSystem;
  18922. };
  18923. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18924. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18925. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18926. if (parsedParticleSystem.textureName) {
  18927. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18928. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18929. }
  18930. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18931. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18932. particleSystem.minSize = parsedParticleSystem.minSize;
  18933. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18934. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18935. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18936. particleSystem.emitter = emitter;
  18937. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18938. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18939. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18940. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18941. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18942. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18943. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18944. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18945. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18946. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18947. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18948. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18949. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18950. particleSystem.start();
  18951. return particleSystem;
  18952. };
  18953. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18954. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18955. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18956. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18957. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18958. shadowGenerator.getShadowMap().renderList.push(mesh);
  18959. }
  18960. if (parsedShadowGenerator.usePoissonSampling) {
  18961. shadowGenerator.usePoissonSampling = true;
  18962. }
  18963. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18964. shadowGenerator.useVarianceShadowMap = true;
  18965. }
  18966. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18967. shadowGenerator.useBlurVarianceShadowMap = true;
  18968. if (parsedShadowGenerator.blurScale) {
  18969. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18970. }
  18971. if (parsedShadowGenerator.blurBoxOffset) {
  18972. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18973. }
  18974. }
  18975. if (parsedShadowGenerator.bias !== undefined) {
  18976. shadowGenerator.bias = parsedShadowGenerator.bias;
  18977. }
  18978. return shadowGenerator;
  18979. };
  18980. var parseAnimation = function (parsedAnimation) {
  18981. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18982. var dataType = parsedAnimation.dataType;
  18983. var keys = [];
  18984. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18985. var key = parsedAnimation.keys[index];
  18986. var data;
  18987. switch (dataType) {
  18988. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18989. data = key.values[0];
  18990. break;
  18991. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18992. data = BABYLON.Quaternion.FromArray(key.values);
  18993. break;
  18994. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18995. data = BABYLON.Matrix.FromArray(key.values);
  18996. break;
  18997. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18998. default:
  18999. data = BABYLON.Vector3.FromArray(key.values);
  19000. break;
  19001. }
  19002. keys.push({
  19003. frame: key.frame,
  19004. value: data
  19005. });
  19006. }
  19007. animation.setKeys(keys);
  19008. return animation;
  19009. };
  19010. var parseLight = function (parsedLight, scene) {
  19011. var light;
  19012. switch (parsedLight.type) {
  19013. case 0:
  19014. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19015. break;
  19016. case 1:
  19017. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19018. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19019. break;
  19020. case 2:
  19021. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19022. break;
  19023. case 3:
  19024. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19025. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19026. break;
  19027. }
  19028. light.id = parsedLight.id;
  19029. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19030. if (parsedLight.intensity !== undefined) {
  19031. light.intensity = parsedLight.intensity;
  19032. }
  19033. if (parsedLight.range) {
  19034. light.range = parsedLight.range;
  19035. }
  19036. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19037. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19038. if (parsedLight.excludedMeshesIds) {
  19039. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19040. }
  19041. // Parent
  19042. if (parsedLight.parentId) {
  19043. light._waitingParentId = parsedLight.parentId;
  19044. }
  19045. if (parsedLight.includedOnlyMeshesIds) {
  19046. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19047. }
  19048. // Animations
  19049. if (parsedLight.animations) {
  19050. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19051. var parsedAnimation = parsedLight.animations[animationIndex];
  19052. light.animations.push(parseAnimation(parsedAnimation));
  19053. }
  19054. }
  19055. if (parsedLight.autoAnimate) {
  19056. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19057. }
  19058. };
  19059. var parseCamera = function (parsedCamera, scene) {
  19060. var camera;
  19061. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19062. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19063. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19064. var alpha = parsedCamera.alpha;
  19065. var beta = parsedCamera.beta;
  19066. var radius = parsedCamera.radius;
  19067. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19068. var eye_space = parsedCamera.eye_space;
  19069. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19070. }
  19071. else {
  19072. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19073. }
  19074. }
  19075. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19076. eye_space = parsedCamera.eye_space;
  19077. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19078. }
  19079. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19080. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19081. }
  19082. else if (parsedCamera.type === "FollowCamera") {
  19083. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19084. camera.heightOffset = parsedCamera.heightOffset;
  19085. camera.radius = parsedCamera.radius;
  19086. camera.rotationOffset = parsedCamera.rotationOffset;
  19087. if (lockedTargetMesh)
  19088. camera.target = lockedTargetMesh;
  19089. }
  19090. else if (parsedCamera.type === "GamepadCamera") {
  19091. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19092. }
  19093. else if (parsedCamera.type === "TouchCamera") {
  19094. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19095. }
  19096. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19097. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19098. }
  19099. else if (parsedCamera.type === "WebVRFreeCamera") {
  19100. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19101. }
  19102. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19103. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19104. }
  19105. else {
  19106. // Free Camera is the default value
  19107. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19108. }
  19109. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19110. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19111. camera.lockedTarget = lockedTargetMesh;
  19112. }
  19113. camera.id = parsedCamera.id;
  19114. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19115. // Parent
  19116. if (parsedCamera.parentId) {
  19117. camera._waitingParentId = parsedCamera.parentId;
  19118. }
  19119. // Target
  19120. if (parsedCamera.target) {
  19121. if (camera.setTarget) {
  19122. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19123. }
  19124. else {
  19125. //For ArcRotate
  19126. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19127. }
  19128. }
  19129. else {
  19130. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19131. }
  19132. camera.fov = parsedCamera.fov;
  19133. camera.minZ = parsedCamera.minZ;
  19134. camera.maxZ = parsedCamera.maxZ;
  19135. camera.speed = parsedCamera.speed;
  19136. camera.inertia = parsedCamera.inertia;
  19137. camera.checkCollisions = parsedCamera.checkCollisions;
  19138. camera.applyGravity = parsedCamera.applyGravity;
  19139. if (parsedCamera.ellipsoid) {
  19140. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19141. }
  19142. // Animations
  19143. if (parsedCamera.animations) {
  19144. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19145. var parsedAnimation = parsedCamera.animations[animationIndex];
  19146. camera.animations.push(parseAnimation(parsedAnimation));
  19147. }
  19148. }
  19149. if (parsedCamera.autoAnimate) {
  19150. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19151. }
  19152. // Layer Mask
  19153. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19154. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19155. }
  19156. else {
  19157. camera.layerMask = 0xFFFFFFFF;
  19158. }
  19159. return camera;
  19160. };
  19161. var parseGeometry = function (parsedGeometry, scene) {
  19162. var id = parsedGeometry.id;
  19163. return scene.getGeometryByID(id);
  19164. };
  19165. var parseBox = function (parsedBox, scene) {
  19166. if (parseGeometry(parsedBox, scene)) {
  19167. return null; // null since geometry could be something else than a box...
  19168. }
  19169. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19170. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19171. scene.pushGeometry(box, true);
  19172. return box;
  19173. };
  19174. var parseSphere = function (parsedSphere, scene) {
  19175. if (parseGeometry(parsedSphere, scene)) {
  19176. return null; // null since geometry could be something else than a sphere...
  19177. }
  19178. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19179. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19180. scene.pushGeometry(sphere, true);
  19181. return sphere;
  19182. };
  19183. var parseCylinder = function (parsedCylinder, scene) {
  19184. if (parseGeometry(parsedCylinder, scene)) {
  19185. return null; // null since geometry could be something else than a cylinder...
  19186. }
  19187. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19188. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19189. scene.pushGeometry(cylinder, true);
  19190. return cylinder;
  19191. };
  19192. var parseTorus = function (parsedTorus, scene) {
  19193. if (parseGeometry(parsedTorus, scene)) {
  19194. return null; // null since geometry could be something else than a torus...
  19195. }
  19196. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19197. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19198. scene.pushGeometry(torus, true);
  19199. return torus;
  19200. };
  19201. var parseGround = function (parsedGround, scene) {
  19202. if (parseGeometry(parsedGround, scene)) {
  19203. return null; // null since geometry could be something else than a ground...
  19204. }
  19205. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19206. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19207. scene.pushGeometry(ground, true);
  19208. return ground;
  19209. };
  19210. var parsePlane = function (parsedPlane, scene) {
  19211. if (parseGeometry(parsedPlane, scene)) {
  19212. return null; // null since geometry could be something else than a plane...
  19213. }
  19214. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19216. scene.pushGeometry(plane, true);
  19217. return plane;
  19218. };
  19219. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19220. if (parseGeometry(parsedTorusKnot, scene)) {
  19221. return null; // null since geometry could be something else than a torusKnot...
  19222. }
  19223. 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);
  19224. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19225. scene.pushGeometry(torusKnot, true);
  19226. return torusKnot;
  19227. };
  19228. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19229. if (parseGeometry(parsedVertexData, scene)) {
  19230. return null; // null since geometry could be a primitive
  19231. }
  19232. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19233. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19234. if (parsedVertexData.delayLoadingFile) {
  19235. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19236. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19237. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19238. geometry._delayInfo = [];
  19239. if (parsedVertexData.hasUVs) {
  19240. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19241. }
  19242. if (parsedVertexData.hasUVs2) {
  19243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19244. }
  19245. if (parsedVertexData.hasColors) {
  19246. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19247. }
  19248. if (parsedVertexData.hasMatricesIndices) {
  19249. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19250. }
  19251. if (parsedVertexData.hasMatricesWeights) {
  19252. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19253. }
  19254. geometry._delayLoadingFunction = importVertexData;
  19255. }
  19256. else {
  19257. importVertexData(parsedVertexData, geometry);
  19258. }
  19259. scene.pushGeometry(geometry, true);
  19260. return geometry;
  19261. };
  19262. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19263. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19264. mesh.id = parsedMesh.id;
  19265. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19266. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19267. if (parsedMesh.rotationQuaternion) {
  19268. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19269. }
  19270. else if (parsedMesh.rotation) {
  19271. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19272. }
  19273. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19274. if (parsedMesh.localMatrix) {
  19275. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19276. }
  19277. else if (parsedMesh.pivotMatrix) {
  19278. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19279. }
  19280. mesh.setEnabled(parsedMesh.isEnabled);
  19281. mesh.isVisible = parsedMesh.isVisible;
  19282. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19283. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19284. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19285. if (parsedMesh.applyFog !== undefined) {
  19286. mesh.applyFog = parsedMesh.applyFog;
  19287. }
  19288. if (parsedMesh.pickable !== undefined) {
  19289. mesh.isPickable = parsedMesh.pickable;
  19290. }
  19291. if (parsedMesh.alphaIndex !== undefined) {
  19292. mesh.alphaIndex = parsedMesh.alphaIndex;
  19293. }
  19294. mesh.receiveShadows = parsedMesh.receiveShadows;
  19295. mesh.billboardMode = parsedMesh.billboardMode;
  19296. if (parsedMesh.visibility !== undefined) {
  19297. mesh.visibility = parsedMesh.visibility;
  19298. }
  19299. mesh.checkCollisions = parsedMesh.checkCollisions;
  19300. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19301. // Parent
  19302. if (parsedMesh.parentId) {
  19303. mesh._waitingParentId = parsedMesh.parentId;
  19304. }
  19305. // Actions
  19306. if (parsedMesh.actions !== undefined) {
  19307. mesh._waitingActions = parsedMesh.actions;
  19308. }
  19309. // Geometry
  19310. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19311. if (parsedMesh.delayLoadingFile) {
  19312. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19313. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19314. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19315. if (parsedMesh._binaryInfo) {
  19316. mesh._binaryInfo = parsedMesh._binaryInfo;
  19317. }
  19318. mesh._delayInfo = [];
  19319. if (parsedMesh.hasUVs) {
  19320. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19321. }
  19322. if (parsedMesh.hasUVs2) {
  19323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19324. }
  19325. if (parsedMesh.hasColors) {
  19326. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19327. }
  19328. if (parsedMesh.hasMatricesIndices) {
  19329. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19330. }
  19331. if (parsedMesh.hasMatricesWeights) {
  19332. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19333. }
  19334. mesh._delayLoadingFunction = importGeometry;
  19335. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19336. mesh._checkDelayState();
  19337. }
  19338. }
  19339. else {
  19340. importGeometry(parsedMesh, mesh);
  19341. }
  19342. // Material
  19343. if (parsedMesh.materialId) {
  19344. mesh.setMaterialByID(parsedMesh.materialId);
  19345. }
  19346. else {
  19347. mesh.material = null;
  19348. }
  19349. // Skeleton
  19350. if (parsedMesh.skeletonId > -1) {
  19351. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19352. }
  19353. // Physics
  19354. if (parsedMesh.physicsImpostor) {
  19355. if (!scene.isPhysicsEnabled()) {
  19356. scene.enablePhysics();
  19357. }
  19358. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19359. }
  19360. // Animations
  19361. if (parsedMesh.animations) {
  19362. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19363. var parsedAnimation = parsedMesh.animations[animationIndex];
  19364. mesh.animations.push(parseAnimation(parsedAnimation));
  19365. }
  19366. }
  19367. if (parsedMesh.autoAnimate) {
  19368. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19369. }
  19370. // Layer Mask
  19371. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19372. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19373. }
  19374. else {
  19375. mesh.layerMask = 0xFFFFFFFF;
  19376. }
  19377. // Instances
  19378. if (parsedMesh.instances) {
  19379. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19380. var parsedInstance = parsedMesh.instances[index];
  19381. var instance = mesh.createInstance(parsedInstance.name);
  19382. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19383. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19384. if (parsedInstance.rotationQuaternion) {
  19385. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19386. }
  19387. else if (parsedInstance.rotation) {
  19388. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19389. }
  19390. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19391. instance.checkCollisions = mesh.checkCollisions;
  19392. if (parsedMesh.animations) {
  19393. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19394. parsedAnimation = parsedMesh.animations[animationIndex];
  19395. instance.animations.push(parseAnimation(parsedAnimation));
  19396. }
  19397. }
  19398. }
  19399. }
  19400. return mesh;
  19401. };
  19402. var parseActions = function (parsedActions, object, scene) {
  19403. var actionManager = new BABYLON.ActionManager(scene);
  19404. if (object === null)
  19405. scene.actionManager = actionManager;
  19406. else
  19407. object.actionManager = actionManager;
  19408. // instanciate a new object
  19409. var instanciate = function (name, params) {
  19410. var newInstance = Object.create(BABYLON[name].prototype);
  19411. newInstance.constructor.apply(newInstance, params);
  19412. return newInstance;
  19413. };
  19414. var parseParameter = function (name, value, target, propertyPath) {
  19415. if (propertyPath === null) {
  19416. // String, boolean or float
  19417. var floatValue = parseFloat(value);
  19418. if (value === "true" || value === "false")
  19419. return value === "true";
  19420. else
  19421. return isNaN(floatValue) ? value : floatValue;
  19422. }
  19423. var effectiveTarget = propertyPath.split(".");
  19424. var values = value.split(",");
  19425. // Get effective Target
  19426. for (var i = 0; i < effectiveTarget.length; i++) {
  19427. target = target[effectiveTarget[i]];
  19428. }
  19429. // Return appropriate value with its type
  19430. if (typeof (target) === "boolean")
  19431. return values[0] === "true";
  19432. if (typeof (target) === "string")
  19433. return values[0];
  19434. // Parameters with multiple values such as Vector3 etc.
  19435. var split = new Array();
  19436. for (var i = 0; i < values.length; i++)
  19437. split.push(parseFloat(values[i]));
  19438. if (target instanceof BABYLON.Vector3)
  19439. return BABYLON.Vector3.FromArray(split);
  19440. if (target instanceof BABYLON.Vector4)
  19441. return BABYLON.Vector4.FromArray(split);
  19442. if (target instanceof BABYLON.Color3)
  19443. return BABYLON.Color3.FromArray(split);
  19444. if (target instanceof BABYLON.Color4)
  19445. return BABYLON.Color4.FromArray(split);
  19446. return parseFloat(values[0]);
  19447. };
  19448. // traverse graph per trigger
  19449. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19450. if (combineArray === void 0) { combineArray = null; }
  19451. if (parsedAction.detached)
  19452. return;
  19453. var parameters = new Array();
  19454. var target = null;
  19455. var propertyPath = null;
  19456. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19457. // Parameters
  19458. if (parsedAction.type === 2)
  19459. parameters.push(actionManager);
  19460. else
  19461. parameters.push(trigger);
  19462. if (combine) {
  19463. var actions = new Array();
  19464. for (var j = 0; j < parsedAction.combine.length; j++) {
  19465. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19466. }
  19467. parameters.push(actions);
  19468. }
  19469. else {
  19470. for (var i = 0; i < parsedAction.properties.length; i++) {
  19471. var value = parsedAction.properties[i].value;
  19472. var name = parsedAction.properties[i].name;
  19473. var targetType = parsedAction.properties[i].targetType;
  19474. if (name === "target")
  19475. if (targetType !== null && targetType === "SceneProperties")
  19476. value = target = scene;
  19477. else
  19478. value = target = scene.getNodeByName(value);
  19479. else if (name === "parent")
  19480. value = scene.getNodeByName(value);
  19481. else if (name === "sound")
  19482. value = scene.getSoundByName(value);
  19483. else if (name !== "propertyPath") {
  19484. if (parsedAction.type === 2 && name === "operator")
  19485. value = BABYLON.ValueCondition[value];
  19486. else
  19487. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19488. }
  19489. else {
  19490. propertyPath = value;
  19491. }
  19492. parameters.push(value);
  19493. }
  19494. }
  19495. if (combineArray === null) {
  19496. parameters.push(condition);
  19497. }
  19498. else {
  19499. parameters.push(null);
  19500. }
  19501. // If interpolate value action
  19502. if (parsedAction.name === "InterpolateValueAction") {
  19503. var param = parameters[parameters.length - 2];
  19504. parameters[parameters.length - 1] = param;
  19505. parameters[parameters.length - 2] = condition;
  19506. }
  19507. // Action or condition(s) and not CombineAction
  19508. var newAction = instanciate(parsedAction.name, parameters);
  19509. if (combineArray === null) {
  19510. if (newAction instanceof BABYLON.Condition) {
  19511. condition = newAction;
  19512. newAction = action;
  19513. }
  19514. else {
  19515. condition = null;
  19516. if (action)
  19517. action.then(newAction);
  19518. else
  19519. actionManager.registerAction(newAction);
  19520. }
  19521. }
  19522. else {
  19523. combineArray.push(newAction);
  19524. }
  19525. for (var i = 0; i < parsedAction.children.length; i++)
  19526. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19527. };
  19528. // triggers
  19529. for (var i = 0; i < parsedActions.children.length; i++) {
  19530. var triggerParams;
  19531. var trigger = parsedActions.children[i];
  19532. if (trigger.properties.length > 0) {
  19533. var param = trigger.properties[0].value;
  19534. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19535. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19536. }
  19537. else
  19538. triggerParams = BABYLON.ActionManager[trigger.name];
  19539. for (var j = 0; j < trigger.children.length; j++) {
  19540. if (!trigger.detached)
  19541. traverse(trigger.children[j], triggerParams, null, null);
  19542. }
  19543. }
  19544. };
  19545. var parseSound = function (parsedSound, scene, rootUrl) {
  19546. var soundName = parsedSound.name;
  19547. var soundUrl = rootUrl + soundName;
  19548. var options = {
  19549. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19550. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19551. rolloffFactor: parsedSound.rolloffFactor,
  19552. refDistance: parsedSound.refDistance,
  19553. distanceModel: parsedSound.distanceModel,
  19554. playbackRate: parsedSound.playbackRate
  19555. };
  19556. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19557. scene._addPendingData(newSound);
  19558. if (parsedSound.position) {
  19559. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19560. newSound.setPosition(soundPosition);
  19561. }
  19562. if (parsedSound.isDirectional) {
  19563. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19564. if (parsedSound.localDirectionToMesh) {
  19565. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19566. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19567. }
  19568. }
  19569. if (parsedSound.connectedMeshId) {
  19570. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19571. if (connectedMesh) {
  19572. newSound.attachToMesh(connectedMesh);
  19573. }
  19574. }
  19575. };
  19576. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19577. names = (names instanceof Array) ? names : [names];
  19578. for (var i in names) {
  19579. if (mesh.name === names[i]) {
  19580. hierarchyIds.push(mesh.id);
  19581. return true;
  19582. }
  19583. }
  19584. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19585. hierarchyIds.push(mesh.id);
  19586. return true;
  19587. }
  19588. return false;
  19589. };
  19590. var importVertexData = function (parsedVertexData, geometry) {
  19591. var vertexData = new BABYLON.VertexData();
  19592. // positions
  19593. var positions = parsedVertexData.positions;
  19594. if (positions) {
  19595. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19596. }
  19597. // normals
  19598. var normals = parsedVertexData.normals;
  19599. if (normals) {
  19600. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19601. }
  19602. // uvs
  19603. var uvs = parsedVertexData.uvs;
  19604. if (uvs) {
  19605. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19606. }
  19607. // uv2s
  19608. var uv2s = parsedVertexData.uv2s;
  19609. if (uv2s) {
  19610. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19611. }
  19612. // colors
  19613. var colors = parsedVertexData.colors;
  19614. if (colors) {
  19615. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19616. }
  19617. // matricesIndices
  19618. var matricesIndices = parsedVertexData.matricesIndices;
  19619. if (matricesIndices) {
  19620. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19621. }
  19622. // matricesWeights
  19623. var matricesWeights = parsedVertexData.matricesWeights;
  19624. if (matricesWeights) {
  19625. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19626. }
  19627. // indices
  19628. var indices = parsedVertexData.indices;
  19629. if (indices) {
  19630. vertexData.indices = indices;
  19631. }
  19632. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19633. };
  19634. var importGeometry = function (parsedGeometry, mesh) {
  19635. var scene = mesh.getScene();
  19636. // Geometry
  19637. var geometryId = parsedGeometry.geometryId;
  19638. if (geometryId) {
  19639. var geometry = scene.getGeometryByID(geometryId);
  19640. if (geometry) {
  19641. geometry.applyToMesh(mesh);
  19642. }
  19643. }
  19644. else if (parsedGeometry instanceof ArrayBuffer) {
  19645. var binaryInfo = mesh._binaryInfo;
  19646. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19647. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19648. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19649. }
  19650. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19651. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19652. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19653. }
  19654. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19655. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19657. }
  19658. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19659. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19660. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19661. }
  19662. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19663. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19664. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19665. }
  19666. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19667. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19669. }
  19670. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19671. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19672. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19673. }
  19674. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19675. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19676. mesh.setIndices(indicesData);
  19677. }
  19678. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19679. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19680. mesh.subMeshes = [];
  19681. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19682. var materialIndex = subMeshesData[(i * 5) + 0];
  19683. var verticesStart = subMeshesData[(i * 5) + 1];
  19684. var verticesCount = subMeshesData[(i * 5) + 2];
  19685. var indexStart = subMeshesData[(i * 5) + 3];
  19686. var indexCount = subMeshesData[(i * 5) + 4];
  19687. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19688. }
  19689. }
  19690. }
  19691. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19692. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19693. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19694. if (parsedGeometry.uvs) {
  19695. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19696. }
  19697. if (parsedGeometry.uvs2) {
  19698. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19699. }
  19700. if (parsedGeometry.colors) {
  19701. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19702. }
  19703. if (parsedGeometry.matricesIndices) {
  19704. if (!parsedGeometry.matricesIndices._isExpanded) {
  19705. var floatIndices = [];
  19706. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19707. var matricesIndex = parsedGeometry.matricesIndices[i];
  19708. floatIndices.push(matricesIndex & 0x000000FF);
  19709. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19710. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19711. floatIndices.push(matricesIndex >> 24);
  19712. }
  19713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19714. }
  19715. else {
  19716. delete parsedGeometry.matricesIndices._isExpanded;
  19717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19718. }
  19719. }
  19720. if (parsedGeometry.matricesWeights) {
  19721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19722. }
  19723. mesh.setIndices(parsedGeometry.indices);
  19724. // SubMeshes
  19725. if (parsedGeometry.subMeshes) {
  19726. mesh.subMeshes = [];
  19727. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19728. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19729. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19730. }
  19731. }
  19732. }
  19733. // Flat shading
  19734. if (mesh._shouldGenerateFlatShading) {
  19735. mesh.convertToFlatShadedMesh();
  19736. delete mesh._shouldGenerateFlatShading;
  19737. }
  19738. // Update
  19739. mesh.computeWorldMatrix(true);
  19740. // Octree
  19741. if (scene._selectionOctree) {
  19742. scene._selectionOctree.addMesh(mesh);
  19743. }
  19744. };
  19745. BABYLON.SceneLoader.RegisterPlugin({
  19746. extensions: ".babylon",
  19747. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19748. var parsedData = JSON.parse(data);
  19749. var loadedSkeletonsIds = [];
  19750. var loadedMaterialsIds = [];
  19751. var hierarchyIds = [];
  19752. for (var index = 0; index < parsedData.meshes.length; index++) {
  19753. var parsedMesh = parsedData.meshes[index];
  19754. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19755. if (meshesNames instanceof Array) {
  19756. // Remove found mesh name from list.
  19757. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19758. }
  19759. //Geometry?
  19760. if (parsedMesh.geometryId) {
  19761. //does the file contain geometries?
  19762. if (parsedData.geometries) {
  19763. //find the correct geometry and add it to the scene
  19764. var found = false;
  19765. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19766. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19767. return;
  19768. }
  19769. else {
  19770. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19771. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19772. switch (geometryType) {
  19773. case "boxes":
  19774. parseBox(parsedGeometryData, scene);
  19775. break;
  19776. case "spheres":
  19777. parseSphere(parsedGeometryData, scene);
  19778. break;
  19779. case "cylinders":
  19780. parseCylinder(parsedGeometryData, scene);
  19781. break;
  19782. case "toruses":
  19783. parseTorus(parsedGeometryData, scene);
  19784. break;
  19785. case "grounds":
  19786. parseGround(parsedGeometryData, scene);
  19787. break;
  19788. case "planes":
  19789. parsePlane(parsedGeometryData, scene);
  19790. break;
  19791. case "torusKnots":
  19792. parseTorusKnot(parsedGeometryData, scene);
  19793. break;
  19794. case "vertexData":
  19795. parseVertexData(parsedGeometryData, scene, rootUrl);
  19796. break;
  19797. }
  19798. found = true;
  19799. }
  19800. });
  19801. }
  19802. });
  19803. }
  19804. }
  19805. // Material ?
  19806. if (parsedMesh.materialId) {
  19807. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19808. if (!materialFound) {
  19809. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19810. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19811. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19812. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19813. var subMatId = parsedMultiMaterial.materials[matIndex];
  19814. loadedMaterialsIds.push(subMatId);
  19815. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19816. }
  19817. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19818. parseMultiMaterial(parsedMultiMaterial, scene);
  19819. materialFound = true;
  19820. break;
  19821. }
  19822. }
  19823. }
  19824. if (!materialFound) {
  19825. loadedMaterialsIds.push(parsedMesh.materialId);
  19826. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19827. }
  19828. }
  19829. // Skeleton ?
  19830. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19831. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19832. if (!skeletonAlreadyLoaded) {
  19833. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19834. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19835. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19836. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19837. loadedSkeletonsIds.push(parsedSkeleton.id);
  19838. }
  19839. }
  19840. }
  19841. }
  19842. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19843. meshes.push(mesh);
  19844. }
  19845. }
  19846. // Connecting parents
  19847. for (index = 0; index < scene.meshes.length; index++) {
  19848. var currentMesh = scene.meshes[index];
  19849. if (currentMesh._waitingParentId) {
  19850. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19851. currentMesh._waitingParentId = undefined;
  19852. }
  19853. }
  19854. // Particles
  19855. if (parsedData.particleSystems) {
  19856. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19857. var parsedParticleSystem = parsedData.particleSystems[index];
  19858. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19859. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19860. }
  19861. }
  19862. }
  19863. return true;
  19864. },
  19865. load: function (scene, data, rootUrl) {
  19866. var parsedData = JSON.parse(data);
  19867. // Scene
  19868. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19869. scene.autoClear = parsedData.autoClear;
  19870. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19871. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19872. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19873. // Fog
  19874. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19875. scene.fogMode = parsedData.fogMode;
  19876. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19877. scene.fogStart = parsedData.fogStart;
  19878. scene.fogEnd = parsedData.fogEnd;
  19879. scene.fogDensity = parsedData.fogDensity;
  19880. }
  19881. // Lights
  19882. for (var index = 0; index < parsedData.lights.length; index++) {
  19883. var parsedLight = parsedData.lights[index];
  19884. parseLight(parsedLight, scene);
  19885. }
  19886. // Materials
  19887. if (parsedData.materials) {
  19888. for (index = 0; index < parsedData.materials.length; index++) {
  19889. var parsedMaterial = parsedData.materials[index];
  19890. parseMaterial(parsedMaterial, scene, rootUrl);
  19891. }
  19892. }
  19893. if (parsedData.multiMaterials) {
  19894. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19895. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19896. parseMultiMaterial(parsedMultiMaterial, scene);
  19897. }
  19898. }
  19899. // Skeletons
  19900. if (parsedData.skeletons) {
  19901. for (index = 0; index < parsedData.skeletons.length; index++) {
  19902. var parsedSkeleton = parsedData.skeletons[index];
  19903. parseSkeleton(parsedSkeleton, scene);
  19904. }
  19905. }
  19906. // Geometries
  19907. var geometries = parsedData.geometries;
  19908. if (geometries) {
  19909. // Boxes
  19910. var boxes = geometries.boxes;
  19911. if (boxes) {
  19912. for (index = 0; index < boxes.length; index++) {
  19913. var parsedBox = boxes[index];
  19914. parseBox(parsedBox, scene);
  19915. }
  19916. }
  19917. // Spheres
  19918. var spheres = geometries.spheres;
  19919. if (spheres) {
  19920. for (index = 0; index < spheres.length; index++) {
  19921. var parsedSphere = spheres[index];
  19922. parseSphere(parsedSphere, scene);
  19923. }
  19924. }
  19925. // Cylinders
  19926. var cylinders = geometries.cylinders;
  19927. if (cylinders) {
  19928. for (index = 0; index < cylinders.length; index++) {
  19929. var parsedCylinder = cylinders[index];
  19930. parseCylinder(parsedCylinder, scene);
  19931. }
  19932. }
  19933. // Toruses
  19934. var toruses = geometries.toruses;
  19935. if (toruses) {
  19936. for (index = 0; index < toruses.length; index++) {
  19937. var parsedTorus = toruses[index];
  19938. parseTorus(parsedTorus, scene);
  19939. }
  19940. }
  19941. // Grounds
  19942. var grounds = geometries.grounds;
  19943. if (grounds) {
  19944. for (index = 0; index < grounds.length; index++) {
  19945. var parsedGround = grounds[index];
  19946. parseGround(parsedGround, scene);
  19947. }
  19948. }
  19949. // Planes
  19950. var planes = geometries.planes;
  19951. if (planes) {
  19952. for (index = 0; index < planes.length; index++) {
  19953. var parsedPlane = planes[index];
  19954. parsePlane(parsedPlane, scene);
  19955. }
  19956. }
  19957. // TorusKnots
  19958. var torusKnots = geometries.torusKnots;
  19959. if (torusKnots) {
  19960. for (index = 0; index < torusKnots.length; index++) {
  19961. var parsedTorusKnot = torusKnots[index];
  19962. parseTorusKnot(parsedTorusKnot, scene);
  19963. }
  19964. }
  19965. // VertexData
  19966. var vertexData = geometries.vertexData;
  19967. if (vertexData) {
  19968. for (index = 0; index < vertexData.length; index++) {
  19969. var parsedVertexData = vertexData[index];
  19970. parseVertexData(parsedVertexData, scene, rootUrl);
  19971. }
  19972. }
  19973. }
  19974. // Meshes
  19975. for (index = 0; index < parsedData.meshes.length; index++) {
  19976. var parsedMesh = parsedData.meshes[index];
  19977. parseMesh(parsedMesh, scene, rootUrl);
  19978. }
  19979. // Cameras
  19980. for (index = 0; index < parsedData.cameras.length; index++) {
  19981. var parsedCamera = parsedData.cameras[index];
  19982. parseCamera(parsedCamera, scene);
  19983. }
  19984. if (parsedData.activeCameraID) {
  19985. scene.setActiveCameraByID(parsedData.activeCameraID);
  19986. }
  19987. // Browsing all the graph to connect the dots
  19988. for (index = 0; index < scene.cameras.length; index++) {
  19989. var camera = scene.cameras[index];
  19990. if (camera._waitingParentId) {
  19991. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19992. camera._waitingParentId = undefined;
  19993. }
  19994. }
  19995. for (index = 0; index < scene.lights.length; index++) {
  19996. var light = scene.lights[index];
  19997. if (light._waitingParentId) {
  19998. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19999. light._waitingParentId = undefined;
  20000. }
  20001. }
  20002. // Sounds
  20003. if (parsedData.sounds) {
  20004. for (index = 0; index < parsedData.sounds.length; index++) {
  20005. var parsedSound = parsedData.sounds[index];
  20006. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20007. parseSound(parsedSound, scene, rootUrl);
  20008. }
  20009. else {
  20010. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20011. }
  20012. }
  20013. }
  20014. // Connect parents & children and parse actions
  20015. for (index = 0; index < scene.meshes.length; index++) {
  20016. var mesh = scene.meshes[index];
  20017. if (mesh._waitingParentId) {
  20018. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20019. mesh._waitingParentId = undefined;
  20020. }
  20021. if (mesh._waitingActions) {
  20022. parseActions(mesh._waitingActions, mesh, scene);
  20023. mesh._waitingActions = undefined;
  20024. }
  20025. }
  20026. // Particles Systems
  20027. if (parsedData.particleSystems) {
  20028. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20029. var parsedParticleSystem = parsedData.particleSystems[index];
  20030. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20031. }
  20032. }
  20033. // Lens flares
  20034. if (parsedData.lensFlareSystems) {
  20035. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20036. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20037. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20038. }
  20039. }
  20040. // Shadows
  20041. if (parsedData.shadowGenerators) {
  20042. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20043. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20044. parseShadowGenerator(parsedShadowGenerator, scene);
  20045. }
  20046. }
  20047. // Actions (scene)
  20048. if (parsedData.actions) {
  20049. parseActions(parsedData.actions, null, scene);
  20050. }
  20051. // Finish
  20052. return true;
  20053. }
  20054. });
  20055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20056. })(BABYLON || (BABYLON = {}));
  20057. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20058. var BABYLON;
  20059. (function (BABYLON) {
  20060. var SpriteManager = (function () {
  20061. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20063. this.name = name;
  20064. this.cellSize = cellSize;
  20065. this.sprites = new Array();
  20066. this.renderingGroupId = 0;
  20067. this.fogEnabled = true;
  20068. this._vertexDeclaration = [4, 4, 4, 4];
  20069. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20070. this._capacity = capacity;
  20071. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20072. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20073. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20074. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20075. this._scene = scene;
  20076. this._scene.spriteManagers.push(this);
  20077. // VBO
  20078. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20079. var indices = [];
  20080. var index = 0;
  20081. for (var count = 0; count < capacity; count++) {
  20082. indices.push(index);
  20083. indices.push(index + 1);
  20084. indices.push(index + 2);
  20085. indices.push(index);
  20086. indices.push(index + 2);
  20087. indices.push(index + 3);
  20088. index += 4;
  20089. }
  20090. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20091. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20092. // Effects
  20093. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20094. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20095. }
  20096. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20097. var arrayOffset = index * 16;
  20098. if (offsetX === 0)
  20099. offsetX = this._epsilon;
  20100. else if (offsetX === 1)
  20101. offsetX = 1 - this._epsilon;
  20102. if (offsetY === 0)
  20103. offsetY = this._epsilon;
  20104. else if (offsetY === 1)
  20105. offsetY = 1 - this._epsilon;
  20106. this._vertices[arrayOffset] = sprite.position.x;
  20107. this._vertices[arrayOffset + 1] = sprite.position.y;
  20108. this._vertices[arrayOffset + 2] = sprite.position.z;
  20109. this._vertices[arrayOffset + 3] = sprite.angle;
  20110. this._vertices[arrayOffset + 4] = sprite.width;
  20111. this._vertices[arrayOffset + 5] = sprite.height;
  20112. this._vertices[arrayOffset + 6] = offsetX;
  20113. this._vertices[arrayOffset + 7] = offsetY;
  20114. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20115. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20116. var offset = (sprite.cellIndex / rowSize) >> 0;
  20117. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20118. this._vertices[arrayOffset + 11] = offset;
  20119. // Color
  20120. this._vertices[arrayOffset + 12] = sprite.color.r;
  20121. this._vertices[arrayOffset + 13] = sprite.color.g;
  20122. this._vertices[arrayOffset + 14] = sprite.color.b;
  20123. this._vertices[arrayOffset + 15] = sprite.color.a;
  20124. };
  20125. SpriteManager.prototype.render = function () {
  20126. // Check
  20127. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20128. return;
  20129. var engine = this._scene.getEngine();
  20130. var baseSize = this._spriteTexture.getBaseSize();
  20131. // Sprites
  20132. var deltaTime = engine.getDeltaTime();
  20133. var max = Math.min(this._capacity, this.sprites.length);
  20134. var rowSize = baseSize.width / this.cellSize;
  20135. var offset = 0;
  20136. for (var index = 0; index < max; index++) {
  20137. var sprite = this.sprites[index];
  20138. if (!sprite) {
  20139. continue;
  20140. }
  20141. sprite._animate(deltaTime);
  20142. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20143. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20144. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20145. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20146. }
  20147. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20148. // Render
  20149. var effect = this._effectBase;
  20150. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20151. effect = this._effectFog;
  20152. }
  20153. engine.enableEffect(effect);
  20154. var viewMatrix = this._scene.getViewMatrix();
  20155. effect.setTexture("diffuseSampler", this._spriteTexture);
  20156. effect.setMatrix("view", viewMatrix);
  20157. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20158. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20159. // Fog
  20160. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20161. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20162. effect.setColor3("vFogColor", this._scene.fogColor);
  20163. }
  20164. // VBOs
  20165. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20166. // Draw order
  20167. engine.setDepthFunctionToLessOrEqual();
  20168. effect.setBool("alphaTest", true);
  20169. engine.setColorWrite(false);
  20170. engine.draw(true, 0, max * 6);
  20171. engine.setColorWrite(true);
  20172. effect.setBool("alphaTest", false);
  20173. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20174. engine.draw(true, 0, max * 6);
  20175. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20176. };
  20177. SpriteManager.prototype.dispose = function () {
  20178. if (this._vertexBuffer) {
  20179. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20180. this._vertexBuffer = null;
  20181. }
  20182. if (this._indexBuffer) {
  20183. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20184. this._indexBuffer = null;
  20185. }
  20186. if (this._spriteTexture) {
  20187. this._spriteTexture.dispose();
  20188. this._spriteTexture = null;
  20189. }
  20190. // Remove from scene
  20191. var index = this._scene.spriteManagers.indexOf(this);
  20192. this._scene.spriteManagers.splice(index, 1);
  20193. // Callback
  20194. if (this.onDispose) {
  20195. this.onDispose();
  20196. }
  20197. };
  20198. return SpriteManager;
  20199. })();
  20200. BABYLON.SpriteManager = SpriteManager;
  20201. })(BABYLON || (BABYLON = {}));
  20202. //# sourceMappingURL=babylon.spriteManager.js.map
  20203. var BABYLON;
  20204. (function (BABYLON) {
  20205. var Sprite = (function () {
  20206. function Sprite(name, manager) {
  20207. this.name = name;
  20208. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20209. this.width = 1.0;
  20210. this.height = 1.0;
  20211. this.angle = 0;
  20212. this.cellIndex = 0;
  20213. this.invertU = 0;
  20214. this.invertV = 0;
  20215. this.animations = new Array();
  20216. this._animationStarted = false;
  20217. this._loopAnimation = false;
  20218. this._fromIndex = 0;
  20219. this._toIndex = 0;
  20220. this._delay = 0;
  20221. this._direction = 1;
  20222. this._frameCount = 0;
  20223. this._time = 0;
  20224. this._manager = manager;
  20225. this._manager.sprites.push(this);
  20226. this.position = BABYLON.Vector3.Zero();
  20227. }
  20228. Object.defineProperty(Sprite.prototype, "size", {
  20229. get: function () {
  20230. return this.width;
  20231. },
  20232. set: function (value) {
  20233. this.width = value;
  20234. this.height = value;
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20240. this._fromIndex = from;
  20241. this._toIndex = to;
  20242. this._loopAnimation = loop;
  20243. this._delay = delay;
  20244. this._animationStarted = true;
  20245. this._direction = from < to ? 1 : -1;
  20246. this.cellIndex = from;
  20247. this._time = 0;
  20248. };
  20249. Sprite.prototype.stopAnimation = function () {
  20250. this._animationStarted = false;
  20251. };
  20252. Sprite.prototype._animate = function (deltaTime) {
  20253. if (!this._animationStarted)
  20254. return;
  20255. this._time += deltaTime;
  20256. if (this._time > this._delay) {
  20257. this._time = this._time % this._delay;
  20258. this.cellIndex += this._direction;
  20259. if (this.cellIndex == this._toIndex) {
  20260. if (this._loopAnimation) {
  20261. this.cellIndex = this._fromIndex;
  20262. }
  20263. else {
  20264. this._animationStarted = false;
  20265. if (this.disposeWhenFinishedAnimating) {
  20266. this.dispose();
  20267. }
  20268. }
  20269. }
  20270. }
  20271. };
  20272. Sprite.prototype.dispose = function () {
  20273. for (var i = 0; i < this._manager.sprites.length; i++) {
  20274. if (this._manager.sprites[i] == this) {
  20275. this._manager.sprites.splice(i, 1);
  20276. }
  20277. }
  20278. };
  20279. return Sprite;
  20280. })();
  20281. BABYLON.Sprite = Sprite;
  20282. })(BABYLON || (BABYLON = {}));
  20283. //# sourceMappingURL=babylon.sprite.js.map
  20284. var BABYLON;
  20285. (function (BABYLON) {
  20286. var Layer = (function () {
  20287. function Layer(name, imgUrl, scene, isBackground, color) {
  20288. this.name = name;
  20289. this._vertexDeclaration = [2];
  20290. this._vertexStrideSize = 2 * 4;
  20291. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20292. this.isBackground = isBackground === undefined ? true : isBackground;
  20293. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20294. this._scene = scene;
  20295. this._scene.layers.push(this);
  20296. // VBO
  20297. var vertices = [];
  20298. vertices.push(1, 1);
  20299. vertices.push(-1, 1);
  20300. vertices.push(-1, -1);
  20301. vertices.push(1, -1);
  20302. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20303. // Indices
  20304. var indices = [];
  20305. indices.push(0);
  20306. indices.push(1);
  20307. indices.push(2);
  20308. indices.push(0);
  20309. indices.push(2);
  20310. indices.push(3);
  20311. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20312. // Effects
  20313. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20314. }
  20315. Layer.prototype.render = function () {
  20316. // Check
  20317. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20318. return;
  20319. var engine = this._scene.getEngine();
  20320. // Render
  20321. engine.enableEffect(this._effect);
  20322. engine.setState(false);
  20323. // Texture
  20324. this._effect.setTexture("textureSampler", this.texture);
  20325. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20326. // Color
  20327. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20328. // VBOs
  20329. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20330. // Draw order
  20331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20332. engine.draw(true, 0, 6);
  20333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20334. };
  20335. Layer.prototype.dispose = function () {
  20336. if (this._vertexBuffer) {
  20337. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20338. this._vertexBuffer = null;
  20339. }
  20340. if (this._indexBuffer) {
  20341. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20342. this._indexBuffer = null;
  20343. }
  20344. if (this.texture) {
  20345. this.texture.dispose();
  20346. this.texture = null;
  20347. }
  20348. // Remove from scene
  20349. var index = this._scene.layers.indexOf(this);
  20350. this._scene.layers.splice(index, 1);
  20351. // Callback
  20352. if (this.onDispose) {
  20353. this.onDispose();
  20354. }
  20355. };
  20356. return Layer;
  20357. })();
  20358. BABYLON.Layer = Layer;
  20359. })(BABYLON || (BABYLON = {}));
  20360. //# sourceMappingURL=babylon.layer.js.map
  20361. var BABYLON;
  20362. (function (BABYLON) {
  20363. var Particle = (function () {
  20364. function Particle() {
  20365. this.position = BABYLON.Vector3.Zero();
  20366. this.direction = BABYLON.Vector3.Zero();
  20367. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20368. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20369. this.lifeTime = 1.0;
  20370. this.age = 0;
  20371. this.size = 0;
  20372. this.angle = 0;
  20373. this.angularSpeed = 0;
  20374. }
  20375. Particle.prototype.copyTo = function (other) {
  20376. other.position.copyFrom(this.position);
  20377. other.direction.copyFrom(this.direction);
  20378. other.color.copyFrom(this.color);
  20379. other.colorStep.copyFrom(this.colorStep);
  20380. other.lifeTime = this.lifeTime;
  20381. other.age = this.age;
  20382. other.size = this.size;
  20383. other.angle = this.angle;
  20384. other.angularSpeed = this.angularSpeed;
  20385. };
  20386. return Particle;
  20387. })();
  20388. BABYLON.Particle = Particle;
  20389. })(BABYLON || (BABYLON = {}));
  20390. //# sourceMappingURL=babylon.particle.js.map
  20391. var BABYLON;
  20392. (function (BABYLON) {
  20393. var randomNumber = function (min, max) {
  20394. if (min === max) {
  20395. return (min);
  20396. }
  20397. var random = Math.random();
  20398. return ((random * (max - min)) + min);
  20399. };
  20400. var ParticleSystem = (function () {
  20401. function ParticleSystem(name, capacity, scene, customEffect) {
  20402. var _this = this;
  20403. this.name = name;
  20404. this.renderingGroupId = 0;
  20405. this.emitter = null;
  20406. this.emitRate = 10;
  20407. this.manualEmitCount = -1;
  20408. this.updateSpeed = 0.01;
  20409. this.targetStopDuration = 0;
  20410. this.disposeOnStop = false;
  20411. this.minEmitPower = 1;
  20412. this.maxEmitPower = 1;
  20413. this.minLifeTime = 1;
  20414. this.maxLifeTime = 1;
  20415. this.minSize = 1;
  20416. this.maxSize = 1;
  20417. this.minAngularSpeed = 0;
  20418. this.maxAngularSpeed = 0;
  20419. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20420. this.forceDepthWrite = false;
  20421. this.gravity = BABYLON.Vector3.Zero();
  20422. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20423. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20424. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20425. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20426. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20427. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20428. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20429. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20430. this.particles = new Array();
  20431. this._vertexDeclaration = [3, 4, 4];
  20432. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20433. this._stockParticles = new Array();
  20434. this._newPartsExcess = 0;
  20435. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20436. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20437. this._scaledDirection = BABYLON.Vector3.Zero();
  20438. this._scaledGravity = BABYLON.Vector3.Zero();
  20439. this._currentRenderId = -1;
  20440. this._started = false;
  20441. this._stopped = false;
  20442. this._actualFrame = 0;
  20443. this.id = name;
  20444. this._capacity = capacity;
  20445. this._scene = scene;
  20446. this._customEffect = customEffect;
  20447. scene.particleSystems.push(this);
  20448. // VBO
  20449. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20450. var indices = [];
  20451. var index = 0;
  20452. for (var count = 0; count < capacity; count++) {
  20453. indices.push(index);
  20454. indices.push(index + 1);
  20455. indices.push(index + 2);
  20456. indices.push(index);
  20457. indices.push(index + 2);
  20458. indices.push(index + 3);
  20459. index += 4;
  20460. }
  20461. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20462. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20463. // Default behaviors
  20464. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20465. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20466. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20467. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20468. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20469. };
  20470. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20471. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20472. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20473. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20474. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20475. };
  20476. this.updateFunction = function (particles) {
  20477. for (var index = 0; index < particles.length; index++) {
  20478. var particle = particles[index];
  20479. particle.age += _this._scaledUpdateSpeed;
  20480. if (particle.age >= particle.lifeTime) {
  20481. _this.recycleParticle(particle);
  20482. index--;
  20483. continue;
  20484. }
  20485. else {
  20486. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20487. particle.color.addInPlace(_this._scaledColorStep);
  20488. if (particle.color.a < 0)
  20489. particle.color.a = 0;
  20490. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20491. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20492. particle.position.addInPlace(_this._scaledDirection);
  20493. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20494. particle.direction.addInPlace(_this._scaledGravity);
  20495. }
  20496. }
  20497. };
  20498. }
  20499. ParticleSystem.prototype.recycleParticle = function (particle) {
  20500. var lastParticle = this.particles.pop();
  20501. if (lastParticle !== particle) {
  20502. lastParticle.copyTo(particle);
  20503. this._stockParticles.push(lastParticle);
  20504. }
  20505. };
  20506. ParticleSystem.prototype.getCapacity = function () {
  20507. return this._capacity;
  20508. };
  20509. ParticleSystem.prototype.isAlive = function () {
  20510. return this._alive;
  20511. };
  20512. ParticleSystem.prototype.isStarted = function () {
  20513. return this._started;
  20514. };
  20515. ParticleSystem.prototype.start = function () {
  20516. this._started = true;
  20517. this._stopped = false;
  20518. this._actualFrame = 0;
  20519. };
  20520. ParticleSystem.prototype.stop = function () {
  20521. this._stopped = true;
  20522. };
  20523. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20524. var offset = index * 11;
  20525. this._vertices[offset] = particle.position.x;
  20526. this._vertices[offset + 1] = particle.position.y;
  20527. this._vertices[offset + 2] = particle.position.z;
  20528. this._vertices[offset + 3] = particle.color.r;
  20529. this._vertices[offset + 4] = particle.color.g;
  20530. this._vertices[offset + 5] = particle.color.b;
  20531. this._vertices[offset + 6] = particle.color.a;
  20532. this._vertices[offset + 7] = particle.angle;
  20533. this._vertices[offset + 8] = particle.size;
  20534. this._vertices[offset + 9] = offsetX;
  20535. this._vertices[offset + 10] = offsetY;
  20536. };
  20537. ParticleSystem.prototype._update = function (newParticles) {
  20538. // Update current
  20539. this._alive = this.particles.length > 0;
  20540. this.updateFunction(this.particles);
  20541. // Add new ones
  20542. var worldMatrix;
  20543. if (this.emitter.position) {
  20544. worldMatrix = this.emitter.getWorldMatrix();
  20545. }
  20546. else {
  20547. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20548. }
  20549. for (var index = 0; index < newParticles; index++) {
  20550. if (this.particles.length === this._capacity) {
  20551. break;
  20552. }
  20553. if (this._stockParticles.length !== 0) {
  20554. var particle = this._stockParticles.pop();
  20555. particle.age = 0;
  20556. }
  20557. else {
  20558. particle = new BABYLON.Particle();
  20559. }
  20560. this.particles.push(particle);
  20561. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20562. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20563. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20564. particle.size = randomNumber(this.minSize, this.maxSize);
  20565. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20566. this.startPositionFunction(worldMatrix, particle.position);
  20567. var step = randomNumber(0, 1.0);
  20568. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20569. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20570. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20571. }
  20572. };
  20573. ParticleSystem.prototype._getEffect = function () {
  20574. if (this._customEffect) {
  20575. return this._customEffect;
  20576. }
  20577. ;
  20578. var defines = [];
  20579. if (this._scene.clipPlane) {
  20580. defines.push("#define CLIPPLANE");
  20581. }
  20582. // Effect
  20583. var join = defines.join("\n");
  20584. if (this._cachedDefines !== join) {
  20585. this._cachedDefines = join;
  20586. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20587. }
  20588. return this._effect;
  20589. };
  20590. ParticleSystem.prototype.animate = function () {
  20591. if (!this._started)
  20592. return;
  20593. var effect = this._getEffect();
  20594. // Check
  20595. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20596. return;
  20597. if (this._currentRenderId === this._scene.getRenderId()) {
  20598. return;
  20599. }
  20600. this._currentRenderId = this._scene.getRenderId();
  20601. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20602. // determine the number of particles we need to create
  20603. var emitCout;
  20604. if (this.manualEmitCount > -1) {
  20605. emitCout = this.manualEmitCount;
  20606. this.manualEmitCount = 0;
  20607. }
  20608. else {
  20609. emitCout = this.emitRate;
  20610. }
  20611. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20612. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20613. if (this._newPartsExcess > 1.0) {
  20614. newParticles += this._newPartsExcess >> 0;
  20615. this._newPartsExcess -= this._newPartsExcess >> 0;
  20616. }
  20617. this._alive = false;
  20618. if (!this._stopped) {
  20619. this._actualFrame += this._scaledUpdateSpeed;
  20620. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20621. this.stop();
  20622. }
  20623. else {
  20624. newParticles = 0;
  20625. }
  20626. this._update(newParticles);
  20627. // Stopped?
  20628. if (this._stopped) {
  20629. if (!this._alive) {
  20630. this._started = false;
  20631. if (this.disposeOnStop) {
  20632. this._scene._toBeDisposed.push(this);
  20633. }
  20634. }
  20635. }
  20636. // Update VBO
  20637. var offset = 0;
  20638. for (var index = 0; index < this.particles.length; index++) {
  20639. var particle = this.particles[index];
  20640. this._appendParticleVertex(offset++, particle, 0, 0);
  20641. this._appendParticleVertex(offset++, particle, 1, 0);
  20642. this._appendParticleVertex(offset++, particle, 1, 1);
  20643. this._appendParticleVertex(offset++, particle, 0, 1);
  20644. }
  20645. var engine = this._scene.getEngine();
  20646. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20647. };
  20648. ParticleSystem.prototype.render = function () {
  20649. var effect = this._getEffect();
  20650. // Check
  20651. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20652. return 0;
  20653. var engine = this._scene.getEngine();
  20654. // Render
  20655. engine.enableEffect(effect);
  20656. engine.setState(false);
  20657. var viewMatrix = this._scene.getViewMatrix();
  20658. effect.setTexture("diffuseSampler", this.particleTexture);
  20659. effect.setMatrix("view", viewMatrix);
  20660. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20661. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20662. if (this._scene.clipPlane) {
  20663. var clipPlane = this._scene.clipPlane;
  20664. var invView = viewMatrix.clone();
  20665. invView.invert();
  20666. effect.setMatrix("invView", invView);
  20667. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20668. }
  20669. // VBOs
  20670. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20671. // Draw order
  20672. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20673. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20674. }
  20675. else {
  20676. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20677. }
  20678. if (this.forceDepthWrite) {
  20679. engine.setDepthWrite(true);
  20680. }
  20681. engine.draw(true, 0, this.particles.length * 6);
  20682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20683. return this.particles.length;
  20684. };
  20685. ParticleSystem.prototype.dispose = function () {
  20686. if (this._vertexBuffer) {
  20687. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20688. this._vertexBuffer = null;
  20689. }
  20690. if (this._indexBuffer) {
  20691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20692. this._indexBuffer = null;
  20693. }
  20694. if (this.particleTexture) {
  20695. this.particleTexture.dispose();
  20696. this.particleTexture = null;
  20697. }
  20698. // Remove from scene
  20699. var index = this._scene.particleSystems.indexOf(this);
  20700. this._scene.particleSystems.splice(index, 1);
  20701. // Callback
  20702. if (this.onDispose) {
  20703. this.onDispose();
  20704. }
  20705. };
  20706. // Clone
  20707. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20708. var result = new ParticleSystem(name, this._capacity, this._scene);
  20709. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20710. if (newEmitter === undefined) {
  20711. newEmitter = this.emitter;
  20712. }
  20713. result.emitter = newEmitter;
  20714. if (this.particleTexture) {
  20715. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20716. }
  20717. result.start();
  20718. return result;
  20719. };
  20720. // Statics
  20721. ParticleSystem.BLENDMODE_ONEONE = 0;
  20722. ParticleSystem.BLENDMODE_STANDARD = 1;
  20723. return ParticleSystem;
  20724. })();
  20725. BABYLON.ParticleSystem = ParticleSystem;
  20726. })(BABYLON || (BABYLON = {}));
  20727. //# sourceMappingURL=babylon.particleSystem.js.map
  20728. var BABYLON;
  20729. (function (BABYLON) {
  20730. var Animation = (function () {
  20731. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20732. this.name = name;
  20733. this.targetProperty = targetProperty;
  20734. this.framePerSecond = framePerSecond;
  20735. this.dataType = dataType;
  20736. this.loopMode = loopMode;
  20737. this._offsetsCache = {};
  20738. this._highLimitsCache = {};
  20739. this._stopped = false;
  20740. this.targetPropertyPath = targetProperty.split(".");
  20741. this.dataType = dataType;
  20742. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20743. }
  20744. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20745. var dataType = undefined;
  20746. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20747. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20748. }
  20749. else if (from instanceof BABYLON.Quaternion) {
  20750. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20751. }
  20752. else if (from instanceof BABYLON.Vector3) {
  20753. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20754. }
  20755. else if (from instanceof BABYLON.Vector2) {
  20756. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20757. }
  20758. else if (from instanceof BABYLON.Color3) {
  20759. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20760. }
  20761. if (dataType == undefined) {
  20762. return null;
  20763. }
  20764. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20765. var keys = [];
  20766. keys.push({ frame: 0, value: from });
  20767. keys.push({ frame: totalFrame, value: to });
  20768. animation.setKeys(keys);
  20769. mesh.animations.push(animation);
  20770. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20771. };
  20772. // Methods
  20773. Animation.prototype.isStopped = function () {
  20774. return this._stopped;
  20775. };
  20776. Animation.prototype.getKeys = function () {
  20777. return this._keys;
  20778. };
  20779. Animation.prototype.getEasingFunction = function () {
  20780. return this._easingFunction;
  20781. };
  20782. Animation.prototype.setEasingFunction = function (easingFunction) {
  20783. this._easingFunction = easingFunction;
  20784. };
  20785. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20786. return startValue + (endValue - startValue) * gradient;
  20787. };
  20788. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20789. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20790. };
  20791. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20792. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20793. };
  20794. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20795. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20796. };
  20797. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20798. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20799. };
  20800. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20801. var startScale = new BABYLON.Vector3(0, 0, 0);
  20802. var startRotation = new BABYLON.Quaternion();
  20803. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20804. startValue.decompose(startScale, startRotation, startTranslation);
  20805. var endScale = new BABYLON.Vector3(0, 0, 0);
  20806. var endRotation = new BABYLON.Quaternion();
  20807. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20808. endValue.decompose(endScale, endRotation, endTranslation);
  20809. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20810. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20811. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20812. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20813. return result;
  20814. };
  20815. Animation.prototype.clone = function () {
  20816. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20817. clone.setKeys(this._keys);
  20818. return clone;
  20819. };
  20820. Animation.prototype.setKeys = function (values) {
  20821. this._keys = values.slice(0);
  20822. this._offsetsCache = {};
  20823. this._highLimitsCache = {};
  20824. };
  20825. Animation.prototype._getKeyValue = function (value) {
  20826. if (typeof value === "function") {
  20827. return value();
  20828. }
  20829. return value;
  20830. };
  20831. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20832. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20833. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20834. }
  20835. this.currentFrame = currentFrame;
  20836. // Try to get a hash to find the right key
  20837. 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));
  20838. if (this._keys[startKey].frame >= currentFrame) {
  20839. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20840. startKey--;
  20841. }
  20842. }
  20843. for (var key = startKey; key < this._keys.length; key++) {
  20844. if (this._keys[key + 1].frame >= currentFrame) {
  20845. var startValue = this._getKeyValue(this._keys[key].value);
  20846. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20847. // gradient : percent of currentFrame between the frame inf and the frame sup
  20848. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20849. // check for easingFunction and correction of gradient
  20850. if (this._easingFunction != null) {
  20851. gradient = this._easingFunction.ease(gradient);
  20852. }
  20853. switch (this.dataType) {
  20854. // Float
  20855. case Animation.ANIMATIONTYPE_FLOAT:
  20856. switch (loopMode) {
  20857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20859. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20860. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20861. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20862. }
  20863. break;
  20864. // Quaternion
  20865. case Animation.ANIMATIONTYPE_QUATERNION:
  20866. var quaternion = null;
  20867. switch (loopMode) {
  20868. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20869. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20870. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20871. break;
  20872. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20873. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20874. break;
  20875. }
  20876. return quaternion;
  20877. // Vector3
  20878. case Animation.ANIMATIONTYPE_VECTOR3:
  20879. switch (loopMode) {
  20880. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20881. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20882. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20883. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20884. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20885. }
  20886. // Vector2
  20887. case Animation.ANIMATIONTYPE_VECTOR2:
  20888. switch (loopMode) {
  20889. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20890. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20891. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20892. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20893. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20894. }
  20895. // Color3
  20896. case Animation.ANIMATIONTYPE_COLOR3:
  20897. switch (loopMode) {
  20898. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20899. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20900. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20901. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20902. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20903. }
  20904. // Matrix
  20905. case Animation.ANIMATIONTYPE_MATRIX:
  20906. switch (loopMode) {
  20907. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20908. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20909. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20910. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20911. return startValue;
  20912. }
  20913. default:
  20914. break;
  20915. }
  20916. break;
  20917. }
  20918. }
  20919. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20920. };
  20921. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20922. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20923. this._stopped = true;
  20924. return false;
  20925. }
  20926. var returnValue = true;
  20927. // Adding a start key at frame 0 if missing
  20928. if (this._keys[0].frame !== 0) {
  20929. var newKey = { frame: 0, value: this._keys[0].value };
  20930. this._keys.splice(0, 0, newKey);
  20931. }
  20932. // Check limits
  20933. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20934. from = this._keys[0].frame;
  20935. }
  20936. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20937. to = this._keys[this._keys.length - 1].frame;
  20938. }
  20939. // Compute ratio
  20940. var range = to - from;
  20941. var offsetValue;
  20942. // ratio represents the frame delta between from and to
  20943. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20944. var highLimitValue = 0;
  20945. if (ratio > range && !loop) {
  20946. returnValue = false;
  20947. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20948. }
  20949. else {
  20950. // Get max value if required
  20951. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20952. var keyOffset = to.toString() + from.toString();
  20953. if (!this._offsetsCache[keyOffset]) {
  20954. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20955. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20956. switch (this.dataType) {
  20957. // Float
  20958. case Animation.ANIMATIONTYPE_FLOAT:
  20959. this._offsetsCache[keyOffset] = toValue - fromValue;
  20960. break;
  20961. // Quaternion
  20962. case Animation.ANIMATIONTYPE_QUATERNION:
  20963. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20964. break;
  20965. // Vector3
  20966. case Animation.ANIMATIONTYPE_VECTOR3:
  20967. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20968. // Vector2
  20969. case Animation.ANIMATIONTYPE_VECTOR2:
  20970. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20971. // Color3
  20972. case Animation.ANIMATIONTYPE_COLOR3:
  20973. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20974. default:
  20975. break;
  20976. }
  20977. this._highLimitsCache[keyOffset] = toValue;
  20978. }
  20979. highLimitValue = this._highLimitsCache[keyOffset];
  20980. offsetValue = this._offsetsCache[keyOffset];
  20981. }
  20982. }
  20983. if (offsetValue === undefined) {
  20984. switch (this.dataType) {
  20985. // Float
  20986. case Animation.ANIMATIONTYPE_FLOAT:
  20987. offsetValue = 0;
  20988. break;
  20989. // Quaternion
  20990. case Animation.ANIMATIONTYPE_QUATERNION:
  20991. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20992. break;
  20993. // Vector3
  20994. case Animation.ANIMATIONTYPE_VECTOR3:
  20995. offsetValue = BABYLON.Vector3.Zero();
  20996. break;
  20997. // Vector2
  20998. case Animation.ANIMATIONTYPE_VECTOR2:
  20999. offsetValue = BABYLON.Vector2.Zero();
  21000. break;
  21001. // Color3
  21002. case Animation.ANIMATIONTYPE_COLOR3:
  21003. offsetValue = BABYLON.Color3.Black();
  21004. }
  21005. }
  21006. // Compute value
  21007. var repeatCount = (ratio / range) >> 0;
  21008. var currentFrame = returnValue ? from + ratio % range : to;
  21009. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21010. // Set value
  21011. if (this.targetPropertyPath.length > 1) {
  21012. var property = this._target[this.targetPropertyPath[0]];
  21013. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21014. property = property[this.targetPropertyPath[index]];
  21015. }
  21016. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21017. }
  21018. else {
  21019. this._target[this.targetPropertyPath[0]] = currentValue;
  21020. }
  21021. if (this._target.markAsDirty) {
  21022. this._target.markAsDirty(this.targetProperty);
  21023. }
  21024. if (!returnValue) {
  21025. this._stopped = true;
  21026. }
  21027. return returnValue;
  21028. };
  21029. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21030. get: function () {
  21031. return Animation._ANIMATIONTYPE_FLOAT;
  21032. },
  21033. enumerable: true,
  21034. configurable: true
  21035. });
  21036. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21037. get: function () {
  21038. return Animation._ANIMATIONTYPE_VECTOR3;
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21044. get: function () {
  21045. return Animation._ANIMATIONTYPE_VECTOR2;
  21046. },
  21047. enumerable: true,
  21048. configurable: true
  21049. });
  21050. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21051. get: function () {
  21052. return Animation._ANIMATIONTYPE_QUATERNION;
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21058. get: function () {
  21059. return Animation._ANIMATIONTYPE_MATRIX;
  21060. },
  21061. enumerable: true,
  21062. configurable: true
  21063. });
  21064. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21065. get: function () {
  21066. return Animation._ANIMATIONTYPE_COLOR3;
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21072. get: function () {
  21073. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21079. get: function () {
  21080. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21081. },
  21082. enumerable: true,
  21083. configurable: true
  21084. });
  21085. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21086. get: function () {
  21087. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21088. },
  21089. enumerable: true,
  21090. configurable: true
  21091. });
  21092. // Statics
  21093. Animation._ANIMATIONTYPE_FLOAT = 0;
  21094. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21095. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21096. Animation._ANIMATIONTYPE_MATRIX = 3;
  21097. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21098. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21099. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21100. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21101. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21102. return Animation;
  21103. })();
  21104. BABYLON.Animation = Animation;
  21105. })(BABYLON || (BABYLON = {}));
  21106. //# sourceMappingURL=babylon.animation.js.map
  21107. var BABYLON;
  21108. (function (BABYLON) {
  21109. var Animatable = (function () {
  21110. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21111. if (fromFrame === void 0) { fromFrame = 0; }
  21112. if (toFrame === void 0) { toFrame = 100; }
  21113. if (loopAnimation === void 0) { loopAnimation = false; }
  21114. if (speedRatio === void 0) { speedRatio = 1.0; }
  21115. this.target = target;
  21116. this.fromFrame = fromFrame;
  21117. this.toFrame = toFrame;
  21118. this.loopAnimation = loopAnimation;
  21119. this.speedRatio = speedRatio;
  21120. this.onAnimationEnd = onAnimationEnd;
  21121. this._animations = new Array();
  21122. this._paused = false;
  21123. this.animationStarted = false;
  21124. if (animations) {
  21125. this.appendAnimations(target, animations);
  21126. }
  21127. this._scene = scene;
  21128. scene._activeAnimatables.push(this);
  21129. }
  21130. // Methods
  21131. Animatable.prototype.appendAnimations = function (target, animations) {
  21132. for (var index = 0; index < animations.length; index++) {
  21133. var animation = animations[index];
  21134. animation._target = target;
  21135. this._animations.push(animation);
  21136. }
  21137. };
  21138. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21139. var animations = this._animations;
  21140. for (var index = 0; index < animations.length; index++) {
  21141. if (animations[index].targetProperty === property) {
  21142. return animations[index];
  21143. }
  21144. }
  21145. return null;
  21146. };
  21147. Animatable.prototype.pause = function () {
  21148. if (this._paused) {
  21149. return;
  21150. }
  21151. this._paused = true;
  21152. };
  21153. Animatable.prototype.restart = function () {
  21154. this._paused = false;
  21155. };
  21156. Animatable.prototype.stop = function () {
  21157. var index = this._scene._activeAnimatables.indexOf(this);
  21158. if (index > -1) {
  21159. this._scene._activeAnimatables.splice(index, 1);
  21160. }
  21161. if (this.onAnimationEnd) {
  21162. this.onAnimationEnd();
  21163. }
  21164. };
  21165. Animatable.prototype._animate = function (delay) {
  21166. if (this._paused) {
  21167. if (!this._pausedDelay) {
  21168. this._pausedDelay = delay;
  21169. }
  21170. return true;
  21171. }
  21172. if (!this._localDelayOffset) {
  21173. this._localDelayOffset = delay;
  21174. }
  21175. else if (this._pausedDelay) {
  21176. this._localDelayOffset += delay - this._pausedDelay;
  21177. this._pausedDelay = null;
  21178. }
  21179. // Animating
  21180. var running = false;
  21181. var animations = this._animations;
  21182. for (var index = 0; index < animations.length; index++) {
  21183. var animation = animations[index];
  21184. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21185. running = running || isRunning;
  21186. }
  21187. if (!running) {
  21188. // Remove from active animatables
  21189. index = this._scene._activeAnimatables.indexOf(this);
  21190. this._scene._activeAnimatables.splice(index, 1);
  21191. }
  21192. if (!running && this.onAnimationEnd) {
  21193. this.onAnimationEnd();
  21194. }
  21195. return running;
  21196. };
  21197. return Animatable;
  21198. })();
  21199. BABYLON.Animatable = Animatable;
  21200. })(BABYLON || (BABYLON = {}));
  21201. //# sourceMappingURL=babylon.animatable.js.map
  21202. var __extends = this.__extends || function (d, b) {
  21203. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21204. function __() { this.constructor = d; }
  21205. __.prototype = b.prototype;
  21206. d.prototype = new __();
  21207. };
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. var EasingFunction = (function () {
  21211. function EasingFunction() {
  21212. // Properties
  21213. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21214. }
  21215. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21216. get: function () {
  21217. return EasingFunction._EASINGMODE_EASEIN;
  21218. },
  21219. enumerable: true,
  21220. configurable: true
  21221. });
  21222. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21223. get: function () {
  21224. return EasingFunction._EASINGMODE_EASEOUT;
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21230. get: function () {
  21231. return EasingFunction._EASINGMODE_EASEINOUT;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21237. var n = Math.min(Math.max(easingMode, 0), 2);
  21238. this._easingMode = n;
  21239. };
  21240. EasingFunction.prototype.getEasingMode = function () {
  21241. return this._easingMode;
  21242. };
  21243. EasingFunction.prototype.easeInCore = function (gradient) {
  21244. throw new Error('You must implement this method');
  21245. };
  21246. EasingFunction.prototype.ease = function (gradient) {
  21247. switch (this._easingMode) {
  21248. case EasingFunction.EASINGMODE_EASEIN:
  21249. return this.easeInCore(gradient);
  21250. case EasingFunction.EASINGMODE_EASEOUT:
  21251. return (1 - this.easeInCore(1 - gradient));
  21252. }
  21253. if (gradient >= 0.5) {
  21254. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21255. }
  21256. return (this.easeInCore(gradient * 2) * 0.5);
  21257. };
  21258. //Statics
  21259. EasingFunction._EASINGMODE_EASEIN = 0;
  21260. EasingFunction._EASINGMODE_EASEOUT = 1;
  21261. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21262. return EasingFunction;
  21263. })();
  21264. BABYLON.EasingFunction = EasingFunction;
  21265. var CircleEase = (function (_super) {
  21266. __extends(CircleEase, _super);
  21267. function CircleEase() {
  21268. _super.apply(this, arguments);
  21269. }
  21270. CircleEase.prototype.easeInCore = function (gradient) {
  21271. gradient = Math.max(0, Math.min(1, gradient));
  21272. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21273. };
  21274. return CircleEase;
  21275. })(EasingFunction);
  21276. BABYLON.CircleEase = CircleEase;
  21277. var BackEase = (function (_super) {
  21278. __extends(BackEase, _super);
  21279. function BackEase(amplitude) {
  21280. if (amplitude === void 0) { amplitude = 1; }
  21281. _super.call(this);
  21282. this.amplitude = amplitude;
  21283. }
  21284. BackEase.prototype.easeInCore = function (gradient) {
  21285. var num = Math.max(0, this.amplitude);
  21286. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21287. };
  21288. return BackEase;
  21289. })(EasingFunction);
  21290. BABYLON.BackEase = BackEase;
  21291. var BounceEase = (function (_super) {
  21292. __extends(BounceEase, _super);
  21293. function BounceEase(bounces, bounciness) {
  21294. if (bounces === void 0) { bounces = 3; }
  21295. if (bounciness === void 0) { bounciness = 2; }
  21296. _super.call(this);
  21297. this.bounces = bounces;
  21298. this.bounciness = bounciness;
  21299. }
  21300. BounceEase.prototype.easeInCore = function (gradient) {
  21301. var y = Math.max(0.0, this.bounces);
  21302. var bounciness = this.bounciness;
  21303. if (bounciness <= 1.0) {
  21304. bounciness = 1.001;
  21305. }
  21306. var num9 = Math.pow(bounciness, y);
  21307. var num5 = 1.0 - bounciness;
  21308. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21309. var num15 = gradient * num4;
  21310. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21311. var num3 = Math.floor(num65);
  21312. var num13 = num3 + 1.0;
  21313. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21314. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21315. var num7 = (num8 + num12) * 0.5;
  21316. var num6 = gradient - num7;
  21317. var num2 = num7 - num8;
  21318. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21319. };
  21320. return BounceEase;
  21321. })(EasingFunction);
  21322. BABYLON.BounceEase = BounceEase;
  21323. var CubicEase = (function (_super) {
  21324. __extends(CubicEase, _super);
  21325. function CubicEase() {
  21326. _super.apply(this, arguments);
  21327. }
  21328. CubicEase.prototype.easeInCore = function (gradient) {
  21329. return (gradient * gradient * gradient);
  21330. };
  21331. return CubicEase;
  21332. })(EasingFunction);
  21333. BABYLON.CubicEase = CubicEase;
  21334. var ElasticEase = (function (_super) {
  21335. __extends(ElasticEase, _super);
  21336. function ElasticEase(oscillations, springiness) {
  21337. if (oscillations === void 0) { oscillations = 3; }
  21338. if (springiness === void 0) { springiness = 3; }
  21339. _super.call(this);
  21340. this.oscillations = oscillations;
  21341. this.springiness = springiness;
  21342. }
  21343. ElasticEase.prototype.easeInCore = function (gradient) {
  21344. var num2;
  21345. var num3 = Math.max(0.0, this.oscillations);
  21346. var num = Math.max(0.0, this.springiness);
  21347. if (num == 0) {
  21348. num2 = gradient;
  21349. }
  21350. else {
  21351. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21352. }
  21353. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21354. };
  21355. return ElasticEase;
  21356. })(EasingFunction);
  21357. BABYLON.ElasticEase = ElasticEase;
  21358. var ExponentialEase = (function (_super) {
  21359. __extends(ExponentialEase, _super);
  21360. function ExponentialEase(exponent) {
  21361. if (exponent === void 0) { exponent = 2; }
  21362. _super.call(this);
  21363. this.exponent = exponent;
  21364. }
  21365. ExponentialEase.prototype.easeInCore = function (gradient) {
  21366. if (this.exponent <= 0) {
  21367. return gradient;
  21368. }
  21369. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21370. };
  21371. return ExponentialEase;
  21372. })(EasingFunction);
  21373. BABYLON.ExponentialEase = ExponentialEase;
  21374. var PowerEase = (function (_super) {
  21375. __extends(PowerEase, _super);
  21376. function PowerEase(power) {
  21377. if (power === void 0) { power = 2; }
  21378. _super.call(this);
  21379. this.power = power;
  21380. }
  21381. PowerEase.prototype.easeInCore = function (gradient) {
  21382. var y = Math.max(0.0, this.power);
  21383. return Math.pow(gradient, y);
  21384. };
  21385. return PowerEase;
  21386. })(EasingFunction);
  21387. BABYLON.PowerEase = PowerEase;
  21388. var QuadraticEase = (function (_super) {
  21389. __extends(QuadraticEase, _super);
  21390. function QuadraticEase() {
  21391. _super.apply(this, arguments);
  21392. }
  21393. QuadraticEase.prototype.easeInCore = function (gradient) {
  21394. return (gradient * gradient);
  21395. };
  21396. return QuadraticEase;
  21397. })(EasingFunction);
  21398. BABYLON.QuadraticEase = QuadraticEase;
  21399. var QuarticEase = (function (_super) {
  21400. __extends(QuarticEase, _super);
  21401. function QuarticEase() {
  21402. _super.apply(this, arguments);
  21403. }
  21404. QuarticEase.prototype.easeInCore = function (gradient) {
  21405. return (gradient * gradient * gradient * gradient);
  21406. };
  21407. return QuarticEase;
  21408. })(EasingFunction);
  21409. BABYLON.QuarticEase = QuarticEase;
  21410. var QuinticEase = (function (_super) {
  21411. __extends(QuinticEase, _super);
  21412. function QuinticEase() {
  21413. _super.apply(this, arguments);
  21414. }
  21415. QuinticEase.prototype.easeInCore = function (gradient) {
  21416. return (gradient * gradient * gradient * gradient * gradient);
  21417. };
  21418. return QuinticEase;
  21419. })(EasingFunction);
  21420. BABYLON.QuinticEase = QuinticEase;
  21421. var SineEase = (function (_super) {
  21422. __extends(SineEase, _super);
  21423. function SineEase() {
  21424. _super.apply(this, arguments);
  21425. }
  21426. SineEase.prototype.easeInCore = function (gradient) {
  21427. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21428. };
  21429. return SineEase;
  21430. })(EasingFunction);
  21431. BABYLON.SineEase = SineEase;
  21432. var BezierCurveEase = (function (_super) {
  21433. __extends(BezierCurveEase, _super);
  21434. function BezierCurveEase(x1, y1, x2, y2) {
  21435. if (x1 === void 0) { x1 = 0; }
  21436. if (y1 === void 0) { y1 = 0; }
  21437. if (x2 === void 0) { x2 = 1; }
  21438. if (y2 === void 0) { y2 = 1; }
  21439. _super.call(this);
  21440. this.x1 = x1;
  21441. this.y1 = y1;
  21442. this.x2 = x2;
  21443. this.y2 = y2;
  21444. }
  21445. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21446. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21447. };
  21448. return BezierCurveEase;
  21449. })(EasingFunction);
  21450. BABYLON.BezierCurveEase = BezierCurveEase;
  21451. })(BABYLON || (BABYLON = {}));
  21452. //# sourceMappingURL=babylon.easing.js.map
  21453. var BABYLON;
  21454. (function (BABYLON) {
  21455. var Octree = (function () {
  21456. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21457. if (maxDepth === void 0) { maxDepth = 2; }
  21458. this.maxDepth = maxDepth;
  21459. this.dynamicContent = new Array();
  21460. this._maxBlockCapacity = maxBlockCapacity || 64;
  21461. this._selectionContent = new BABYLON.SmartArray(1024);
  21462. this._creationFunc = creationFunc;
  21463. }
  21464. // Methods
  21465. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21466. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21467. };
  21468. Octree.prototype.addMesh = function (entry) {
  21469. for (var index = 0; index < this.blocks.length; index++) {
  21470. var block = this.blocks[index];
  21471. block.addEntry(entry);
  21472. }
  21473. };
  21474. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21475. this._selectionContent.reset();
  21476. for (var index = 0; index < this.blocks.length; index++) {
  21477. var block = this.blocks[index];
  21478. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21479. }
  21480. if (allowDuplicate) {
  21481. this._selectionContent.concat(this.dynamicContent);
  21482. }
  21483. else {
  21484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21485. }
  21486. return this._selectionContent;
  21487. };
  21488. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21489. this._selectionContent.reset();
  21490. for (var index = 0; index < this.blocks.length; index++) {
  21491. var block = this.blocks[index];
  21492. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21493. }
  21494. if (allowDuplicate) {
  21495. this._selectionContent.concat(this.dynamicContent);
  21496. }
  21497. else {
  21498. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21499. }
  21500. return this._selectionContent;
  21501. };
  21502. Octree.prototype.intersectsRay = function (ray) {
  21503. this._selectionContent.reset();
  21504. for (var index = 0; index < this.blocks.length; index++) {
  21505. var block = this.blocks[index];
  21506. block.intersectsRay(ray, this._selectionContent);
  21507. }
  21508. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21509. return this._selectionContent;
  21510. };
  21511. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21512. target.blocks = new Array();
  21513. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21514. // Segmenting space
  21515. for (var x = 0; x < 2; x++) {
  21516. for (var y = 0; y < 2; y++) {
  21517. for (var z = 0; z < 2; z++) {
  21518. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21519. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21520. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21521. block.addEntries(entries);
  21522. target.blocks.push(block);
  21523. }
  21524. }
  21525. }
  21526. };
  21527. Octree.CreationFuncForMeshes = function (entry, block) {
  21528. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21529. block.entries.push(entry);
  21530. }
  21531. };
  21532. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21533. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21534. block.entries.push(entry);
  21535. }
  21536. };
  21537. return Octree;
  21538. })();
  21539. BABYLON.Octree = Octree;
  21540. })(BABYLON || (BABYLON = {}));
  21541. //# sourceMappingURL=babylon.octree.js.map
  21542. var BABYLON;
  21543. (function (BABYLON) {
  21544. var OctreeBlock = (function () {
  21545. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21546. this.entries = new Array();
  21547. this._boundingVectors = new Array();
  21548. this._capacity = capacity;
  21549. this._depth = depth;
  21550. this._maxDepth = maxDepth;
  21551. this._creationFunc = creationFunc;
  21552. this._minPoint = minPoint;
  21553. this._maxPoint = maxPoint;
  21554. this._boundingVectors.push(minPoint.clone());
  21555. this._boundingVectors.push(maxPoint.clone());
  21556. this._boundingVectors.push(minPoint.clone());
  21557. this._boundingVectors[2].x = maxPoint.x;
  21558. this._boundingVectors.push(minPoint.clone());
  21559. this._boundingVectors[3].y = maxPoint.y;
  21560. this._boundingVectors.push(minPoint.clone());
  21561. this._boundingVectors[4].z = maxPoint.z;
  21562. this._boundingVectors.push(maxPoint.clone());
  21563. this._boundingVectors[5].z = minPoint.z;
  21564. this._boundingVectors.push(maxPoint.clone());
  21565. this._boundingVectors[6].x = minPoint.x;
  21566. this._boundingVectors.push(maxPoint.clone());
  21567. this._boundingVectors[7].y = minPoint.y;
  21568. }
  21569. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21570. // Property
  21571. get: function () {
  21572. return this._capacity;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21578. get: function () {
  21579. return this._minPoint;
  21580. },
  21581. enumerable: true,
  21582. configurable: true
  21583. });
  21584. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21585. get: function () {
  21586. return this._maxPoint;
  21587. },
  21588. enumerable: true,
  21589. configurable: true
  21590. });
  21591. // Methods
  21592. OctreeBlock.prototype.addEntry = function (entry) {
  21593. if (this.blocks) {
  21594. for (var index = 0; index < this.blocks.length; index++) {
  21595. var block = this.blocks[index];
  21596. block.addEntry(entry);
  21597. }
  21598. return;
  21599. }
  21600. this._creationFunc(entry, this);
  21601. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21602. this.createInnerBlocks();
  21603. }
  21604. };
  21605. OctreeBlock.prototype.addEntries = function (entries) {
  21606. for (var index = 0; index < entries.length; index++) {
  21607. var mesh = entries[index];
  21608. this.addEntry(mesh);
  21609. }
  21610. };
  21611. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21612. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21613. if (this.blocks) {
  21614. for (var index = 0; index < this.blocks.length; index++) {
  21615. var block = this.blocks[index];
  21616. block.select(frustumPlanes, selection, allowDuplicate);
  21617. }
  21618. return;
  21619. }
  21620. if (allowDuplicate) {
  21621. selection.concat(this.entries);
  21622. }
  21623. else {
  21624. selection.concatWithNoDuplicate(this.entries);
  21625. }
  21626. }
  21627. };
  21628. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21629. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21630. if (this.blocks) {
  21631. for (var index = 0; index < this.blocks.length; index++) {
  21632. var block = this.blocks[index];
  21633. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21634. }
  21635. return;
  21636. }
  21637. if (allowDuplicate) {
  21638. selection.concat(this.entries);
  21639. }
  21640. else {
  21641. selection.concatWithNoDuplicate(this.entries);
  21642. }
  21643. }
  21644. };
  21645. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21646. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21647. if (this.blocks) {
  21648. for (var index = 0; index < this.blocks.length; index++) {
  21649. var block = this.blocks[index];
  21650. block.intersectsRay(ray, selection);
  21651. }
  21652. return;
  21653. }
  21654. selection.concatWithNoDuplicate(this.entries);
  21655. }
  21656. };
  21657. OctreeBlock.prototype.createInnerBlocks = function () {
  21658. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21659. };
  21660. return OctreeBlock;
  21661. })();
  21662. BABYLON.OctreeBlock = OctreeBlock;
  21663. })(BABYLON || (BABYLON = {}));
  21664. //# sourceMappingURL=babylon.octreeBlock.js.map
  21665. var BABYLON;
  21666. (function (BABYLON) {
  21667. var Bone = (function () {
  21668. function Bone(name, skeleton, parentBone, matrix) {
  21669. this.name = name;
  21670. this.children = new Array();
  21671. this.animations = new Array();
  21672. this._worldTransform = new BABYLON.Matrix();
  21673. this._absoluteTransform = new BABYLON.Matrix();
  21674. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21675. this._skeleton = skeleton;
  21676. this._matrix = matrix;
  21677. this._baseMatrix = matrix;
  21678. skeleton.bones.push(this);
  21679. if (parentBone) {
  21680. this._parent = parentBone;
  21681. parentBone.children.push(this);
  21682. }
  21683. else {
  21684. this._parent = null;
  21685. }
  21686. this._updateDifferenceMatrix();
  21687. }
  21688. // Members
  21689. Bone.prototype.getParent = function () {
  21690. return this._parent;
  21691. };
  21692. Bone.prototype.getLocalMatrix = function () {
  21693. return this._matrix;
  21694. };
  21695. Bone.prototype.getBaseMatrix = function () {
  21696. return this._baseMatrix;
  21697. };
  21698. Bone.prototype.getWorldMatrix = function () {
  21699. return this._worldTransform;
  21700. };
  21701. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21702. return this._invertedAbsoluteTransform;
  21703. };
  21704. Bone.prototype.getAbsoluteMatrix = function () {
  21705. var matrix = this._matrix.clone();
  21706. var parent = this._parent;
  21707. while (parent) {
  21708. matrix = matrix.multiply(parent.getLocalMatrix());
  21709. parent = parent.getParent();
  21710. }
  21711. return matrix;
  21712. };
  21713. // Methods
  21714. Bone.prototype.updateMatrix = function (matrix) {
  21715. this._matrix = matrix;
  21716. this._skeleton._markAsDirty();
  21717. this._updateDifferenceMatrix();
  21718. };
  21719. Bone.prototype._updateDifferenceMatrix = function () {
  21720. if (this._parent) {
  21721. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21722. }
  21723. else {
  21724. this._absoluteTransform.copyFrom(this._matrix);
  21725. }
  21726. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21727. for (var index = 0; index < this.children.length; index++) {
  21728. this.children[index]._updateDifferenceMatrix();
  21729. }
  21730. };
  21731. Bone.prototype.markAsDirty = function () {
  21732. this._skeleton._markAsDirty();
  21733. };
  21734. return Bone;
  21735. })();
  21736. BABYLON.Bone = Bone;
  21737. })(BABYLON || (BABYLON = {}));
  21738. //# sourceMappingURL=babylon.bone.js.map
  21739. var BABYLON;
  21740. (function (BABYLON) {
  21741. var Skeleton = (function () {
  21742. function Skeleton(name, id, scene) {
  21743. this.name = name;
  21744. this.id = id;
  21745. this.bones = new Array();
  21746. this._isDirty = true;
  21747. this._identity = BABYLON.Matrix.Identity();
  21748. this.bones = [];
  21749. this._scene = scene;
  21750. scene.skeletons.push(this);
  21751. this.prepare();
  21752. //make sure it will recalculate the matrix next time prepare is called.
  21753. this._isDirty = true;
  21754. }
  21755. // Members
  21756. Skeleton.prototype.getTransformMatrices = function () {
  21757. return this._transformMatrices;
  21758. };
  21759. // Methods
  21760. Skeleton.prototype._markAsDirty = function () {
  21761. this._isDirty = true;
  21762. };
  21763. Skeleton.prototype.prepare = function () {
  21764. if (!this._isDirty) {
  21765. return;
  21766. }
  21767. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21768. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21769. }
  21770. for (var index = 0; index < this.bones.length; index++) {
  21771. var bone = this.bones[index];
  21772. var parentBone = bone.getParent();
  21773. if (parentBone) {
  21774. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21775. }
  21776. else {
  21777. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21778. }
  21779. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21780. }
  21781. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21782. this._isDirty = false;
  21783. this._scene._activeBones += this.bones.length;
  21784. };
  21785. Skeleton.prototype.getAnimatables = function () {
  21786. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21787. this._animatables = [];
  21788. for (var index = 0; index < this.bones.length; index++) {
  21789. this._animatables.push(this.bones[index]);
  21790. }
  21791. }
  21792. return this._animatables;
  21793. };
  21794. Skeleton.prototype.clone = function (name, id) {
  21795. var result = new Skeleton(name, id || name, this._scene);
  21796. for (var index = 0; index < this.bones.length; index++) {
  21797. var source = this.bones[index];
  21798. var parentBone = null;
  21799. if (source.getParent()) {
  21800. var parentIndex = this.bones.indexOf(source.getParent());
  21801. parentBone = result.bones[parentIndex];
  21802. }
  21803. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21804. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21805. }
  21806. return result;
  21807. };
  21808. return Skeleton;
  21809. })();
  21810. BABYLON.Skeleton = Skeleton;
  21811. })(BABYLON || (BABYLON = {}));
  21812. //# sourceMappingURL=babylon.skeleton.js.map
  21813. var BABYLON;
  21814. (function (BABYLON) {
  21815. var PostProcess = (function () {
  21816. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21818. this.name = name;
  21819. this.width = -1;
  21820. this.height = -1;
  21821. this._reusable = false;
  21822. this._textures = new BABYLON.SmartArray(2);
  21823. this._currentRenderTextureInd = 0;
  21824. if (camera != null) {
  21825. this._camera = camera;
  21826. this._scene = camera.getScene();
  21827. camera.attachPostProcess(this);
  21828. this._engine = this._scene.getEngine();
  21829. }
  21830. else {
  21831. this._engine = engine;
  21832. }
  21833. this._renderRatio = ratio;
  21834. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21835. this._reusable = reusable || false;
  21836. samplers = samplers || [];
  21837. samplers.push("textureSampler");
  21838. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21839. }
  21840. PostProcess.prototype.isReusable = function () {
  21841. return this._reusable;
  21842. };
  21843. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21844. camera = camera || this._camera;
  21845. var scene = camera.getScene();
  21846. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21847. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21848. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21849. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21850. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21851. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21852. if (this._textures.length > 0) {
  21853. for (var i = 0; i < this._textures.length; i++) {
  21854. this._engine._releaseTexture(this._textures.data[i]);
  21855. }
  21856. this._textures.reset();
  21857. }
  21858. this.width = desiredWidth;
  21859. this.height = desiredHeight;
  21860. 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 }));
  21861. if (this._reusable) {
  21862. 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 }));
  21863. }
  21864. if (this.onSizeChanged) {
  21865. this.onSizeChanged();
  21866. }
  21867. }
  21868. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21869. if (this.onActivate) {
  21870. this.onActivate(camera);
  21871. }
  21872. // Clear
  21873. if (this.clearColor) {
  21874. this._engine.clear(this.clearColor, true, true);
  21875. }
  21876. else {
  21877. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21878. }
  21879. if (this._reusable) {
  21880. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21881. }
  21882. };
  21883. PostProcess.prototype.apply = function () {
  21884. // Check
  21885. if (!this._effect.isReady())
  21886. return null;
  21887. // States
  21888. this._engine.enableEffect(this._effect);
  21889. this._engine.setState(false);
  21890. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21891. this._engine.setDepthBuffer(false);
  21892. this._engine.setDepthWrite(false);
  21893. // Texture
  21894. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21895. // Parameters
  21896. if (this.onApply) {
  21897. this.onApply(this._effect);
  21898. }
  21899. return this._effect;
  21900. };
  21901. PostProcess.prototype.dispose = function (camera) {
  21902. camera = camera || this._camera;
  21903. if (this._textures.length > 0) {
  21904. for (var i = 0; i < this._textures.length; i++) {
  21905. this._engine._releaseTexture(this._textures.data[i]);
  21906. }
  21907. this._textures.reset();
  21908. }
  21909. if (!camera) {
  21910. return;
  21911. }
  21912. camera.detachPostProcess(this);
  21913. var index = camera._postProcesses.indexOf(this);
  21914. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21915. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21916. }
  21917. };
  21918. return PostProcess;
  21919. })();
  21920. BABYLON.PostProcess = PostProcess;
  21921. })(BABYLON || (BABYLON = {}));
  21922. //# sourceMappingURL=babylon.postProcess.js.map
  21923. var BABYLON;
  21924. (function (BABYLON) {
  21925. var PostProcessManager = (function () {
  21926. function PostProcessManager(scene) {
  21927. this._vertexDeclaration = [2];
  21928. this._vertexStrideSize = 2 * 4;
  21929. this._scene = scene;
  21930. }
  21931. PostProcessManager.prototype._prepareBuffers = function () {
  21932. if (this._vertexBuffer) {
  21933. return;
  21934. }
  21935. // VBO
  21936. var vertices = [];
  21937. vertices.push(1, 1);
  21938. vertices.push(-1, 1);
  21939. vertices.push(-1, -1);
  21940. vertices.push(1, -1);
  21941. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21942. // Indices
  21943. var indices = [];
  21944. indices.push(0);
  21945. indices.push(1);
  21946. indices.push(2);
  21947. indices.push(0);
  21948. indices.push(2);
  21949. indices.push(3);
  21950. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21951. };
  21952. // Methods
  21953. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21954. var postProcesses = this._scene.activeCamera._postProcesses;
  21955. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21956. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21957. return false;
  21958. }
  21959. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21960. return true;
  21961. };
  21962. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21963. var engine = this._scene.getEngine();
  21964. for (var index = 0; index < postProcesses.length; index++) {
  21965. if (index < postProcesses.length - 1) {
  21966. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21967. }
  21968. else {
  21969. if (targetTexture) {
  21970. engine.bindFramebuffer(targetTexture);
  21971. }
  21972. else {
  21973. engine.restoreDefaultFramebuffer();
  21974. }
  21975. }
  21976. var pp = postProcesses[index];
  21977. var effect = pp.apply();
  21978. if (effect) {
  21979. if (pp.onBeforeRender) {
  21980. pp.onBeforeRender(effect);
  21981. }
  21982. // VBOs
  21983. this._prepareBuffers();
  21984. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21985. // Draw order
  21986. engine.draw(true, 0, 6);
  21987. }
  21988. }
  21989. // Restore depth buffer
  21990. engine.setDepthBuffer(true);
  21991. engine.setDepthWrite(true);
  21992. };
  21993. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21994. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21995. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21996. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21997. return;
  21998. }
  21999. var engine = this._scene.getEngine();
  22000. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22001. if (index < postProcessesTakenIndices.length - 1) {
  22002. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22003. }
  22004. else {
  22005. if (targetTexture) {
  22006. engine.bindFramebuffer(targetTexture);
  22007. }
  22008. else {
  22009. engine.restoreDefaultFramebuffer();
  22010. }
  22011. }
  22012. if (doNotPresent) {
  22013. break;
  22014. }
  22015. var pp = postProcesses[postProcessesTakenIndices[index]];
  22016. var effect = pp.apply();
  22017. if (effect) {
  22018. if (pp.onBeforeRender) {
  22019. pp.onBeforeRender(effect);
  22020. }
  22021. // VBOs
  22022. this._prepareBuffers();
  22023. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22024. // Draw order
  22025. engine.draw(true, 0, 6);
  22026. }
  22027. }
  22028. // Restore depth buffer
  22029. engine.setDepthBuffer(true);
  22030. engine.setDepthWrite(true);
  22031. };
  22032. PostProcessManager.prototype.dispose = function () {
  22033. if (this._vertexBuffer) {
  22034. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22035. this._vertexBuffer = null;
  22036. }
  22037. if (this._indexBuffer) {
  22038. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22039. this._indexBuffer = null;
  22040. }
  22041. };
  22042. return PostProcessManager;
  22043. })();
  22044. BABYLON.PostProcessManager = PostProcessManager;
  22045. })(BABYLON || (BABYLON = {}));
  22046. //# sourceMappingURL=babylon.postProcessManager.js.map
  22047. var __extends = this.__extends || function (d, b) {
  22048. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22049. function __() { this.constructor = d; }
  22050. __.prototype = b.prototype;
  22051. d.prototype = new __();
  22052. };
  22053. var BABYLON;
  22054. (function (BABYLON) {
  22055. var PassPostProcess = (function (_super) {
  22056. __extends(PassPostProcess, _super);
  22057. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22058. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22059. }
  22060. return PassPostProcess;
  22061. })(BABYLON.PostProcess);
  22062. BABYLON.PassPostProcess = PassPostProcess;
  22063. })(BABYLON || (BABYLON = {}));
  22064. //# sourceMappingURL=babylon.passPostProcess.js.map
  22065. var __extends = this.__extends || function (d, b) {
  22066. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22067. function __() { this.constructor = d; }
  22068. __.prototype = b.prototype;
  22069. d.prototype = new __();
  22070. };
  22071. var BABYLON;
  22072. (function (BABYLON) {
  22073. var BlurPostProcess = (function (_super) {
  22074. __extends(BlurPostProcess, _super);
  22075. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22076. var _this = this;
  22077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22078. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22079. this.direction = direction;
  22080. this.blurWidth = blurWidth;
  22081. this.onApply = function (effect) {
  22082. effect.setFloat2("screenSize", _this.width, _this.height);
  22083. effect.setVector2("direction", _this.direction);
  22084. effect.setFloat("blurWidth", _this.blurWidth);
  22085. };
  22086. }
  22087. return BlurPostProcess;
  22088. })(BABYLON.PostProcess);
  22089. BABYLON.BlurPostProcess = BlurPostProcess;
  22090. })(BABYLON || (BABYLON = {}));
  22091. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22092. var __extends = this.__extends || function (d, b) {
  22093. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22094. function __() { this.constructor = d; }
  22095. __.prototype = b.prototype;
  22096. d.prototype = new __();
  22097. };
  22098. var BABYLON;
  22099. (function (BABYLON) {
  22100. var RefractionPostProcess = (function (_super) {
  22101. __extends(RefractionPostProcess, _super);
  22102. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22103. var _this = this;
  22104. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22105. this.color = color;
  22106. this.depth = depth;
  22107. this.colorLevel = colorLevel;
  22108. this.onActivate = function (cam) {
  22109. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22110. };
  22111. this.onApply = function (effect) {
  22112. effect.setColor3("baseColor", _this.color);
  22113. effect.setFloat("depth", _this.depth);
  22114. effect.setFloat("colorLevel", _this.colorLevel);
  22115. effect.setTexture("refractionSampler", _this._refRexture);
  22116. };
  22117. }
  22118. // Methods
  22119. RefractionPostProcess.prototype.dispose = function (camera) {
  22120. if (this._refRexture) {
  22121. this._refRexture.dispose();
  22122. }
  22123. _super.prototype.dispose.call(this, camera);
  22124. };
  22125. return RefractionPostProcess;
  22126. })(BABYLON.PostProcess);
  22127. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22128. })(BABYLON || (BABYLON = {}));
  22129. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22130. var __extends = this.__extends || function (d, b) {
  22131. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22132. function __() { this.constructor = d; }
  22133. __.prototype = b.prototype;
  22134. d.prototype = new __();
  22135. };
  22136. var BABYLON;
  22137. (function (BABYLON) {
  22138. var BlackAndWhitePostProcess = (function (_super) {
  22139. __extends(BlackAndWhitePostProcess, _super);
  22140. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22141. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22142. }
  22143. return BlackAndWhitePostProcess;
  22144. })(BABYLON.PostProcess);
  22145. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22146. })(BABYLON || (BABYLON = {}));
  22147. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22148. var __extends = this.__extends || function (d, b) {
  22149. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22150. function __() { this.constructor = d; }
  22151. __.prototype = b.prototype;
  22152. d.prototype = new __();
  22153. };
  22154. var BABYLON;
  22155. (function (BABYLON) {
  22156. var ConvolutionPostProcess = (function (_super) {
  22157. __extends(ConvolutionPostProcess, _super);
  22158. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22159. var _this = this;
  22160. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22161. this.kernel = kernel;
  22162. this.onApply = function (effect) {
  22163. effect.setFloat2("screenSize", _this.width, _this.height);
  22164. effect.setArray("kernel", _this.kernel);
  22165. };
  22166. }
  22167. // Statics
  22168. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22169. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22170. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22171. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22172. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22173. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22174. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22175. return ConvolutionPostProcess;
  22176. })(BABYLON.PostProcess);
  22177. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22178. })(BABYLON || (BABYLON = {}));
  22179. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22180. var __extends = this.__extends || function (d, b) {
  22181. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22182. function __() { this.constructor = d; }
  22183. __.prototype = b.prototype;
  22184. d.prototype = new __();
  22185. };
  22186. var BABYLON;
  22187. (function (BABYLON) {
  22188. var FilterPostProcess = (function (_super) {
  22189. __extends(FilterPostProcess, _super);
  22190. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22191. var _this = this;
  22192. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22193. this.kernelMatrix = kernelMatrix;
  22194. this.onApply = function (effect) {
  22195. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22196. };
  22197. }
  22198. return FilterPostProcess;
  22199. })(BABYLON.PostProcess);
  22200. BABYLON.FilterPostProcess = FilterPostProcess;
  22201. })(BABYLON || (BABYLON = {}));
  22202. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22203. var __extends = this.__extends || function (d, b) {
  22204. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22205. function __() { this.constructor = d; }
  22206. __.prototype = b.prototype;
  22207. d.prototype = new __();
  22208. };
  22209. var BABYLON;
  22210. (function (BABYLON) {
  22211. var FxaaPostProcess = (function (_super) {
  22212. __extends(FxaaPostProcess, _super);
  22213. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22214. var _this = this;
  22215. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22216. this.onSizeChanged = function () {
  22217. _this.texelWidth = 1.0 / _this.width;
  22218. _this.texelHeight = 1.0 / _this.height;
  22219. };
  22220. this.onApply = function (effect) {
  22221. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22222. };
  22223. }
  22224. return FxaaPostProcess;
  22225. })(BABYLON.PostProcess);
  22226. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22227. })(BABYLON || (BABYLON = {}));
  22228. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22229. var __extends = this.__extends || function (d, b) {
  22230. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22231. function __() { this.constructor = d; }
  22232. __.prototype = b.prototype;
  22233. d.prototype = new __();
  22234. };
  22235. var BABYLON;
  22236. (function (BABYLON) {
  22237. var StereogramInterlacePostProcess = (function (_super) {
  22238. __extends(StereogramInterlacePostProcess, _super);
  22239. function StereogramInterlacePostProcess(name, camB, postProcessA, isStereogramHoriz, samplingMode) {
  22240. var _this = this;
  22241. _super.call(this, name, "stereogramInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereogramHoriz ? "#define IS_STEREOGRAM_HORIZ 1" : undefined);
  22242. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22243. this.onSizeChanged = function () {
  22244. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22245. };
  22246. this.onApply = function (effect) {
  22247. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22248. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22249. };
  22250. }
  22251. return StereogramInterlacePostProcess;
  22252. })(BABYLON.PostProcess);
  22253. BABYLON.StereogramInterlacePostProcess = StereogramInterlacePostProcess;
  22254. })(BABYLON || (BABYLON = {}));
  22255. //# sourceMappingURL=babylon.stereogramInterlacePostProcess.js.map
  22256. var BABYLON;
  22257. (function (BABYLON) {
  22258. var LensFlare = (function () {
  22259. function LensFlare(size, position, color, imgUrl, system) {
  22260. this.size = size;
  22261. this.position = position;
  22262. this.dispose = function () {
  22263. if (this.texture) {
  22264. this.texture.dispose();
  22265. }
  22266. // Remove from scene
  22267. var index = this._system.lensFlares.indexOf(this);
  22268. this._system.lensFlares.splice(index, 1);
  22269. };
  22270. this.color = color || new BABYLON.Color3(1, 1, 1);
  22271. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22272. this._system = system;
  22273. system.lensFlares.push(this);
  22274. }
  22275. return LensFlare;
  22276. })();
  22277. BABYLON.LensFlare = LensFlare;
  22278. })(BABYLON || (BABYLON = {}));
  22279. //# sourceMappingURL=babylon.lensFlare.js.map
  22280. var BABYLON;
  22281. (function (BABYLON) {
  22282. var LensFlareSystem = (function () {
  22283. function LensFlareSystem(name, emitter, scene) {
  22284. this.name = name;
  22285. this.lensFlares = new Array();
  22286. this.borderLimit = 300;
  22287. this._vertexDeclaration = [2];
  22288. this._vertexStrideSize = 2 * 4;
  22289. this._isEnabled = true;
  22290. this._scene = scene;
  22291. this._emitter = emitter;
  22292. scene.lensFlareSystems.push(this);
  22293. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22294. // VBO
  22295. var vertices = [];
  22296. vertices.push(1, 1);
  22297. vertices.push(-1, 1);
  22298. vertices.push(-1, -1);
  22299. vertices.push(1, -1);
  22300. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22301. // Indices
  22302. var indices = [];
  22303. indices.push(0);
  22304. indices.push(1);
  22305. indices.push(2);
  22306. indices.push(0);
  22307. indices.push(2);
  22308. indices.push(3);
  22309. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22310. // Effects
  22311. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22312. }
  22313. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22314. get: function () {
  22315. return this._isEnabled;
  22316. },
  22317. set: function (value) {
  22318. this._isEnabled = value;
  22319. },
  22320. enumerable: true,
  22321. configurable: true
  22322. });
  22323. LensFlareSystem.prototype.getScene = function () {
  22324. return this._scene;
  22325. };
  22326. LensFlareSystem.prototype.getEmitter = function () {
  22327. return this._emitter;
  22328. };
  22329. LensFlareSystem.prototype.getEmitterPosition = function () {
  22330. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22331. };
  22332. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22333. var position = this.getEmitterPosition();
  22334. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22335. this._positionX = position.x;
  22336. this._positionY = position.y;
  22337. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22338. if (position.z > 0) {
  22339. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22340. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22341. return true;
  22342. }
  22343. }
  22344. return false;
  22345. };
  22346. LensFlareSystem.prototype._isVisible = function () {
  22347. if (!this._isEnabled) {
  22348. return false;
  22349. }
  22350. var emitterPosition = this.getEmitterPosition();
  22351. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22352. var distance = direction.length();
  22353. direction.normalize();
  22354. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22355. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22356. return !pickInfo.hit || pickInfo.distance > distance;
  22357. };
  22358. LensFlareSystem.prototype.render = function () {
  22359. if (!this._effect.isReady())
  22360. return false;
  22361. var engine = this._scene.getEngine();
  22362. var viewport = this._scene.activeCamera.viewport;
  22363. var globalViewport = viewport.toGlobal(engine);
  22364. // Position
  22365. if (!this.computeEffectivePosition(globalViewport)) {
  22366. return false;
  22367. }
  22368. // Visibility
  22369. if (!this._isVisible()) {
  22370. return false;
  22371. }
  22372. // Intensity
  22373. var awayX;
  22374. var awayY;
  22375. if (this._positionX < this.borderLimit + globalViewport.x) {
  22376. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22377. }
  22378. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22379. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22380. }
  22381. else {
  22382. awayX = 0;
  22383. }
  22384. if (this._positionY < this.borderLimit + globalViewport.y) {
  22385. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22386. }
  22387. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22388. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22389. }
  22390. else {
  22391. awayY = 0;
  22392. }
  22393. var away = (awayX > awayY) ? awayX : awayY;
  22394. if (away > this.borderLimit) {
  22395. away = this.borderLimit;
  22396. }
  22397. var intensity = 1.0 - (away / this.borderLimit);
  22398. if (intensity < 0) {
  22399. return false;
  22400. }
  22401. if (intensity > 1.0) {
  22402. intensity = 1.0;
  22403. }
  22404. // Position
  22405. var centerX = globalViewport.x + globalViewport.width / 2;
  22406. var centerY = globalViewport.y + globalViewport.height / 2;
  22407. var distX = centerX - this._positionX;
  22408. var distY = centerY - this._positionY;
  22409. // Effects
  22410. engine.enableEffect(this._effect);
  22411. engine.setState(false);
  22412. engine.setDepthBuffer(false);
  22413. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22414. // VBOs
  22415. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22416. // Flares
  22417. for (var index = 0; index < this.lensFlares.length; index++) {
  22418. var flare = this.lensFlares[index];
  22419. var x = centerX - (distX * flare.position);
  22420. var y = centerY - (distY * flare.position);
  22421. var cw = flare.size;
  22422. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22423. var cx = 2 * (x / globalViewport.width) - 1.0;
  22424. var cy = 1.0 - 2 * (y / globalViewport.height);
  22425. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22426. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22427. // Texture
  22428. this._effect.setTexture("textureSampler", flare.texture);
  22429. // Color
  22430. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22431. // Draw order
  22432. engine.draw(true, 0, 6);
  22433. }
  22434. engine.setDepthBuffer(true);
  22435. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22436. return true;
  22437. };
  22438. LensFlareSystem.prototype.dispose = function () {
  22439. if (this._vertexBuffer) {
  22440. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22441. this._vertexBuffer = null;
  22442. }
  22443. if (this._indexBuffer) {
  22444. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22445. this._indexBuffer = null;
  22446. }
  22447. while (this.lensFlares.length) {
  22448. this.lensFlares[0].dispose();
  22449. }
  22450. // Remove from scene
  22451. var index = this._scene.lensFlareSystems.indexOf(this);
  22452. this._scene.lensFlareSystems.splice(index, 1);
  22453. };
  22454. return LensFlareSystem;
  22455. })();
  22456. BABYLON.LensFlareSystem = LensFlareSystem;
  22457. })(BABYLON || (BABYLON = {}));
  22458. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22459. var BABYLON;
  22460. (function (BABYLON) {
  22461. var CannonJSPlugin = (function () {
  22462. function CannonJSPlugin() {
  22463. this._registeredMeshes = [];
  22464. this._physicsMaterials = [];
  22465. this.updateBodyPosition = function (mesh) {
  22466. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22467. var registeredMesh = this._registeredMeshes[index];
  22468. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22469. var body = registeredMesh.body;
  22470. var center = mesh.getBoundingInfo().boundingBox.center;
  22471. body.position.set(center.x, center.z, center.y);
  22472. body.quaternion.x = mesh.rotationQuaternion.x;
  22473. body.quaternion.z = mesh.rotationQuaternion.y;
  22474. body.quaternion.y = mesh.rotationQuaternion.z;
  22475. body.quaternion.w = -mesh.rotationQuaternion.w;
  22476. return;
  22477. }
  22478. }
  22479. };
  22480. }
  22481. CannonJSPlugin.prototype.initialize = function (iterations) {
  22482. if (iterations === void 0) { iterations = 10; }
  22483. this._world = new CANNON.World();
  22484. this._world.broadphase = new CANNON.NaiveBroadphase();
  22485. this._world.solver.iterations = iterations;
  22486. };
  22487. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22488. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22489. };
  22490. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22491. this._world.step(delta);
  22492. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22493. var registeredMesh = this._registeredMeshes[index];
  22494. if (registeredMesh.isChild) {
  22495. continue;
  22496. }
  22497. // Body position
  22498. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22499. var deltaPos = registeredMesh.delta;
  22500. if (deltaPos) {
  22501. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22502. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22503. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22504. }
  22505. else {
  22506. registeredMesh.mesh.position.x = bodyX;
  22507. registeredMesh.mesh.position.y = bodyZ;
  22508. registeredMesh.mesh.position.z = bodyY;
  22509. }
  22510. if (!registeredMesh.mesh.rotationQuaternion) {
  22511. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22512. }
  22513. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22514. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22515. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22516. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22517. }
  22518. };
  22519. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22520. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22521. };
  22522. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22523. this.unregisterMesh(mesh);
  22524. mesh.computeWorldMatrix(true);
  22525. switch (impostor) {
  22526. case BABYLON.PhysicsEngine.SphereImpostor:
  22527. var bbox = mesh.getBoundingInfo().boundingBox;
  22528. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22529. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22530. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22531. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22532. case BABYLON.PhysicsEngine.BoxImpostor:
  22533. bbox = mesh.getBoundingInfo().boundingBox;
  22534. var min = bbox.minimumWorld;
  22535. var max = bbox.maximumWorld;
  22536. var box = max.subtract(min).scale(0.5);
  22537. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22538. case BABYLON.PhysicsEngine.PlaneImpostor:
  22539. return this._createPlane(mesh, options);
  22540. case BABYLON.PhysicsEngine.MeshImpostor:
  22541. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22542. var rawFaces = mesh.getIndices();
  22543. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22544. }
  22545. return null;
  22546. };
  22547. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22548. var shape = new CANNON.Sphere(radius);
  22549. if (!options) {
  22550. return shape;
  22551. }
  22552. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22553. };
  22554. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22555. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22556. if (!options) {
  22557. return shape;
  22558. }
  22559. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22560. };
  22561. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22562. var shape = new CANNON.Plane();
  22563. if (!options) {
  22564. return shape;
  22565. }
  22566. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22567. };
  22568. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22569. var verts = [], faces = [];
  22570. mesh.computeWorldMatrix(true);
  22571. // Get vertices
  22572. for (var i = 0; i < rawVerts.length; i += 3) {
  22573. var transformed = BABYLON.Vector3.Zero();
  22574. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22575. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22576. }
  22577. // Get faces
  22578. for (var j = 0; j < rawFaces.length; j += 3) {
  22579. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22580. }
  22581. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22582. if (!options) {
  22583. return shape;
  22584. }
  22585. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22586. };
  22587. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22588. var index;
  22589. var mat;
  22590. for (index = 0; index < this._physicsMaterials.length; index++) {
  22591. mat = this._physicsMaterials[index];
  22592. if (mat.friction === friction && mat.restitution === restitution) {
  22593. return mat;
  22594. }
  22595. }
  22596. var currentMat = new CANNON.Material();
  22597. currentMat.friction = friction;
  22598. currentMat.restitution = restitution;
  22599. this._physicsMaterials.push(currentMat);
  22600. for (index = 0; index < this._physicsMaterials.length; index++) {
  22601. mat = this._physicsMaterials[index];
  22602. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22603. contactMaterial.contactEquationStiffness = 1e10;
  22604. contactMaterial.contactEquationRegularizationTime = 10;
  22605. this._world.addContactMaterial(contactMaterial);
  22606. }
  22607. return currentMat;
  22608. };
  22609. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22610. var initialRotation = null;
  22611. if (mesh.rotationQuaternion) {
  22612. initialRotation = mesh.rotationQuaternion.clone();
  22613. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22614. }
  22615. // The delta between the mesh position and the mesh bounding box center
  22616. var bbox = mesh.getBoundingInfo().boundingBox;
  22617. var deltaPosition = mesh.position.subtract(bbox.center);
  22618. var material = this._addMaterial(friction, restitution);
  22619. var body = new CANNON.RigidBody(mass, shape, material);
  22620. if (initialRotation) {
  22621. body.quaternion.x = initialRotation.x;
  22622. body.quaternion.z = initialRotation.y;
  22623. body.quaternion.y = initialRotation.z;
  22624. body.quaternion.w = -initialRotation.w;
  22625. }
  22626. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22627. this._world.add(body);
  22628. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22629. return body;
  22630. };
  22631. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22632. var compoundShape = new CANNON.Compound();
  22633. for (var index = 0; index < parts.length; index++) {
  22634. var mesh = parts[index].mesh;
  22635. var shape = this.registerMesh(mesh, parts[index].impostor);
  22636. if (index == 0) {
  22637. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22638. }
  22639. else {
  22640. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22641. }
  22642. }
  22643. var initialMesh = parts[0].mesh;
  22644. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22645. body.parts = parts;
  22646. return body;
  22647. };
  22648. CannonJSPlugin.prototype._unbindBody = function (body) {
  22649. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22650. var registeredMesh = this._registeredMeshes[index];
  22651. if (registeredMesh.body === body) {
  22652. registeredMesh.body = null;
  22653. registeredMesh.delta = 0;
  22654. }
  22655. }
  22656. };
  22657. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22658. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22659. var registeredMesh = this._registeredMeshes[index];
  22660. if (registeredMesh.mesh === mesh) {
  22661. // Remove body
  22662. if (registeredMesh.body) {
  22663. this._world.remove(registeredMesh.body);
  22664. this._unbindBody(registeredMesh.body);
  22665. }
  22666. this._registeredMeshes.splice(index, 1);
  22667. return;
  22668. }
  22669. }
  22670. };
  22671. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22672. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22673. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22674. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22675. var registeredMesh = this._registeredMeshes[index];
  22676. if (registeredMesh.mesh === mesh) {
  22677. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22678. return;
  22679. }
  22680. }
  22681. };
  22682. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22683. var body1 = null, body2 = null;
  22684. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22685. var registeredMesh = this._registeredMeshes[index];
  22686. if (registeredMesh.mesh === mesh1) {
  22687. body1 = registeredMesh.body;
  22688. }
  22689. else if (registeredMesh.mesh === mesh2) {
  22690. body2 = registeredMesh.body;
  22691. }
  22692. }
  22693. if (!body1 || !body2) {
  22694. return false;
  22695. }
  22696. 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));
  22697. this._world.addConstraint(constraint);
  22698. return true;
  22699. };
  22700. CannonJSPlugin.prototype.dispose = function () {
  22701. while (this._registeredMeshes.length) {
  22702. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22703. }
  22704. };
  22705. CannonJSPlugin.prototype.isSupported = function () {
  22706. return window.CANNON !== undefined;
  22707. };
  22708. return CannonJSPlugin;
  22709. })();
  22710. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22711. })(BABYLON || (BABYLON = {}));
  22712. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22713. var BABYLON;
  22714. (function (BABYLON) {
  22715. var OimoJSPlugin = (function () {
  22716. function OimoJSPlugin() {
  22717. this._registeredMeshes = [];
  22718. /**
  22719. * Update the body position according to the mesh position
  22720. * @param mesh
  22721. */
  22722. this.updateBodyPosition = function (mesh) {
  22723. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22724. var registeredMesh = this._registeredMeshes[index];
  22725. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22726. var body = registeredMesh.body.body;
  22727. mesh.computeWorldMatrix(true);
  22728. var center = mesh.getBoundingInfo().boundingBox.center;
  22729. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22730. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22731. body.sleeping = false;
  22732. return;
  22733. }
  22734. // Case where the parent has been updated
  22735. if (registeredMesh.mesh.parent === mesh) {
  22736. mesh.computeWorldMatrix(true);
  22737. registeredMesh.mesh.computeWorldMatrix(true);
  22738. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22739. var absoluteRotation = mesh.rotation;
  22740. body = registeredMesh.body.body;
  22741. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22742. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22743. body.sleeping = false;
  22744. return;
  22745. }
  22746. }
  22747. };
  22748. }
  22749. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22750. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22751. };
  22752. OimoJSPlugin.prototype.initialize = function (iterations) {
  22753. this._world = new OIMO.World();
  22754. this._world.clear();
  22755. };
  22756. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22757. this._world.gravity = gravity;
  22758. };
  22759. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22760. var body = null;
  22761. this.unregisterMesh(mesh);
  22762. mesh.computeWorldMatrix(true);
  22763. var initialRotation = null;
  22764. if (mesh.rotationQuaternion) {
  22765. initialRotation = mesh.rotationQuaternion.clone();
  22766. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22767. mesh.computeWorldMatrix(true);
  22768. }
  22769. var bbox = mesh.getBoundingInfo().boundingBox;
  22770. // The delta between the mesh position and the mesh bounding box center
  22771. var deltaPosition = mesh.position.subtract(bbox.center);
  22772. // Transform delta position with the rotation
  22773. if (initialRotation) {
  22774. var m = new BABYLON.Matrix();
  22775. initialRotation.toRotationMatrix(m);
  22776. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22777. }
  22778. // register mesh
  22779. switch (impostor) {
  22780. case BABYLON.PhysicsEngine.SphereImpostor:
  22781. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22782. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22783. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22784. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22785. body = new OIMO.Body({
  22786. type: 'sphere',
  22787. size: [size],
  22788. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22789. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22790. move: options.mass != 0,
  22791. config: [options.mass, options.friction, options.restitution],
  22792. world: this._world
  22793. });
  22794. break;
  22795. case BABYLON.PhysicsEngine.PlaneImpostor:
  22796. //Oimo "fakes" a cylinder as a box, so why don't we!
  22797. case BABYLON.PhysicsEngine.CylinderImpostor:
  22798. case BABYLON.PhysicsEngine.BoxImpostor:
  22799. var min = bbox.minimumWorld;
  22800. var max = bbox.maximumWorld;
  22801. var box = max.subtract(min);
  22802. var sizeX = this._checkWithEpsilon(box.x);
  22803. var sizeY = this._checkWithEpsilon(box.y);
  22804. var sizeZ = this._checkWithEpsilon(box.z);
  22805. body = new OIMO.Body({
  22806. type: 'box',
  22807. size: [sizeX, sizeY, sizeZ],
  22808. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22809. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22810. move: options.mass != 0,
  22811. config: [options.mass, options.friction, options.restitution],
  22812. world: this._world
  22813. });
  22814. break;
  22815. }
  22816. //If quaternion was set as the rotation of the object
  22817. if (initialRotation) {
  22818. //We have to access the rigid body's properties to set the quaternion.
  22819. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22820. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22821. //update the internal rotation matrix
  22822. body.body.syncShapes();
  22823. }
  22824. this._registeredMeshes.push({
  22825. mesh: mesh,
  22826. body: body,
  22827. delta: deltaPosition
  22828. });
  22829. return body;
  22830. };
  22831. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22832. var types = [], sizes = [], positions = [], rotations = [];
  22833. var initialMesh = parts[0].mesh;
  22834. for (var index = 0; index < parts.length; index++) {
  22835. var part = parts[index];
  22836. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22837. types.push(bodyParameters.type);
  22838. sizes.push.apply(sizes, bodyParameters.size);
  22839. positions.push.apply(positions, bodyParameters.pos);
  22840. rotations.push.apply(rotations, bodyParameters.rot);
  22841. }
  22842. var body = new OIMO.Body({
  22843. type: types,
  22844. size: sizes,
  22845. pos: positions,
  22846. rot: rotations,
  22847. move: options.mass != 0,
  22848. config: [options.mass, options.friction, options.restitution],
  22849. world: this._world
  22850. });
  22851. this._registeredMeshes.push({
  22852. mesh: initialMesh,
  22853. body: body
  22854. });
  22855. return body;
  22856. };
  22857. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22858. var bodyParameters = null;
  22859. var mesh = part.mesh;
  22860. // We need the bounding box/sphere info to compute the physics body
  22861. mesh.computeWorldMatrix();
  22862. switch (part.impostor) {
  22863. case BABYLON.PhysicsEngine.SphereImpostor:
  22864. var bbox = mesh.getBoundingInfo().boundingBox;
  22865. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22866. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22867. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22868. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22869. bodyParameters = {
  22870. type: 'sphere',
  22871. /* bug with oimo : sphere needs 3 sizes in this case */
  22872. size: [size, -1, -1],
  22873. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22874. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22875. };
  22876. break;
  22877. case BABYLON.PhysicsEngine.PlaneImpostor:
  22878. case BABYLON.PhysicsEngine.BoxImpostor:
  22879. bbox = mesh.getBoundingInfo().boundingBox;
  22880. var min = bbox.minimumWorld;
  22881. var max = bbox.maximumWorld;
  22882. var box = max.subtract(min);
  22883. var sizeX = this._checkWithEpsilon(box.x);
  22884. var sizeY = this._checkWithEpsilon(box.y);
  22885. var sizeZ = this._checkWithEpsilon(box.z);
  22886. var relativePosition = mesh.position;
  22887. bodyParameters = {
  22888. type: 'box',
  22889. size: [sizeX, sizeY, sizeZ],
  22890. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22891. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22892. };
  22893. break;
  22894. }
  22895. return bodyParameters;
  22896. };
  22897. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22898. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22899. var registeredMesh = this._registeredMeshes[index];
  22900. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22901. if (registeredMesh.body) {
  22902. this._world.removeRigidBody(registeredMesh.body.body);
  22903. this._unbindBody(registeredMesh.body);
  22904. }
  22905. this._registeredMeshes.splice(index, 1);
  22906. return;
  22907. }
  22908. }
  22909. };
  22910. OimoJSPlugin.prototype._unbindBody = function (body) {
  22911. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22912. var registeredMesh = this._registeredMeshes[index];
  22913. if (registeredMesh.body === body) {
  22914. registeredMesh.body = null;
  22915. }
  22916. }
  22917. };
  22918. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22919. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22920. var registeredMesh = this._registeredMeshes[index];
  22921. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22922. // Get object mass to have a behaviour similar to cannon.js
  22923. var mass = registeredMesh.body.body.massInfo.mass;
  22924. // The force is scaled with the mass of object
  22925. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22926. return;
  22927. }
  22928. }
  22929. };
  22930. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22931. var body1 = null, body2 = null;
  22932. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22933. var registeredMesh = this._registeredMeshes[index];
  22934. if (registeredMesh.mesh === mesh1) {
  22935. body1 = registeredMesh.body.body;
  22936. }
  22937. else if (registeredMesh.mesh === mesh2) {
  22938. body2 = registeredMesh.body.body;
  22939. }
  22940. }
  22941. if (!body1 || !body2) {
  22942. return false;
  22943. }
  22944. if (!options) {
  22945. options = {};
  22946. }
  22947. new OIMO.Link({
  22948. type: options.type,
  22949. body1: body1,
  22950. body2: body2,
  22951. min: options.min,
  22952. max: options.max,
  22953. axe1: options.axe1,
  22954. axe2: options.axe2,
  22955. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22956. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22957. collision: options.collision,
  22958. spring: options.spring,
  22959. world: this._world
  22960. });
  22961. return true;
  22962. };
  22963. OimoJSPlugin.prototype.dispose = function () {
  22964. this._world.clear();
  22965. while (this._registeredMeshes.length) {
  22966. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22967. }
  22968. };
  22969. OimoJSPlugin.prototype.isSupported = function () {
  22970. return OIMO !== undefined;
  22971. };
  22972. OimoJSPlugin.prototype._getLastShape = function (body) {
  22973. var lastShape = body.shapes;
  22974. while (lastShape.next) {
  22975. lastShape = lastShape.next;
  22976. }
  22977. return lastShape;
  22978. };
  22979. OimoJSPlugin.prototype.runOneStep = function (time) {
  22980. this._world.step();
  22981. // Update the position of all registered meshes
  22982. var i = this._registeredMeshes.length;
  22983. var m;
  22984. while (i--) {
  22985. var body = this._registeredMeshes[i].body.body;
  22986. var mesh = this._registeredMeshes[i].mesh;
  22987. var delta = this._registeredMeshes[i].delta;
  22988. if (!body.sleeping) {
  22989. if (body.shapes.next) {
  22990. var parentShape = this._getLastShape(body);
  22991. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22992. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22993. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22994. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22995. if (!mesh.rotationQuaternion) {
  22996. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22997. }
  22998. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22999. mesh.computeWorldMatrix();
  23000. }
  23001. else {
  23002. m = body.getMatrix();
  23003. mtx = BABYLON.Matrix.FromArray(m);
  23004. // Body position
  23005. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23006. if (!delta) {
  23007. mesh.position.x = bodyX;
  23008. mesh.position.y = bodyY;
  23009. mesh.position.z = bodyZ;
  23010. }
  23011. else {
  23012. mesh.position.x = bodyX + delta.x;
  23013. mesh.position.y = bodyY + delta.y;
  23014. mesh.position.z = bodyZ + delta.z;
  23015. }
  23016. if (!mesh.rotationQuaternion) {
  23017. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23018. }
  23019. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23020. mesh.computeWorldMatrix();
  23021. }
  23022. }
  23023. }
  23024. };
  23025. return OimoJSPlugin;
  23026. })();
  23027. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23028. })(BABYLON || (BABYLON = {}));
  23029. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  23030. var BABYLON;
  23031. (function (BABYLON) {
  23032. var PhysicsEngine = (function () {
  23033. function PhysicsEngine(plugin) {
  23034. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23035. }
  23036. PhysicsEngine.prototype._initialize = function (gravity) {
  23037. this._currentPlugin.initialize();
  23038. this._setGravity(gravity);
  23039. };
  23040. PhysicsEngine.prototype._runOneStep = function (delta) {
  23041. if (delta > 0.1) {
  23042. delta = 0.1;
  23043. }
  23044. else if (delta <= 0) {
  23045. delta = 1.0 / 60.0;
  23046. }
  23047. this._currentPlugin.runOneStep(delta);
  23048. };
  23049. PhysicsEngine.prototype._setGravity = function (gravity) {
  23050. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  23051. this._currentPlugin.setGravity(this.gravity);
  23052. };
  23053. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23054. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23055. };
  23056. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23057. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23058. };
  23059. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23060. this._currentPlugin.unregisterMesh(mesh);
  23061. };
  23062. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23063. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23064. };
  23065. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23066. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23067. };
  23068. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23069. this._currentPlugin.updateBodyPosition(mesh);
  23070. };
  23071. PhysicsEngine.prototype.dispose = function () {
  23072. this._currentPlugin.dispose();
  23073. };
  23074. PhysicsEngine.prototype.isSupported = function () {
  23075. return this._currentPlugin.isSupported();
  23076. };
  23077. // Statics
  23078. PhysicsEngine.NoImpostor = 0;
  23079. PhysicsEngine.SphereImpostor = 1;
  23080. PhysicsEngine.BoxImpostor = 2;
  23081. PhysicsEngine.PlaneImpostor = 3;
  23082. PhysicsEngine.MeshImpostor = 4;
  23083. PhysicsEngine.CapsuleImpostor = 5;
  23084. PhysicsEngine.ConeImpostor = 6;
  23085. PhysicsEngine.CylinderImpostor = 7;
  23086. PhysicsEngine.ConvexHullImpostor = 8;
  23087. PhysicsEngine.Epsilon = 0.001;
  23088. return PhysicsEngine;
  23089. })();
  23090. BABYLON.PhysicsEngine = PhysicsEngine;
  23091. })(BABYLON || (BABYLON = {}));
  23092. //# sourceMappingURL=babylon.physicsEngine.js.map
  23093. var BABYLON;
  23094. (function (BABYLON) {
  23095. var serializeLight = function (light) {
  23096. var serializationObject = {};
  23097. serializationObject.name = light.name;
  23098. serializationObject.id = light.id;
  23099. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23100. if (light instanceof BABYLON.PointLight) {
  23101. serializationObject.type = 0;
  23102. serializationObject.position = light.position.asArray();
  23103. }
  23104. else if (light instanceof BABYLON.DirectionalLight) {
  23105. serializationObject.type = 1;
  23106. var directionalLight = light;
  23107. serializationObject.position = directionalLight.position.asArray();
  23108. serializationObject.direction = directionalLight.direction.asArray();
  23109. }
  23110. else if (light instanceof BABYLON.SpotLight) {
  23111. serializationObject.type = 2;
  23112. var spotLight = light;
  23113. serializationObject.position = spotLight.position.asArray();
  23114. serializationObject.direction = spotLight.position.asArray();
  23115. serializationObject.angle = spotLight.angle;
  23116. serializationObject.exponent = spotLight.exponent;
  23117. }
  23118. else if (light instanceof BABYLON.HemisphericLight) {
  23119. serializationObject.type = 3;
  23120. var hemisphericLight = light;
  23121. serializationObject.direction = hemisphericLight.direction.asArray();
  23122. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23123. }
  23124. if (light.intensity) {
  23125. serializationObject.intensity = light.intensity;
  23126. }
  23127. serializationObject.range = light.range;
  23128. serializationObject.diffuse = light.diffuse.asArray();
  23129. serializationObject.specular = light.specular.asArray();
  23130. return serializationObject;
  23131. };
  23132. var serializeFresnelParameter = function (fresnelParameter) {
  23133. var serializationObject = {};
  23134. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23135. serializationObject.leftColor = fresnelParameter.leftColor;
  23136. serializationObject.rightColor = fresnelParameter.rightColor;
  23137. serializationObject.bias = fresnelParameter.bias;
  23138. serializationObject.power = fresnelParameter.power;
  23139. return serializationObject;
  23140. };
  23141. var appendAnimations = function (source, destination) {
  23142. if (source.animations) {
  23143. destination.animations = [];
  23144. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23145. var animation = source.animations[animationIndex];
  23146. destination.animations.push(serializeAnimation(animation));
  23147. }
  23148. }
  23149. };
  23150. var serializeCamera = function (camera) {
  23151. var serializationObject = {};
  23152. serializationObject.name = camera.name;
  23153. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23154. serializationObject.id = camera.id;
  23155. serializationObject.position = camera.position.asArray();
  23156. // Parent
  23157. if (camera.parent) {
  23158. serializationObject.parentId = camera.parent.id;
  23159. }
  23160. serializationObject.fov = camera.fov;
  23161. serializationObject.minZ = camera.minZ;
  23162. serializationObject.maxZ = camera.maxZ;
  23163. serializationObject.inertia = camera.inertia;
  23164. //setting the type
  23165. if (camera instanceof BABYLON.FreeCamera) {
  23166. serializationObject.type = "FreeCamera";
  23167. }
  23168. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23169. serializationObject.type = "ArcRotateCamera";
  23170. }
  23171. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23172. serializationObject.type = "AnaglyphArcRotateCamera";
  23173. }
  23174. else if (camera instanceof BABYLON.GamepadCamera) {
  23175. serializationObject.type = "GamepadCamera";
  23176. }
  23177. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23178. serializationObject.type = "AnaglyphFreeCamera";
  23179. }
  23180. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23181. serializationObject.type = "DeviceOrientationCamera";
  23182. }
  23183. else if (camera instanceof BABYLON.FollowCamera) {
  23184. serializationObject.type = "FollowCamera";
  23185. }
  23186. else if (camera instanceof BABYLON.TouchCamera) {
  23187. serializationObject.type = "TouchCamera";
  23188. }
  23189. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23190. serializationObject.type = "VirtualJoysticksCamera";
  23191. }
  23192. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23193. serializationObject.type = "WebVRFreeCamera";
  23194. }
  23195. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23196. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23197. }
  23198. //special properties of specific cameras
  23199. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23200. var arcCamera = camera;
  23201. serializationObject.alpha = arcCamera.alpha;
  23202. serializationObject.beta = arcCamera.beta;
  23203. serializationObject.radius = arcCamera.radius;
  23204. if (arcCamera.target && arcCamera.target.id) {
  23205. serializationObject.lockedTargetId = arcCamera.target.id;
  23206. }
  23207. }
  23208. else if (camera instanceof BABYLON.FollowCamera) {
  23209. var followCam = camera;
  23210. serializationObject.radius = followCam.radius;
  23211. serializationObject.heightOffset = followCam.heightOffset;
  23212. serializationObject.rotationOffset = followCam.rotationOffset;
  23213. }
  23214. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23215. //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.
  23216. if (camera['_eyeSpace'] !== undefined) {
  23217. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23218. }
  23219. }
  23220. //general properties that not all cameras have. The [] is due to typescript's type safety
  23221. if (camera['speed'] !== undefined) {
  23222. serializationObject.speed = camera['speed'];
  23223. }
  23224. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23225. serializationObject.target = camera['target'].asArray();
  23226. }
  23227. // Target
  23228. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23229. serializationObject.rotation = camera['rotation'].asArray();
  23230. }
  23231. // Locked target
  23232. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23233. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23234. }
  23235. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23236. serializationObject.applyGravity = camera['applyGravity'] || false;
  23237. if (camera['ellipsoid']) {
  23238. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23239. }
  23240. // Animations
  23241. appendAnimations(camera, serializationObject);
  23242. // Layer mask
  23243. serializationObject.layerMask = camera.layerMask;
  23244. return serializationObject;
  23245. };
  23246. var serializeAnimation = function (animation) {
  23247. var serializationObject = {};
  23248. serializationObject.name = animation.name;
  23249. serializationObject.property = animation.targetProperty;
  23250. serializationObject.framePerSecond = animation.framePerSecond;
  23251. serializationObject.dataType = animation.dataType;
  23252. serializationObject.loopBehavior = animation.loopMode;
  23253. var dataType = animation.dataType;
  23254. serializationObject.keys = [];
  23255. var keys = animation.getKeys();
  23256. for (var index = 0; index < keys.length; index++) {
  23257. var animationKey = keys[index];
  23258. var key = {};
  23259. key.frame = animationKey.frame;
  23260. switch (dataType) {
  23261. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23262. key.values = [animationKey.value];
  23263. break;
  23264. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23265. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23266. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23267. key.values = animationKey.value.asArray();
  23268. break;
  23269. }
  23270. serializationObject.keys.push(key);
  23271. }
  23272. return serializationObject;
  23273. };
  23274. var serializeMultiMaterial = function (material) {
  23275. var serializationObject = {};
  23276. serializationObject.name = material.name;
  23277. serializationObject.id = material.id;
  23278. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23279. serializationObject.materials = [];
  23280. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23281. var subMat = material.subMaterials[matIndex];
  23282. if (subMat) {
  23283. serializationObject.materials.push(subMat.id);
  23284. }
  23285. else {
  23286. serializationObject.materials.push(null);
  23287. }
  23288. }
  23289. return serializationObject;
  23290. };
  23291. var serializeMaterial = function (material) {
  23292. var serializationObject = {};
  23293. serializationObject.name = material.name;
  23294. serializationObject.ambient = material.ambientColor.asArray();
  23295. serializationObject.diffuse = material.diffuseColor.asArray();
  23296. serializationObject.specular = material.specularColor.asArray();
  23297. serializationObject.specularPower = material.specularPower;
  23298. serializationObject.emissive = material.emissiveColor.asArray();
  23299. serializationObject.alpha = material.alpha;
  23300. serializationObject.id = material.id;
  23301. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23302. serializationObject.backFaceCulling = material.backFaceCulling;
  23303. if (material.diffuseTexture) {
  23304. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23305. }
  23306. if (material.diffuseFresnelParameters) {
  23307. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23308. }
  23309. if (material.ambientTexture) {
  23310. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23311. }
  23312. if (material.opacityTexture) {
  23313. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23314. }
  23315. if (material.opacityFresnelParameters) {
  23316. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23317. }
  23318. if (material.reflectionTexture) {
  23319. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23320. }
  23321. if (material.reflectionFresnelParameters) {
  23322. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23323. }
  23324. if (material.emissiveTexture) {
  23325. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23326. }
  23327. if (material.emissiveFresnelParameters) {
  23328. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23329. }
  23330. if (material.specularTexture) {
  23331. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23332. }
  23333. if (material.bumpTexture) {
  23334. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23335. }
  23336. return serializationObject;
  23337. };
  23338. var serializeTexture = function (texture) {
  23339. var serializationObject = {};
  23340. if (!texture.name) {
  23341. return null;
  23342. }
  23343. if (texture instanceof BABYLON.CubeTexture) {
  23344. serializationObject.name = texture.name;
  23345. serializationObject.hasAlpha = texture.hasAlpha;
  23346. serializationObject.level = texture.level;
  23347. serializationObject.coordinatesMode = texture.coordinatesMode;
  23348. return serializationObject;
  23349. }
  23350. if (texture instanceof BABYLON.MirrorTexture) {
  23351. var mirrorTexture = texture;
  23352. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23353. serializationObject.renderList = [];
  23354. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23355. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23356. }
  23357. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23358. }
  23359. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23360. var renderTargetTexture = texture;
  23361. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23362. serializationObject.renderList = [];
  23363. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23364. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23365. }
  23366. }
  23367. var regularTexture = texture;
  23368. serializationObject.name = texture.name;
  23369. serializationObject.hasAlpha = texture.hasAlpha;
  23370. serializationObject.level = texture.level;
  23371. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23372. serializationObject.coordinatesMode = texture.coordinatesMode;
  23373. serializationObject.uOffset = regularTexture.uOffset;
  23374. serializationObject.vOffset = regularTexture.vOffset;
  23375. serializationObject.uScale = regularTexture.uScale;
  23376. serializationObject.vScale = regularTexture.vScale;
  23377. serializationObject.uAng = regularTexture.uAng;
  23378. serializationObject.vAng = regularTexture.vAng;
  23379. serializationObject.wAng = regularTexture.wAng;
  23380. serializationObject.wrapU = texture.wrapU;
  23381. serializationObject.wrapV = texture.wrapV;
  23382. // Animations
  23383. appendAnimations(texture, serializationObject);
  23384. return serializationObject;
  23385. };
  23386. var serializeSkeleton = function (skeleton) {
  23387. var serializationObject = {};
  23388. serializationObject.name = skeleton.name;
  23389. serializationObject.id = skeleton.id;
  23390. serializationObject.bones = [];
  23391. for (var index = 0; index < skeleton.bones.length; index++) {
  23392. var bone = skeleton.bones[index];
  23393. var serializedBone = {
  23394. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23395. name: bone.name,
  23396. matrix: bone.getLocalMatrix().toArray()
  23397. };
  23398. serializationObject.bones.push(serializedBone);
  23399. if (bone.animations && bone.animations.length > 0) {
  23400. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23401. }
  23402. }
  23403. return serializationObject;
  23404. };
  23405. var serializeParticleSystem = function (particleSystem) {
  23406. var serializationObject = {};
  23407. serializationObject.emitterId = particleSystem.emitter.id;
  23408. serializationObject.capacity = particleSystem.getCapacity();
  23409. if (particleSystem.particleTexture) {
  23410. serializationObject.textureName = particleSystem.particleTexture.name;
  23411. }
  23412. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23413. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23414. serializationObject.minSize = particleSystem.minSize;
  23415. serializationObject.maxSize = particleSystem.maxSize;
  23416. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23417. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23418. serializationObject.emitRate = particleSystem.emitRate;
  23419. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23420. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23421. serializationObject.gravity = particleSystem.gravity.asArray();
  23422. serializationObject.direction1 = particleSystem.direction1.asArray();
  23423. serializationObject.direction2 = particleSystem.direction2.asArray();
  23424. serializationObject.color1 = particleSystem.color1.asArray();
  23425. serializationObject.color2 = particleSystem.color2.asArray();
  23426. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23427. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23428. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23429. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23430. serializationObject.blendMode = particleSystem.blendMode;
  23431. return serializationObject;
  23432. };
  23433. var serializeLensFlareSystem = function (lensFlareSystem) {
  23434. var serializationObject = {};
  23435. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23436. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23437. serializationObject.flares = [];
  23438. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23439. var flare = lensFlareSystem.lensFlares[index];
  23440. serializationObject.flares.push({
  23441. size: flare.size,
  23442. position: flare.position,
  23443. color: flare.color.asArray(),
  23444. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23445. });
  23446. }
  23447. return serializationObject;
  23448. };
  23449. var serializeShadowGenerator = function (light) {
  23450. var serializationObject = {};
  23451. var shadowGenerator = light.getShadowGenerator();
  23452. serializationObject.lightId = light.id;
  23453. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23454. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23455. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23456. serializationObject.renderList = [];
  23457. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23458. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23459. serializationObject.renderList.push(mesh.id);
  23460. }
  23461. return serializationObject;
  23462. };
  23463. var serializedGeometries = [];
  23464. var serializeGeometry = function (geometry, serializationGeometries) {
  23465. if (serializedGeometries[geometry.id]) {
  23466. return;
  23467. }
  23468. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23469. serializationGeometries.boxes.push(serializeBox(geometry));
  23470. }
  23471. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23472. serializationGeometries.spheres.push(serializeSphere(geometry));
  23473. }
  23474. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23475. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23476. }
  23477. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23478. serializationGeometries.toruses.push(serializeTorus(geometry));
  23479. }
  23480. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23481. serializationGeometries.grounds.push(serializeGround(geometry));
  23482. }
  23483. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23484. serializationGeometries.planes.push(serializePlane(geometry));
  23485. }
  23486. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23487. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23488. }
  23489. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23490. throw new Error("Unknow primitive type");
  23491. }
  23492. else {
  23493. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23494. }
  23495. serializedGeometries[geometry.id] = true;
  23496. };
  23497. var serializeGeometryBase = function (geometry) {
  23498. var serializationObject = {};
  23499. serializationObject.id = geometry.id;
  23500. if (BABYLON.Tags.HasTags(geometry)) {
  23501. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23502. }
  23503. return serializationObject;
  23504. };
  23505. var serializeVertexData = function (vertexData) {
  23506. var serializationObject = serializeGeometryBase(vertexData);
  23507. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23508. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23509. }
  23510. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23511. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23512. }
  23513. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23514. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23515. }
  23516. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23517. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23518. }
  23519. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23520. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23521. }
  23522. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23523. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23524. serializationObject.matricesIndices._isExpanded = true;
  23525. }
  23526. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23527. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23528. }
  23529. serializationObject.indices = vertexData.getIndices();
  23530. return serializationObject;
  23531. };
  23532. var serializePrimitive = function (primitive) {
  23533. var serializationObject = serializeGeometryBase(primitive);
  23534. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23535. return serializationObject;
  23536. };
  23537. var serializeBox = function (box) {
  23538. var serializationObject = serializePrimitive(box);
  23539. serializationObject.size = box.size;
  23540. return serializationObject;
  23541. };
  23542. var serializeSphere = function (sphere) {
  23543. var serializationObject = serializePrimitive(sphere);
  23544. serializationObject.segments = sphere.segments;
  23545. serializationObject.diameter = sphere.diameter;
  23546. return serializationObject;
  23547. };
  23548. var serializeCylinder = function (cylinder) {
  23549. var serializationObject = serializePrimitive(cylinder);
  23550. serializationObject.height = cylinder.height;
  23551. serializationObject.diameterTop = cylinder.diameterTop;
  23552. serializationObject.diameterBottom = cylinder.diameterBottom;
  23553. serializationObject.tessellation = cylinder.tessellation;
  23554. return serializationObject;
  23555. };
  23556. var serializeTorus = function (torus) {
  23557. var serializationObject = serializePrimitive(torus);
  23558. serializationObject.diameter = torus.diameter;
  23559. serializationObject.thickness = torus.thickness;
  23560. serializationObject.tessellation = torus.tessellation;
  23561. return serializationObject;
  23562. };
  23563. var serializeGround = function (ground) {
  23564. var serializationObject = serializePrimitive(ground);
  23565. serializationObject.width = ground.width;
  23566. serializationObject.height = ground.height;
  23567. serializationObject.subdivisions = ground.subdivisions;
  23568. return serializationObject;
  23569. };
  23570. var serializePlane = function (plane) {
  23571. var serializationObject = serializePrimitive(plane);
  23572. serializationObject.size = plane.size;
  23573. return serializationObject;
  23574. };
  23575. var serializeTorusKnot = function (torusKnot) {
  23576. var serializationObject = serializePrimitive(torusKnot);
  23577. serializationObject.radius = torusKnot.radius;
  23578. serializationObject.tube = torusKnot.tube;
  23579. serializationObject.radialSegments = torusKnot.radialSegments;
  23580. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23581. serializationObject.p = torusKnot.p;
  23582. serializationObject.q = torusKnot.q;
  23583. return serializationObject;
  23584. };
  23585. var serializeMesh = function (mesh, serializationScene) {
  23586. var serializationObject = {};
  23587. serializationObject.name = mesh.name;
  23588. serializationObject.id = mesh.id;
  23589. if (BABYLON.Tags.HasTags(mesh)) {
  23590. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23591. }
  23592. serializationObject.position = mesh.position.asArray();
  23593. if (mesh.rotationQuaternion) {
  23594. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23595. }
  23596. else if (mesh.rotation) {
  23597. serializationObject.rotation = mesh.rotation.asArray();
  23598. }
  23599. serializationObject.scaling = mesh.scaling.asArray();
  23600. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23601. serializationObject.isEnabled = mesh.isEnabled();
  23602. serializationObject.isVisible = mesh.isVisible;
  23603. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23604. serializationObject.pickable = mesh.isPickable;
  23605. serializationObject.receiveShadows = mesh.receiveShadows;
  23606. serializationObject.billboardMode = mesh.billboardMode;
  23607. serializationObject.visibility = mesh.visibility;
  23608. serializationObject.checkCollisions = mesh.checkCollisions;
  23609. // Parent
  23610. if (mesh.parent) {
  23611. serializationObject.parentId = mesh.parent.id;
  23612. }
  23613. // Geometry
  23614. var geometry = mesh._geometry;
  23615. if (geometry) {
  23616. var geometryId = geometry.id;
  23617. serializationObject.geometryId = geometryId;
  23618. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23619. // 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
  23620. serializeGeometry(geometry, serializationScene.geometries);
  23621. }
  23622. // SubMeshes
  23623. serializationObject.subMeshes = [];
  23624. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23625. var subMesh = mesh.subMeshes[subIndex];
  23626. serializationObject.subMeshes.push({
  23627. materialIndex: subMesh.materialIndex,
  23628. verticesStart: subMesh.verticesStart,
  23629. verticesCount: subMesh.verticesCount,
  23630. indexStart: subMesh.indexStart,
  23631. indexCount: subMesh.indexCount
  23632. });
  23633. }
  23634. }
  23635. // Material
  23636. if (mesh.material) {
  23637. serializationObject.materialId = mesh.material.id;
  23638. }
  23639. else {
  23640. mesh.material = null;
  23641. }
  23642. // Skeleton
  23643. if (mesh.skeleton) {
  23644. serializationObject.skeletonId = mesh.skeleton.id;
  23645. }
  23646. // Physics
  23647. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23648. serializationObject.physicsMass = mesh.getPhysicsMass();
  23649. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23650. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23651. switch (mesh.getPhysicsImpostor()) {
  23652. case BABYLON.PhysicsEngine.BoxImpostor:
  23653. serializationObject.physicsImpostor = 1;
  23654. break;
  23655. case BABYLON.PhysicsEngine.SphereImpostor:
  23656. serializationObject.physicsImpostor = 2;
  23657. break;
  23658. }
  23659. }
  23660. // Instances
  23661. serializationObject.instances = [];
  23662. for (var index = 0; index < mesh.instances.length; index++) {
  23663. var instance = mesh.instances[index];
  23664. var serializationInstance = {
  23665. name: instance.name,
  23666. position: instance.position,
  23667. rotation: instance.rotation,
  23668. rotationQuaternion: instance.rotationQuaternion,
  23669. scaling: instance.scaling
  23670. };
  23671. serializationObject.instances.push(serializationInstance);
  23672. // Animations
  23673. appendAnimations(instance, serializationInstance);
  23674. }
  23675. // Animations
  23676. appendAnimations(mesh, serializationObject);
  23677. // Layer mask
  23678. serializationObject.layerMask = mesh.layerMask;
  23679. return serializationObject;
  23680. };
  23681. var SceneSerializer = (function () {
  23682. function SceneSerializer() {
  23683. }
  23684. SceneSerializer.Serialize = function (scene) {
  23685. var serializationObject = {};
  23686. // Scene
  23687. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23688. serializationObject.autoClear = scene.autoClear;
  23689. serializationObject.clearColor = scene.clearColor.asArray();
  23690. serializationObject.ambientColor = scene.ambientColor.asArray();
  23691. serializationObject.gravity = scene.gravity.asArray();
  23692. // Fog
  23693. if (scene.fogMode && scene.fogMode !== 0) {
  23694. serializationObject.fogMode = scene.fogMode;
  23695. serializationObject.fogColor = scene.fogColor.asArray();
  23696. serializationObject.fogStart = scene.fogStart;
  23697. serializationObject.fogEnd = scene.fogEnd;
  23698. serializationObject.fogDensity = scene.fogDensity;
  23699. }
  23700. // Lights
  23701. serializationObject.lights = [];
  23702. for (var index = 0; index < scene.lights.length; index++) {
  23703. var light = scene.lights[index];
  23704. serializationObject.lights.push(serializeLight(light));
  23705. }
  23706. // Cameras
  23707. serializationObject.cameras = [];
  23708. for (index = 0; index < scene.cameras.length; index++) {
  23709. var camera = scene.cameras[index];
  23710. serializationObject.cameras.push(serializeCamera(camera));
  23711. }
  23712. if (scene.activeCamera) {
  23713. serializationObject.activeCameraID = scene.activeCamera.id;
  23714. }
  23715. // Materials
  23716. serializationObject.materials = [];
  23717. serializationObject.multiMaterials = [];
  23718. for (index = 0; index < scene.materials.length; index++) {
  23719. var material = scene.materials[index];
  23720. if (material instanceof BABYLON.StandardMaterial) {
  23721. serializationObject.materials.push(serializeMaterial(material));
  23722. }
  23723. else if (material instanceof BABYLON.MultiMaterial) {
  23724. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23725. }
  23726. }
  23727. // Skeletons
  23728. serializationObject.skeletons = [];
  23729. for (index = 0; index < scene.skeletons.length; index++) {
  23730. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23731. }
  23732. // Geometries
  23733. serializationObject.geometries = {};
  23734. serializationObject.geometries.boxes = [];
  23735. serializationObject.geometries.spheres = [];
  23736. serializationObject.geometries.cylinders = [];
  23737. serializationObject.geometries.toruses = [];
  23738. serializationObject.geometries.grounds = [];
  23739. serializationObject.geometries.planes = [];
  23740. serializationObject.geometries.torusKnots = [];
  23741. serializationObject.geometries.vertexData = [];
  23742. serializedGeometries = [];
  23743. var geometries = scene.getGeometries();
  23744. for (index = 0; index < geometries.length; index++) {
  23745. var geometry = geometries[index];
  23746. if (geometry.isReady()) {
  23747. serializeGeometry(geometry, serializationObject.geometries);
  23748. }
  23749. }
  23750. // Meshes
  23751. serializationObject.meshes = [];
  23752. for (index = 0; index < scene.meshes.length; index++) {
  23753. var abstractMesh = scene.meshes[index];
  23754. if (abstractMesh instanceof BABYLON.Mesh) {
  23755. var mesh = abstractMesh;
  23756. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23757. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23758. }
  23759. }
  23760. }
  23761. // Particles Systems
  23762. serializationObject.particleSystems = [];
  23763. for (index = 0; index < scene.particleSystems.length; index++) {
  23764. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23765. }
  23766. // Lens flares
  23767. serializationObject.lensFlareSystems = [];
  23768. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23769. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23770. }
  23771. // Shadows
  23772. serializationObject.shadowGenerators = [];
  23773. for (index = 0; index < scene.lights.length; index++) {
  23774. light = scene.lights[index];
  23775. if (light.getShadowGenerator()) {
  23776. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23777. }
  23778. }
  23779. return serializationObject;
  23780. };
  23781. return SceneSerializer;
  23782. })();
  23783. BABYLON.SceneSerializer = SceneSerializer;
  23784. })(BABYLON || (BABYLON = {}));
  23785. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23786. var BABYLON;
  23787. (function (BABYLON) {
  23788. // Unique ID when we import meshes from Babylon to CSG
  23789. var currentCSGMeshId = 0;
  23790. // # class Vertex
  23791. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23792. // one to provide additional features like texture coordinates and vertex
  23793. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23794. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23795. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23796. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23797. // is not used anywhere else.
  23798. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23799. var Vertex = (function () {
  23800. function Vertex(pos, normal, uv) {
  23801. this.pos = pos;
  23802. this.normal = normal;
  23803. this.uv = uv;
  23804. }
  23805. Vertex.prototype.clone = function () {
  23806. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23807. };
  23808. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23809. // orientation of a polygon is flipped.
  23810. Vertex.prototype.flip = function () {
  23811. this.normal = this.normal.scale(-1);
  23812. };
  23813. // Create a new vertex between this vertex and `other` by linearly
  23814. // interpolating all properties using a parameter of `t`. Subclasses should
  23815. // override this to interpolate additional properties.
  23816. Vertex.prototype.interpolate = function (other, t) {
  23817. 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));
  23818. };
  23819. return Vertex;
  23820. })();
  23821. // # class Plane
  23822. // Represents a plane in 3D space.
  23823. var Plane = (function () {
  23824. function Plane(normal, w) {
  23825. this.normal = normal;
  23826. this.w = w;
  23827. }
  23828. Plane.FromPoints = function (a, b, c) {
  23829. var v0 = c.subtract(a);
  23830. var v1 = b.subtract(a);
  23831. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23832. return null;
  23833. }
  23834. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23835. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23836. };
  23837. Plane.prototype.clone = function () {
  23838. return new Plane(this.normal.clone(), this.w);
  23839. };
  23840. Plane.prototype.flip = function () {
  23841. this.normal.scaleInPlace(-1);
  23842. this.w = -this.w;
  23843. };
  23844. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23845. // fragments in the appropriate lists. Coplanar polygons go into either
  23846. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23847. // respect to this plane. Polygons in front or in back of this plane go into
  23848. // either `front` or `back`.
  23849. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23850. var COPLANAR = 0;
  23851. var FRONT = 1;
  23852. var BACK = 2;
  23853. var SPANNING = 3;
  23854. // Classify each point as well as the entire polygon into one of the above
  23855. // four classes.
  23856. var polygonType = 0;
  23857. var types = [];
  23858. for (var i = 0; i < polygon.vertices.length; i++) {
  23859. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23860. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23861. polygonType |= type;
  23862. types.push(type);
  23863. }
  23864. // Put the polygon in the correct list, splitting it when necessary.
  23865. switch (polygonType) {
  23866. case COPLANAR:
  23867. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23868. break;
  23869. case FRONT:
  23870. front.push(polygon);
  23871. break;
  23872. case BACK:
  23873. back.push(polygon);
  23874. break;
  23875. case SPANNING:
  23876. var f = [], b = [];
  23877. for (i = 0; i < polygon.vertices.length; i++) {
  23878. var j = (i + 1) % polygon.vertices.length;
  23879. var ti = types[i], tj = types[j];
  23880. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23881. if (ti != BACK)
  23882. f.push(vi);
  23883. if (ti != FRONT)
  23884. b.push(ti != BACK ? vi.clone() : vi);
  23885. if ((ti | tj) == SPANNING) {
  23886. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23887. var v = vi.interpolate(vj, t);
  23888. f.push(v);
  23889. b.push(v.clone());
  23890. }
  23891. }
  23892. if (f.length >= 3) {
  23893. var poly = new Polygon(f, polygon.shared);
  23894. if (poly.plane)
  23895. front.push(poly);
  23896. }
  23897. if (b.length >= 3) {
  23898. poly = new Polygon(b, polygon.shared);
  23899. if (poly.plane)
  23900. back.push(poly);
  23901. }
  23902. break;
  23903. }
  23904. };
  23905. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23906. // point is on the plane.
  23907. Plane.EPSILON = 1e-5;
  23908. return Plane;
  23909. })();
  23910. // # class Polygon
  23911. // Represents a convex polygon. The vertices used to initialize a polygon must
  23912. // be coplanar and form a convex loop.
  23913. //
  23914. // Each convex polygon has a `shared` property, which is shared between all
  23915. // polygons that are clones of each other or were split from the same polygon.
  23916. // This can be used to define per-polygon properties (such as surface color).
  23917. var Polygon = (function () {
  23918. function Polygon(vertices, shared) {
  23919. this.vertices = vertices;
  23920. this.shared = shared;
  23921. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23922. }
  23923. Polygon.prototype.clone = function () {
  23924. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23925. return new Polygon(vertices, this.shared);
  23926. };
  23927. Polygon.prototype.flip = function () {
  23928. this.vertices.reverse().map(function (v) { v.flip(); });
  23929. this.plane.flip();
  23930. };
  23931. return Polygon;
  23932. })();
  23933. // # class Node
  23934. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23935. // by picking a polygon to split along. That polygon (and all other coplanar
  23936. // polygons) are added directly to that node and the other polygons are added to
  23937. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23938. // no distinction between internal and leaf nodes.
  23939. var Node = (function () {
  23940. function Node(polygons) {
  23941. this.plane = null;
  23942. this.front = null;
  23943. this.back = null;
  23944. this.polygons = [];
  23945. if (polygons) {
  23946. this.build(polygons);
  23947. }
  23948. }
  23949. Node.prototype.clone = function () {
  23950. var node = new Node();
  23951. node.plane = this.plane && this.plane.clone();
  23952. node.front = this.front && this.front.clone();
  23953. node.back = this.back && this.back.clone();
  23954. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23955. return node;
  23956. };
  23957. // Convert solid space to empty space and empty space to solid space.
  23958. Node.prototype.invert = function () {
  23959. for (var i = 0; i < this.polygons.length; i++) {
  23960. this.polygons[i].flip();
  23961. }
  23962. if (this.plane) {
  23963. this.plane.flip();
  23964. }
  23965. if (this.front) {
  23966. this.front.invert();
  23967. }
  23968. if (this.back) {
  23969. this.back.invert();
  23970. }
  23971. var temp = this.front;
  23972. this.front = this.back;
  23973. this.back = temp;
  23974. };
  23975. // Recursively remove all polygons in `polygons` that are inside this BSP
  23976. // tree.
  23977. Node.prototype.clipPolygons = function (polygons) {
  23978. if (!this.plane)
  23979. return polygons.slice();
  23980. var front = [], back = [];
  23981. for (var i = 0; i < polygons.length; i++) {
  23982. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23983. }
  23984. if (this.front) {
  23985. front = this.front.clipPolygons(front);
  23986. }
  23987. if (this.back) {
  23988. back = this.back.clipPolygons(back);
  23989. }
  23990. else {
  23991. back = [];
  23992. }
  23993. return front.concat(back);
  23994. };
  23995. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23996. // `bsp`.
  23997. Node.prototype.clipTo = function (bsp) {
  23998. this.polygons = bsp.clipPolygons(this.polygons);
  23999. if (this.front)
  24000. this.front.clipTo(bsp);
  24001. if (this.back)
  24002. this.back.clipTo(bsp);
  24003. };
  24004. // Return a list of all polygons in this BSP tree.
  24005. Node.prototype.allPolygons = function () {
  24006. var polygons = this.polygons.slice();
  24007. if (this.front)
  24008. polygons = polygons.concat(this.front.allPolygons());
  24009. if (this.back)
  24010. polygons = polygons.concat(this.back.allPolygons());
  24011. return polygons;
  24012. };
  24013. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24014. // new polygons are filtered down to the bottom of the tree and become new
  24015. // nodes there. Each set of polygons is partitioned using the first polygon
  24016. // (no heuristic is used to pick a good split).
  24017. Node.prototype.build = function (polygons) {
  24018. if (!polygons.length)
  24019. return;
  24020. if (!this.plane)
  24021. this.plane = polygons[0].plane.clone();
  24022. var front = [], back = [];
  24023. for (var i = 0; i < polygons.length; i++) {
  24024. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24025. }
  24026. if (front.length) {
  24027. if (!this.front)
  24028. this.front = new Node();
  24029. this.front.build(front);
  24030. }
  24031. if (back.length) {
  24032. if (!this.back)
  24033. this.back = new Node();
  24034. this.back.build(back);
  24035. }
  24036. };
  24037. return Node;
  24038. })();
  24039. var CSG = (function () {
  24040. function CSG() {
  24041. this.polygons = new Array();
  24042. }
  24043. // Convert BABYLON.Mesh to BABYLON.CSG
  24044. CSG.FromMesh = function (mesh) {
  24045. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  24046. if (mesh instanceof BABYLON.Mesh) {
  24047. mesh.computeWorldMatrix(true);
  24048. var matrix = mesh.getWorldMatrix();
  24049. var meshPosition = mesh.position.clone();
  24050. var meshRotation = mesh.rotation.clone();
  24051. var meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24052. var meshScaling = mesh.scaling.clone();
  24053. }
  24054. else {
  24055. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24056. }
  24057. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24058. var subMeshes = mesh.subMeshes;
  24059. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24060. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24061. vertices = [];
  24062. for (var j = 0; j < 3; j++) {
  24063. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24064. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24065. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24066. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24067. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24068. vertex = new Vertex(position, normal, uv);
  24069. vertices.push(vertex);
  24070. }
  24071. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24072. // To handle the case of degenerated triangle
  24073. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24074. if (polygon.plane)
  24075. polygons.push(polygon);
  24076. }
  24077. }
  24078. var csg = CSG.FromPolygons(polygons);
  24079. csg.matrix = matrix;
  24080. csg.position = meshPosition;
  24081. csg.rotation = meshRotation;
  24082. csg.scaling = meshScaling;
  24083. csg.rotationQuaternion = meshRotationQuaternion;
  24084. currentCSGMeshId++;
  24085. return csg;
  24086. };
  24087. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24088. CSG.FromPolygons = function (polygons) {
  24089. var csg = new BABYLON.CSG();
  24090. csg.polygons = polygons;
  24091. return csg;
  24092. };
  24093. CSG.prototype.clone = function () {
  24094. var csg = new BABYLON.CSG();
  24095. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24096. csg.copyTransformAttributes(this);
  24097. return csg;
  24098. };
  24099. CSG.prototype.toPolygons = function () {
  24100. return this.polygons;
  24101. };
  24102. CSG.prototype.union = function (csg) {
  24103. var a = new Node(this.clone().polygons);
  24104. var b = new Node(csg.clone().polygons);
  24105. a.clipTo(b);
  24106. b.clipTo(a);
  24107. b.invert();
  24108. b.clipTo(a);
  24109. b.invert();
  24110. a.build(b.allPolygons());
  24111. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24112. };
  24113. CSG.prototype.unionInPlace = function (csg) {
  24114. var a = new Node(this.polygons);
  24115. var b = new Node(csg.polygons);
  24116. a.clipTo(b);
  24117. b.clipTo(a);
  24118. b.invert();
  24119. b.clipTo(a);
  24120. b.invert();
  24121. a.build(b.allPolygons());
  24122. this.polygons = a.allPolygons();
  24123. };
  24124. CSG.prototype.subtract = function (csg) {
  24125. var a = new Node(this.clone().polygons);
  24126. var b = new Node(csg.clone().polygons);
  24127. a.invert();
  24128. a.clipTo(b);
  24129. b.clipTo(a);
  24130. b.invert();
  24131. b.clipTo(a);
  24132. b.invert();
  24133. a.build(b.allPolygons());
  24134. a.invert();
  24135. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24136. };
  24137. CSG.prototype.subtractInPlace = function (csg) {
  24138. var a = new Node(this.polygons);
  24139. var b = new Node(csg.polygons);
  24140. a.invert();
  24141. a.clipTo(b);
  24142. b.clipTo(a);
  24143. b.invert();
  24144. b.clipTo(a);
  24145. b.invert();
  24146. a.build(b.allPolygons());
  24147. a.invert();
  24148. this.polygons = a.allPolygons();
  24149. };
  24150. CSG.prototype.intersect = function (csg) {
  24151. var a = new Node(this.clone().polygons);
  24152. var b = new Node(csg.clone().polygons);
  24153. a.invert();
  24154. b.clipTo(a);
  24155. b.invert();
  24156. a.clipTo(b);
  24157. b.clipTo(a);
  24158. a.build(b.allPolygons());
  24159. a.invert();
  24160. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24161. };
  24162. CSG.prototype.intersectInPlace = function (csg) {
  24163. var a = new Node(this.polygons);
  24164. var b = new Node(csg.polygons);
  24165. a.invert();
  24166. b.clipTo(a);
  24167. b.invert();
  24168. a.clipTo(b);
  24169. b.clipTo(a);
  24170. a.build(b.allPolygons());
  24171. a.invert();
  24172. this.polygons = a.allPolygons();
  24173. };
  24174. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24175. // not modified.
  24176. CSG.prototype.inverse = function () {
  24177. var csg = this.clone();
  24178. csg.inverseInPlace();
  24179. return csg;
  24180. };
  24181. CSG.prototype.inverseInPlace = function () {
  24182. this.polygons.map(function (p) { p.flip(); });
  24183. };
  24184. // This is used to keep meshes transformations so they can be restored
  24185. // when we build back a Babylon Mesh
  24186. // NB : All CSG operations are performed in world coordinates
  24187. CSG.prototype.copyTransformAttributes = function (csg) {
  24188. this.matrix = csg.matrix;
  24189. this.position = csg.position;
  24190. this.rotation = csg.rotation;
  24191. this.scaling = csg.scaling;
  24192. this.rotationQuaternion = csg.rotationQuaternion;
  24193. return this;
  24194. };
  24195. // Build Raw mesh from CSG
  24196. // Coordinates here are in world space
  24197. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24198. var matrix = this.matrix.clone();
  24199. matrix.invert();
  24200. 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;
  24201. if (keepSubMeshes) {
  24202. // Sort Polygons, since subMeshes are indices range
  24203. polygons.sort(function (a, b) {
  24204. if (a.shared.meshId === b.shared.meshId) {
  24205. return a.shared.subMeshId - b.shared.subMeshId;
  24206. }
  24207. else {
  24208. return a.shared.meshId - b.shared.meshId;
  24209. }
  24210. });
  24211. }
  24212. for (var i = 0, il = polygons.length; i < il; i++) {
  24213. polygon = polygons[i];
  24214. // Building SubMeshes
  24215. if (!subMesh_dict[polygon.shared.meshId]) {
  24216. subMesh_dict[polygon.shared.meshId] = {};
  24217. }
  24218. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24219. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24220. indexStart: +Infinity,
  24221. indexEnd: -Infinity,
  24222. materialIndex: polygon.shared.materialIndex
  24223. };
  24224. }
  24225. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24226. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24227. polygonIndices[0] = 0;
  24228. polygonIndices[1] = j - 1;
  24229. polygonIndices[2] = j;
  24230. for (var k = 0; k < 3; k++) {
  24231. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24232. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24233. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24234. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24235. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24236. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24237. // Check if 2 points can be merged
  24238. if (!(typeof vertex_idx !== 'undefined' &&
  24239. normals[vertex_idx * 3] === localNormal.x &&
  24240. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24241. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24242. uvs[vertex_idx * 2] === uv.x &&
  24243. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24244. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24245. uvs.push(uv.x, uv.y);
  24246. normals.push(normal.x, normal.y, normal.z);
  24247. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24248. }
  24249. indices.push(vertex_idx);
  24250. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24251. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24252. currentIndex++;
  24253. }
  24254. }
  24255. }
  24256. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24257. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24258. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24259. mesh.setIndices(indices);
  24260. if (keepSubMeshes) {
  24261. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24262. var materialIndexOffset = 0, materialMaxIndex;
  24263. mesh.subMeshes.length = 0;
  24264. for (var m in subMesh_dict) {
  24265. materialMaxIndex = -1;
  24266. for (var sm in subMesh_dict[m]) {
  24267. subMesh_obj = subMesh_dict[m][sm];
  24268. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24269. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24270. }
  24271. materialIndexOffset += ++materialMaxIndex;
  24272. }
  24273. }
  24274. return mesh;
  24275. };
  24276. // Build Mesh from CSG taking material and transforms into account
  24277. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24278. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24279. mesh.material = material;
  24280. mesh.position.copyFrom(this.position);
  24281. mesh.rotation.copyFrom(this.rotation);
  24282. mesh.rotationQuaternion.copyFrom(this.rotationQuaternion);
  24283. mesh.scaling.copyFrom(this.scaling);
  24284. mesh.computeWorldMatrix(true);
  24285. return mesh;
  24286. };
  24287. return CSG;
  24288. })();
  24289. BABYLON.CSG = CSG;
  24290. })(BABYLON || (BABYLON = {}));
  24291. //# sourceMappingURL=babylon.csg.js.map
  24292. var __extends = this.__extends || function (d, b) {
  24293. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24294. function __() { this.constructor = d; }
  24295. __.prototype = b.prototype;
  24296. d.prototype = new __();
  24297. };
  24298. var BABYLON;
  24299. (function (BABYLON) {
  24300. var VRDistortionCorrectionPostProcess = (function (_super) {
  24301. __extends(VRDistortionCorrectionPostProcess, _super);
  24302. //ANY
  24303. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24304. var _this = this;
  24305. _super.call(this, name, "vrDistortionCorrection", [
  24306. 'LensCenter',
  24307. 'Scale',
  24308. 'ScaleIn',
  24309. 'HmdWarpParam'
  24310. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24311. this._isRightEye = isRightEye;
  24312. this._distortionFactors = vrMetrics.distortionK;
  24313. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24314. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24315. this.onSizeChanged = function () {
  24316. _this.aspectRatio = _this.width * .5 / _this.height;
  24317. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24318. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24319. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24320. };
  24321. this.onApply = function (effect) {
  24322. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24323. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24324. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24325. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24326. };
  24327. }
  24328. return VRDistortionCorrectionPostProcess;
  24329. })(BABYLON.PostProcess);
  24330. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24331. })(BABYLON || (BABYLON = {}));
  24332. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24333. // Mainly based on these 2 articles :
  24334. // 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
  24335. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24336. var BABYLON;
  24337. (function (BABYLON) {
  24338. (function (JoystickAxis) {
  24339. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24340. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24341. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24342. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24343. var JoystickAxis = BABYLON.JoystickAxis;
  24344. var VirtualJoystick = (function () {
  24345. function VirtualJoystick(leftJoystick) {
  24346. var _this = this;
  24347. if (leftJoystick) {
  24348. this._leftJoystick = true;
  24349. }
  24350. else {
  24351. this._leftJoystick = false;
  24352. }
  24353. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24354. VirtualJoystick._globalJoystickIndex++;
  24355. // By default left & right arrow keys are moving the X
  24356. // and up & down keys are moving the Y
  24357. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24358. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24359. this.reverseLeftRight = false;
  24360. this.reverseUpDown = false;
  24361. // collections of pointers
  24362. this._touches = new BABYLON.SmartCollection();
  24363. this.deltaPosition = BABYLON.Vector3.Zero();
  24364. this._joystickSensibility = 25;
  24365. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24366. this._rotationSpeed = 25;
  24367. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24368. this._rotateOnAxisRelativeToMesh = false;
  24369. // injecting a canvas element on top of the canvas 3D game
  24370. if (!VirtualJoystick.vjCanvas) {
  24371. window.addEventListener("resize", function () {
  24372. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24373. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24374. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24375. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24376. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24377. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24378. }, false);
  24379. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24380. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24381. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24382. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24383. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24384. VirtualJoystick.vjCanvas.style.width = "100%";
  24385. VirtualJoystick.vjCanvas.style.height = "100%";
  24386. VirtualJoystick.vjCanvas.style.position = "absolute";
  24387. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24388. VirtualJoystick.vjCanvas.style.top = "0px";
  24389. VirtualJoystick.vjCanvas.style.left = "0px";
  24390. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24391. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24392. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24393. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24394. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24395. document.body.appendChild(VirtualJoystick.vjCanvas);
  24396. }
  24397. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24398. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24399. this.pressed = false;
  24400. // default joystick color
  24401. this._joystickColor = "cyan";
  24402. this._joystickPointerID = -1;
  24403. // current joystick position
  24404. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24405. // origin joystick position
  24406. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24407. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24408. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24409. _this._onPointerDown(evt);
  24410. }, false);
  24411. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24412. _this._onPointerMove(evt);
  24413. }, false);
  24414. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24415. _this._onPointerUp(evt);
  24416. }, false);
  24417. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24418. _this._onPointerUp(evt);
  24419. }, false);
  24420. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24421. evt.preventDefault(); // Disables system menu
  24422. }, false);
  24423. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24424. }
  24425. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24426. this._joystickSensibility = newJoystickSensibility;
  24427. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24428. };
  24429. VirtualJoystick.prototype._onPointerDown = function (e) {
  24430. var positionOnScreenCondition;
  24431. e.preventDefault();
  24432. if (this._leftJoystick === true) {
  24433. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24434. }
  24435. else {
  24436. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24437. }
  24438. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24439. // First contact will be dedicated to the virtual joystick
  24440. this._joystickPointerID = e.pointerId;
  24441. this._joystickPointerStartPos.x = e.clientX;
  24442. this._joystickPointerStartPos.y = e.clientY;
  24443. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24444. this._deltaJoystickVector.x = 0;
  24445. this._deltaJoystickVector.y = 0;
  24446. this.pressed = true;
  24447. this._touches.add(e.pointerId.toString(), e);
  24448. }
  24449. else {
  24450. // You can only trigger the action buttons with a joystick declared
  24451. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24452. this._action();
  24453. this._touches.add(e.pointerId.toString(), e);
  24454. }
  24455. }
  24456. };
  24457. VirtualJoystick.prototype._onPointerMove = function (e) {
  24458. // If the current pointer is the one associated to the joystick (first touch contact)
  24459. if (this._joystickPointerID == e.pointerId) {
  24460. this._joystickPointerPos.x = e.clientX;
  24461. this._joystickPointerPos.y = e.clientY;
  24462. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24463. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24464. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24465. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24466. switch (this._axisTargetedByLeftAndRight) {
  24467. case JoystickAxis.X:
  24468. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24469. break;
  24470. case JoystickAxis.Y:
  24471. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24472. break;
  24473. case JoystickAxis.Z:
  24474. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24475. break;
  24476. }
  24477. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24478. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24479. switch (this._axisTargetedByUpAndDown) {
  24480. case JoystickAxis.X:
  24481. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24482. break;
  24483. case JoystickAxis.Y:
  24484. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24485. break;
  24486. case JoystickAxis.Z:
  24487. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24488. break;
  24489. }
  24490. }
  24491. else {
  24492. if (this._touches.item(e.pointerId.toString())) {
  24493. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24494. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24495. }
  24496. }
  24497. };
  24498. VirtualJoystick.prototype._onPointerUp = function (e) {
  24499. this._clearCanvas();
  24500. if (this._joystickPointerID == e.pointerId) {
  24501. this._joystickPointerID = -1;
  24502. this.pressed = false;
  24503. }
  24504. this._deltaJoystickVector.x = 0;
  24505. this._deltaJoystickVector.y = 0;
  24506. this._touches.remove(e.pointerId.toString());
  24507. };
  24508. /**
  24509. * Change the color of the virtual joystick
  24510. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24511. */
  24512. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24513. this._joystickColor = newColor;
  24514. };
  24515. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24516. this._action = action;
  24517. };
  24518. // Define which axis you'd like to control for left & right
  24519. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24520. switch (axis) {
  24521. case JoystickAxis.X:
  24522. case JoystickAxis.Y:
  24523. case JoystickAxis.Z:
  24524. this._axisTargetedByLeftAndRight = axis;
  24525. break;
  24526. default:
  24527. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24528. break;
  24529. }
  24530. };
  24531. // Define which axis you'd like to control for up & down
  24532. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24533. switch (axis) {
  24534. case JoystickAxis.X:
  24535. case JoystickAxis.Y:
  24536. case JoystickAxis.Z:
  24537. this._axisTargetedByUpAndDown = axis;
  24538. break;
  24539. default:
  24540. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24541. break;
  24542. }
  24543. };
  24544. VirtualJoystick.prototype._clearCanvas = function () {
  24545. if (this._leftJoystick) {
  24546. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24547. }
  24548. else {
  24549. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24550. }
  24551. };
  24552. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24553. var _this = this;
  24554. if (this.pressed) {
  24555. this._clearCanvas();
  24556. this._touches.forEach(function (touch) {
  24557. if (touch.pointerId === _this._joystickPointerID) {
  24558. VirtualJoystick.vjCanvasContext.beginPath();
  24559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24560. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24561. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24562. VirtualJoystick.vjCanvasContext.stroke();
  24563. VirtualJoystick.vjCanvasContext.beginPath();
  24564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24565. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24566. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24567. VirtualJoystick.vjCanvasContext.stroke();
  24568. VirtualJoystick.vjCanvasContext.beginPath();
  24569. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24570. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24571. VirtualJoystick.vjCanvasContext.stroke();
  24572. }
  24573. else {
  24574. VirtualJoystick.vjCanvasContext.beginPath();
  24575. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24576. VirtualJoystick.vjCanvasContext.beginPath();
  24577. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24578. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24579. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24580. VirtualJoystick.vjCanvasContext.stroke();
  24581. }
  24582. ;
  24583. });
  24584. }
  24585. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24586. };
  24587. VirtualJoystick.prototype.releaseCanvas = function () {
  24588. if (VirtualJoystick.vjCanvas) {
  24589. document.body.removeChild(VirtualJoystick.vjCanvas);
  24590. VirtualJoystick.vjCanvas = null;
  24591. }
  24592. };
  24593. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24594. VirtualJoystick._globalJoystickIndex = 0;
  24595. return VirtualJoystick;
  24596. })();
  24597. BABYLON.VirtualJoystick = VirtualJoystick;
  24598. })(BABYLON || (BABYLON = {}));
  24599. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24600. var __extends = this.__extends || function (d, b) {
  24601. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24602. function __() { this.constructor = d; }
  24603. __.prototype = b.prototype;
  24604. d.prototype = new __();
  24605. };
  24606. var BABYLON;
  24607. (function (BABYLON) {
  24608. // We're mainly based on the logic defined into the FreeCamera code
  24609. var VirtualJoysticksCamera = (function (_super) {
  24610. __extends(VirtualJoysticksCamera, _super);
  24611. function VirtualJoysticksCamera(name, position, scene) {
  24612. _super.call(this, name, position, scene);
  24613. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24614. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24615. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24616. this._leftjoystick.setJoystickSensibility(0.15);
  24617. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24618. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24619. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24620. this._rightjoystick.reverseUpDown = true;
  24621. this._rightjoystick.setJoystickSensibility(0.05);
  24622. this._rightjoystick.setJoystickColor("yellow");
  24623. }
  24624. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24625. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24626. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24627. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24628. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24629. if (!this._leftjoystick.pressed) {
  24630. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24631. }
  24632. if (!this._rightjoystick.pressed) {
  24633. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24634. }
  24635. _super.prototype._checkInputs.call(this);
  24636. };
  24637. VirtualJoysticksCamera.prototype.dispose = function () {
  24638. this._leftjoystick.releaseCanvas();
  24639. _super.prototype.dispose.call(this);
  24640. };
  24641. return VirtualJoysticksCamera;
  24642. })(BABYLON.FreeCamera);
  24643. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24644. })(BABYLON || (BABYLON = {}));
  24645. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24646. var __extends = this.__extends || function (d, b) {
  24647. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24648. function __() { this.constructor = d; }
  24649. __.prototype = b.prototype;
  24650. d.prototype = new __();
  24651. };
  24652. var BABYLON;
  24653. (function (BABYLON) {
  24654. var ShaderMaterial = (function (_super) {
  24655. __extends(ShaderMaterial, _super);
  24656. function ShaderMaterial(name, scene, shaderPath, options) {
  24657. _super.call(this, name, scene);
  24658. this._textures = new Array();
  24659. this._floats = new Array();
  24660. this._floatsArrays = {};
  24661. this._colors3 = new Array();
  24662. this._colors4 = new Array();
  24663. this._vectors2 = new Array();
  24664. this._vectors3 = new Array();
  24665. this._matrices = new Array();
  24666. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24667. this._shaderPath = shaderPath;
  24668. options.needAlphaBlending = options.needAlphaBlending || false;
  24669. options.needAlphaTesting = options.needAlphaTesting || false;
  24670. options.attributes = options.attributes || ["position", "normal", "uv"];
  24671. options.uniforms = options.uniforms || ["worldViewProjection"];
  24672. options.samplers = options.samplers || [];
  24673. this._options = options;
  24674. }
  24675. ShaderMaterial.prototype.needAlphaBlending = function () {
  24676. return this._options.needAlphaBlending;
  24677. };
  24678. ShaderMaterial.prototype.needAlphaTesting = function () {
  24679. return this._options.needAlphaTesting;
  24680. };
  24681. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24682. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24683. this._options.uniforms.push(uniformName);
  24684. }
  24685. };
  24686. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24687. if (this._options.samplers.indexOf(name) === -1) {
  24688. this._options.samplers.push(name);
  24689. }
  24690. this._textures[name] = texture;
  24691. return this;
  24692. };
  24693. ShaderMaterial.prototype.setFloat = function (name, value) {
  24694. this._checkUniform(name);
  24695. this._floats[name] = value;
  24696. return this;
  24697. };
  24698. ShaderMaterial.prototype.setFloats = function (name, value) {
  24699. this._checkUniform(name);
  24700. this._floatsArrays[name] = value;
  24701. return this;
  24702. };
  24703. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24704. this._checkUniform(name);
  24705. this._colors3[name] = value;
  24706. return this;
  24707. };
  24708. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24709. this._checkUniform(name);
  24710. this._colors4[name] = value;
  24711. return this;
  24712. };
  24713. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24714. this._checkUniform(name);
  24715. this._vectors2[name] = value;
  24716. return this;
  24717. };
  24718. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24719. this._checkUniform(name);
  24720. this._vectors3[name] = value;
  24721. return this;
  24722. };
  24723. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24724. this._checkUniform(name);
  24725. this._matrices[name] = value;
  24726. return this;
  24727. };
  24728. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24729. var scene = this.getScene();
  24730. var engine = scene.getEngine();
  24731. if (!this.checkReadyOnEveryCall) {
  24732. if (this._renderId === scene.getRenderId()) {
  24733. return true;
  24734. }
  24735. }
  24736. // Instances
  24737. var defines = [];
  24738. var fallbacks = new BABYLON.EffectFallbacks();
  24739. if (useInstances) {
  24740. defines.push("#define INSTANCES");
  24741. }
  24742. // Bones
  24743. if (mesh && mesh.useBones) {
  24744. defines.push("#define BONES");
  24745. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24746. defines.push("#define BONES4");
  24747. fallbacks.addFallback(0, "BONES4");
  24748. }
  24749. // Alpha test
  24750. if (engine.getAlphaTesting()) {
  24751. defines.push("#define ALPHATEST");
  24752. }
  24753. var previousEffect = this._effect;
  24754. var join = defines.join("\n");
  24755. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24756. if (!this._effect.isReady()) {
  24757. return false;
  24758. }
  24759. if (previousEffect !== this._effect) {
  24760. scene.resetCachedMaterial();
  24761. }
  24762. this._renderId = scene.getRenderId();
  24763. return true;
  24764. };
  24765. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24766. var scene = this.getScene();
  24767. if (this._options.uniforms.indexOf("world") !== -1) {
  24768. this._effect.setMatrix("world", world);
  24769. }
  24770. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24771. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24772. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24773. }
  24774. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24775. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24776. }
  24777. };
  24778. ShaderMaterial.prototype.bind = function (world, mesh) {
  24779. // Std values
  24780. this.bindOnlyWorldMatrix(world);
  24781. if (this.getScene().getCachedMaterial() !== this) {
  24782. if (this._options.uniforms.indexOf("view") !== -1) {
  24783. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24784. }
  24785. if (this._options.uniforms.indexOf("projection") !== -1) {
  24786. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24787. }
  24788. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24789. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24790. }
  24791. // Bones
  24792. if (mesh && mesh.useBones) {
  24793. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24794. }
  24795. // Texture
  24796. for (var name in this._textures) {
  24797. this._effect.setTexture(name, this._textures[name]);
  24798. }
  24799. // Float
  24800. for (name in this._floats) {
  24801. this._effect.setFloat(name, this._floats[name]);
  24802. }
  24803. // Float s
  24804. for (name in this._floatsArrays) {
  24805. this._effect.setArray(name, this._floatsArrays[name]);
  24806. }
  24807. // Color3
  24808. for (name in this._colors3) {
  24809. this._effect.setColor3(name, this._colors3[name]);
  24810. }
  24811. // Color4
  24812. for (name in this._colors4) {
  24813. var color = this._colors4[name];
  24814. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24815. }
  24816. // Vector2
  24817. for (name in this._vectors2) {
  24818. this._effect.setVector2(name, this._vectors2[name]);
  24819. }
  24820. // Vector3
  24821. for (name in this._vectors3) {
  24822. this._effect.setVector3(name, this._vectors3[name]);
  24823. }
  24824. // Matrix
  24825. for (name in this._matrices) {
  24826. this._effect.setMatrix(name, this._matrices[name]);
  24827. }
  24828. }
  24829. _super.prototype.bind.call(this, world, mesh);
  24830. };
  24831. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24832. for (var name in this._textures) {
  24833. this._textures[name].dispose();
  24834. }
  24835. this._textures = [];
  24836. _super.prototype.dispose.call(this, forceDisposeEffect);
  24837. };
  24838. return ShaderMaterial;
  24839. })(BABYLON.Material);
  24840. BABYLON.ShaderMaterial = ShaderMaterial;
  24841. })(BABYLON || (BABYLON = {}));
  24842. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24843. var BABYLON;
  24844. (function (BABYLON) {
  24845. var VertexData = (function () {
  24846. function VertexData() {
  24847. }
  24848. VertexData.prototype.set = function (data, kind) {
  24849. switch (kind) {
  24850. case BABYLON.VertexBuffer.PositionKind:
  24851. this.positions = data;
  24852. break;
  24853. case BABYLON.VertexBuffer.NormalKind:
  24854. this.normals = data;
  24855. break;
  24856. case BABYLON.VertexBuffer.UVKind:
  24857. this.uvs = data;
  24858. break;
  24859. case BABYLON.VertexBuffer.UV2Kind:
  24860. this.uv2s = data;
  24861. break;
  24862. case BABYLON.VertexBuffer.ColorKind:
  24863. this.colors = data;
  24864. break;
  24865. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24866. this.matricesIndices = data;
  24867. break;
  24868. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24869. this.matricesWeights = data;
  24870. break;
  24871. }
  24872. };
  24873. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24874. this._applyTo(mesh, updatable);
  24875. };
  24876. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24877. this._applyTo(geometry, updatable);
  24878. };
  24879. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24880. this._update(mesh);
  24881. };
  24882. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24883. this._update(geometry);
  24884. };
  24885. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24886. if (this.positions) {
  24887. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24888. }
  24889. if (this.normals) {
  24890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24891. }
  24892. if (this.uvs) {
  24893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24894. }
  24895. if (this.uv2s) {
  24896. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24897. }
  24898. if (this.colors) {
  24899. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24900. }
  24901. if (this.matricesIndices) {
  24902. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24903. }
  24904. if (this.matricesWeights) {
  24905. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24906. }
  24907. if (this.indices) {
  24908. meshOrGeometry.setIndices(this.indices);
  24909. }
  24910. };
  24911. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24912. if (this.positions) {
  24913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24914. }
  24915. if (this.normals) {
  24916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24917. }
  24918. if (this.uvs) {
  24919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24920. }
  24921. if (this.uv2s) {
  24922. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24923. }
  24924. if (this.colors) {
  24925. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24926. }
  24927. if (this.matricesIndices) {
  24928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24929. }
  24930. if (this.matricesWeights) {
  24931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24932. }
  24933. if (this.indices) {
  24934. meshOrGeometry.setIndices(this.indices);
  24935. }
  24936. };
  24937. VertexData.prototype.transform = function (matrix) {
  24938. var transformed = BABYLON.Vector3.Zero();
  24939. if (this.positions) {
  24940. var position = BABYLON.Vector3.Zero();
  24941. for (var index = 0; index < this.positions.length; index += 3) {
  24942. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24943. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24944. this.positions[index] = transformed.x;
  24945. this.positions[index + 1] = transformed.y;
  24946. this.positions[index + 2] = transformed.z;
  24947. }
  24948. }
  24949. if (this.normals) {
  24950. var normal = BABYLON.Vector3.Zero();
  24951. for (index = 0; index < this.normals.length; index += 3) {
  24952. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24953. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24954. this.normals[index] = transformed.x;
  24955. this.normals[index + 1] = transformed.y;
  24956. this.normals[index + 2] = transformed.z;
  24957. }
  24958. }
  24959. };
  24960. VertexData.prototype.merge = function (other) {
  24961. if (other.indices) {
  24962. if (!this.indices) {
  24963. this.indices = [];
  24964. }
  24965. var offset = this.positions ? this.positions.length / 3 : 0;
  24966. for (var index = 0; index < other.indices.length; index++) {
  24967. this.indices.push(other.indices[index] + offset);
  24968. }
  24969. }
  24970. if (other.positions) {
  24971. if (!this.positions) {
  24972. this.positions = [];
  24973. }
  24974. for (index = 0; index < other.positions.length; index++) {
  24975. this.positions.push(other.positions[index]);
  24976. }
  24977. }
  24978. if (other.normals) {
  24979. if (!this.normals) {
  24980. this.normals = [];
  24981. }
  24982. for (index = 0; index < other.normals.length; index++) {
  24983. this.normals.push(other.normals[index]);
  24984. }
  24985. }
  24986. if (other.uvs) {
  24987. if (!this.uvs) {
  24988. this.uvs = [];
  24989. }
  24990. for (index = 0; index < other.uvs.length; index++) {
  24991. this.uvs.push(other.uvs[index]);
  24992. }
  24993. }
  24994. if (other.uv2s) {
  24995. if (!this.uv2s) {
  24996. this.uv2s = [];
  24997. }
  24998. for (index = 0; index < other.uv2s.length; index++) {
  24999. this.uv2s.push(other.uv2s[index]);
  25000. }
  25001. }
  25002. if (other.matricesIndices) {
  25003. if (!this.matricesIndices) {
  25004. this.matricesIndices = [];
  25005. }
  25006. for (index = 0; index < other.matricesIndices.length; index++) {
  25007. this.matricesIndices.push(other.matricesIndices[index]);
  25008. }
  25009. }
  25010. if (other.matricesWeights) {
  25011. if (!this.matricesWeights) {
  25012. this.matricesWeights = [];
  25013. }
  25014. for (index = 0; index < other.matricesWeights.length; index++) {
  25015. this.matricesWeights.push(other.matricesWeights[index]);
  25016. }
  25017. }
  25018. if (other.colors) {
  25019. if (!this.colors) {
  25020. this.colors = [];
  25021. }
  25022. for (index = 0; index < other.colors.length; index++) {
  25023. this.colors.push(other.colors[index]);
  25024. }
  25025. }
  25026. };
  25027. // Statics
  25028. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25029. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25030. };
  25031. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25032. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25033. };
  25034. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25035. var result = new VertexData();
  25036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25037. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25038. }
  25039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25040. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25041. }
  25042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25043. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25044. }
  25045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25046. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25047. }
  25048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25049. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25050. }
  25051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25052. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  25053. }
  25054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25055. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  25056. }
  25057. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25058. return result;
  25059. };
  25060. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25061. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25062. closeArray = closeArray || false;
  25063. closePath = closePath || false;
  25064. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25065. offset = offset || defaultOffset;
  25066. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25067. var positions = [];
  25068. var indices = [];
  25069. var normals = [];
  25070. var uvs = [];
  25071. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25072. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25073. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25074. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25075. var minlg; // minimal length among all paths from pathArray
  25076. var lg = []; // array of path lengths : nb of vertex per path
  25077. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  25078. var p; // path iterator
  25079. var i; // point iterator
  25080. var j; // point iterator
  25081. // if single path in pathArray
  25082. if (pathArray.length < 2) {
  25083. var ar1 = [];
  25084. var ar2 = [];
  25085. for (i = 0; i < pathArray[0].length - offset; i++) {
  25086. ar1.push(pathArray[0][i]);
  25087. ar2.push(pathArray[0][i + offset]);
  25088. }
  25089. pathArray = [ar1, ar2];
  25090. }
  25091. // positions and horizontal distances (u)
  25092. var idc = 0;
  25093. minlg = pathArray[0].length;
  25094. for (p = 0; p < pathArray.length; p++) {
  25095. uTotalDistance[p] = 0;
  25096. us[p] = [0];
  25097. var path = pathArray[p];
  25098. var l = path.length;
  25099. minlg = (minlg < l) ? minlg : l;
  25100. lg[p] = l;
  25101. idx[p] = idc;
  25102. j = 0;
  25103. while (j < l) {
  25104. positions.push(path[j].x, path[j].y, path[j].z);
  25105. if (j > 0) {
  25106. var vectlg = path[j].subtract(path[j - 1]).length();
  25107. var dist = vectlg + uTotalDistance[p];
  25108. us[p].push(dist);
  25109. uTotalDistance[p] = dist;
  25110. }
  25111. j++;
  25112. }
  25113. if (closePath) {
  25114. vectlg = path[0].subtract(path[j - 1]).length();
  25115. dist = vectlg + uTotalDistance[p];
  25116. uTotalDistance[p] = dist;
  25117. }
  25118. idc += l;
  25119. }
  25120. // vertical distances (v)
  25121. for (i = 0; i < minlg; i++) {
  25122. vTotalDistance[i] = 0;
  25123. vs[i] = [0];
  25124. var path1;
  25125. var path2;
  25126. for (p = 0; p < pathArray.length - 1; p++) {
  25127. path1 = pathArray[p];
  25128. path2 = pathArray[p + 1];
  25129. vectlg = path2[i].subtract(path1[i]).length();
  25130. dist = vectlg + vTotalDistance[i];
  25131. vs[i].push(dist);
  25132. vTotalDistance[i] = dist;
  25133. }
  25134. if (closeArray) {
  25135. path1 = pathArray[p];
  25136. path2 = pathArray[0];
  25137. vectlg = path2[i].subtract(path1[i]).length();
  25138. dist = vectlg + vTotalDistance[i];
  25139. vTotalDistance[i] = dist;
  25140. }
  25141. }
  25142. // uvs
  25143. var u;
  25144. var v;
  25145. for (p = 0; p < pathArray.length; p++) {
  25146. for (i = 0; i < minlg; i++) {
  25147. u = us[p][i] / uTotalDistance[p];
  25148. v = vs[i][p] / vTotalDistance[i];
  25149. uvs.push(u, v);
  25150. }
  25151. }
  25152. // indices
  25153. p = 0; // path index
  25154. var pi = 0; // positions array index
  25155. var l1 = lg[p] - 1; // path1 length
  25156. var l2 = lg[p + 1] - 1; // path2 length
  25157. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25158. var shft = idx[1] - idx[0]; // shift
  25159. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25160. var t1; // two consecutive triangles, so 4 points : point1
  25161. var t2; // point2
  25162. var t3; // point3
  25163. var t4; // point4
  25164. while (pi <= min && p < path1nb) {
  25165. // 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
  25166. t1 = pi;
  25167. t2 = pi + shft;
  25168. t3 = pi + 1;
  25169. t4 = pi + shft + 1;
  25170. indices.push(pi, pi + shft, pi + 1);
  25171. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25172. pi += 1;
  25173. if (pi === min) {
  25174. if (closePath) {
  25175. indices.push(pi, pi + shft, idx[p]);
  25176. indices.push(idx[p] + shft, idx[p], pi + shft);
  25177. t3 = idx[p];
  25178. t4 = idx[p] + shft;
  25179. }
  25180. p++;
  25181. if (p === lg.length - 1) {
  25182. shft = idx[0] - idx[p];
  25183. l1 = lg[p] - 1;
  25184. l2 = lg[0] - 1;
  25185. }
  25186. else {
  25187. shft = idx[p + 1] - idx[p];
  25188. l1 = lg[p] - 1;
  25189. l2 = lg[p + 1] - 1;
  25190. }
  25191. pi = idx[p];
  25192. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25193. }
  25194. }
  25195. // normals
  25196. VertexData.ComputeNormals(positions, indices, normals);
  25197. // sides
  25198. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25199. // Result
  25200. var vertexData = new VertexData();
  25201. vertexData.indices = indices;
  25202. vertexData.positions = positions;
  25203. vertexData.normals = normals;
  25204. vertexData.uvs = uvs;
  25205. return vertexData;
  25206. };
  25207. VertexData.CreateBox = function (size, sideOrientation) {
  25208. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25209. var normalsSource = [
  25210. new BABYLON.Vector3(0, 0, 1),
  25211. new BABYLON.Vector3(0, 0, -1),
  25212. new BABYLON.Vector3(1, 0, 0),
  25213. new BABYLON.Vector3(-1, 0, 0),
  25214. new BABYLON.Vector3(0, 1, 0),
  25215. new BABYLON.Vector3(0, -1, 0)
  25216. ];
  25217. var indices = [];
  25218. var positions = [];
  25219. var normals = [];
  25220. var uvs = [];
  25221. size = size || 1;
  25222. // Create each face in turn.
  25223. for (var index = 0; index < normalsSource.length; index++) {
  25224. var normal = normalsSource[index];
  25225. // Get two vectors perpendicular to the face normal and to each other.
  25226. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25227. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25228. // Six indices (two triangles) per face.
  25229. var verticesLength = positions.length / 3;
  25230. indices.push(verticesLength);
  25231. indices.push(verticesLength + 1);
  25232. indices.push(verticesLength + 2);
  25233. indices.push(verticesLength);
  25234. indices.push(verticesLength + 2);
  25235. indices.push(verticesLength + 3);
  25236. // Four vertices per face.
  25237. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25238. positions.push(vertex.x, vertex.y, vertex.z);
  25239. normals.push(normal.x, normal.y, normal.z);
  25240. uvs.push(1.0, 1.0);
  25241. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25242. positions.push(vertex.x, vertex.y, vertex.z);
  25243. normals.push(normal.x, normal.y, normal.z);
  25244. uvs.push(0.0, 1.0);
  25245. vertex = normal.add(side1).add(side2).scale(size / 2);
  25246. positions.push(vertex.x, vertex.y, vertex.z);
  25247. normals.push(normal.x, normal.y, normal.z);
  25248. uvs.push(0.0, 0.0);
  25249. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25250. positions.push(vertex.x, vertex.y, vertex.z);
  25251. normals.push(normal.x, normal.y, normal.z);
  25252. uvs.push(1.0, 0.0);
  25253. }
  25254. // sides
  25255. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25256. // Result
  25257. var vertexData = new VertexData();
  25258. vertexData.indices = indices;
  25259. vertexData.positions = positions;
  25260. vertexData.normals = normals;
  25261. vertexData.uvs = uvs;
  25262. return vertexData;
  25263. };
  25264. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25265. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25266. segments = segments || 32;
  25267. diameter = diameter || 1;
  25268. var radius = diameter / 2;
  25269. var totalZRotationSteps = 2 + segments;
  25270. var totalYRotationSteps = 2 * totalZRotationSteps;
  25271. var indices = [];
  25272. var positions = [];
  25273. var normals = [];
  25274. var uvs = [];
  25275. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25276. var normalizedZ = zRotationStep / totalZRotationSteps;
  25277. var angleZ = (normalizedZ * Math.PI);
  25278. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25279. var normalizedY = yRotationStep / totalYRotationSteps;
  25280. var angleY = normalizedY * Math.PI * 2;
  25281. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25282. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25283. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25284. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25285. var vertex = complete.scale(radius);
  25286. var normal = BABYLON.Vector3.Normalize(vertex);
  25287. positions.push(vertex.x, vertex.y, vertex.z);
  25288. normals.push(normal.x, normal.y, normal.z);
  25289. uvs.push(normalizedZ, normalizedY);
  25290. }
  25291. if (zRotationStep > 0) {
  25292. var verticesCount = positions.length / 3;
  25293. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25294. indices.push((firstIndex));
  25295. indices.push((firstIndex + 1));
  25296. indices.push(firstIndex + totalYRotationSteps + 1);
  25297. indices.push((firstIndex + totalYRotationSteps + 1));
  25298. indices.push((firstIndex + 1));
  25299. indices.push((firstIndex + totalYRotationSteps + 2));
  25300. }
  25301. }
  25302. }
  25303. // Sides
  25304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25305. // Result
  25306. var vertexData = new VertexData();
  25307. vertexData.indices = indices;
  25308. vertexData.positions = positions;
  25309. vertexData.normals = normals;
  25310. vertexData.uvs = uvs;
  25311. return vertexData;
  25312. };
  25313. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25314. if (subdivisions === void 0) { subdivisions = 1; }
  25315. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25316. var radiusTop = diameterTop / 2;
  25317. var radiusBottom = diameterBottom / 2;
  25318. var indices = [];
  25319. var positions = [];
  25320. var normals = [];
  25321. var uvs = [];
  25322. height = height || 1;
  25323. diameterTop = diameterTop || 0.5;
  25324. diameterBottom = diameterBottom || 1;
  25325. tessellation = tessellation || 16;
  25326. subdivisions = subdivisions || 1;
  25327. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25328. var getCircleVector = function (i) {
  25329. var angle = (i * 2.0 * Math.PI / tessellation);
  25330. var dx = Math.cos(angle);
  25331. var dz = Math.sin(angle);
  25332. return new BABYLON.Vector3(dx, 0, dz);
  25333. };
  25334. var createCylinderCap = function (isTop) {
  25335. var radius = isTop ? radiusTop : radiusBottom;
  25336. if (radius === 0) {
  25337. return;
  25338. }
  25339. var vbase = positions.length / 3;
  25340. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25341. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25342. if (!isTop) {
  25343. offset.scaleInPlace(-1);
  25344. textureScale.x = -textureScale.x;
  25345. }
  25346. // Positions, normals & uvs
  25347. for (var i = 0; i < tessellation; i++) {
  25348. var circleVector = getCircleVector(i);
  25349. var position = circleVector.scale(radius).add(offset);
  25350. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25351. positions.push(position.x, position.y, position.z);
  25352. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25353. }
  25354. // Indices
  25355. for (i = 0; i < tessellation - 2; i++) {
  25356. if (!isTop) {
  25357. indices.push(vbase);
  25358. indices.push(vbase + (i + 2) % tessellation);
  25359. indices.push(vbase + (i + 1) % tessellation);
  25360. }
  25361. else {
  25362. indices.push(vbase);
  25363. indices.push(vbase + (i + 1) % tessellation);
  25364. indices.push(vbase + (i + 2) % tessellation);
  25365. }
  25366. }
  25367. };
  25368. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25369. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25370. var stride = tessellation + 1;
  25371. // Positions, normals & uvs
  25372. for (var i = 0; i <= tessellation; i++) {
  25373. var circleVector = getCircleVector(i);
  25374. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25375. var position, radius = radiusBottom;
  25376. for (var s = 0; s <= subdivisions; s++) {
  25377. // Update variables
  25378. position = circleVector.scale(radius);
  25379. position.addInPlace(base.add(offset.scale(s)));
  25380. textureCoordinate.y += 1 / subdivisions;
  25381. radius += (radiusTop - radiusBottom) / subdivisions;
  25382. // Push in arrays
  25383. positions.push(position.x, position.y, position.z);
  25384. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25385. }
  25386. }
  25387. subdivisions += 1;
  25388. // Indices
  25389. for (s = 0; s < subdivisions - 1; s++) {
  25390. for (i = 0; i <= tessellation; i++) {
  25391. indices.push(i * subdivisions + s);
  25392. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25393. indices.push(i * subdivisions + (s + 1));
  25394. indices.push(i * subdivisions + (s + 1));
  25395. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25396. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25397. }
  25398. }
  25399. // Create flat triangle fan caps to seal the top and bottom.
  25400. createCylinderCap(true);
  25401. createCylinderCap(false);
  25402. // Normals
  25403. VertexData.ComputeNormals(positions, indices, normals);
  25404. // Sides
  25405. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25406. // Result
  25407. var vertexData = new VertexData();
  25408. vertexData.indices = indices;
  25409. vertexData.positions = positions;
  25410. vertexData.normals = normals;
  25411. vertexData.uvs = uvs;
  25412. return vertexData;
  25413. };
  25414. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25415. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25416. var indices = [];
  25417. var positions = [];
  25418. var normals = [];
  25419. var uvs = [];
  25420. diameter = diameter || 1;
  25421. thickness = thickness || 0.5;
  25422. tessellation = tessellation || 16;
  25423. var stride = tessellation + 1;
  25424. for (var i = 0; i <= tessellation; i++) {
  25425. var u = i / tessellation;
  25426. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25427. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25428. for (var j = 0; j <= tessellation; j++) {
  25429. var v = 1 - j / tessellation;
  25430. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25431. var dx = Math.cos(innerAngle);
  25432. var dy = Math.sin(innerAngle);
  25433. // Create a vertex.
  25434. var normal = new BABYLON.Vector3(dx, dy, 0);
  25435. var position = normal.scale(thickness / 2);
  25436. var textureCoordinate = new BABYLON.Vector2(u, v);
  25437. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25438. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25439. positions.push(position.x, position.y, position.z);
  25440. normals.push(normal.x, normal.y, normal.z);
  25441. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25442. // And create indices for two triangles.
  25443. var nextI = (i + 1) % stride;
  25444. var nextJ = (j + 1) % stride;
  25445. indices.push(i * stride + j);
  25446. indices.push(i * stride + nextJ);
  25447. indices.push(nextI * stride + j);
  25448. indices.push(i * stride + nextJ);
  25449. indices.push(nextI * stride + nextJ);
  25450. indices.push(nextI * stride + j);
  25451. }
  25452. }
  25453. // Sides
  25454. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25455. // Result
  25456. var vertexData = new VertexData();
  25457. vertexData.indices = indices;
  25458. vertexData.positions = positions;
  25459. vertexData.normals = normals;
  25460. vertexData.uvs = uvs;
  25461. return vertexData;
  25462. };
  25463. VertexData.CreateLines = function (points) {
  25464. var indices = [];
  25465. var positions = [];
  25466. for (var index = 0; index < points.length; index++) {
  25467. positions.push(points[index].x, points[index].y, points[index].z);
  25468. if (index > 0) {
  25469. indices.push(index - 1);
  25470. indices.push(index);
  25471. }
  25472. }
  25473. // Result
  25474. var vertexData = new VertexData();
  25475. vertexData.indices = indices;
  25476. vertexData.positions = positions;
  25477. return vertexData;
  25478. };
  25479. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25480. dashSize = dashSize || 3;
  25481. gapSize = gapSize || 1;
  25482. dashNb = dashNb || 200;
  25483. var positions = new Array();
  25484. var indices = new Array();
  25485. var curvect = BABYLON.Vector3.Zero();
  25486. var lg = 0;
  25487. var nb = 0;
  25488. var shft = 0;
  25489. var dashshft = 0;
  25490. var curshft = 0;
  25491. var idx = 0;
  25492. var i = 0;
  25493. for (i = 0; i < points.length - 1; i++) {
  25494. points[i + 1].subtractToRef(points[i], curvect);
  25495. lg += curvect.length();
  25496. }
  25497. shft = lg / dashNb;
  25498. dashshft = dashSize * shft / (dashSize + gapSize);
  25499. for (i = 0; i < points.length - 1; i++) {
  25500. points[i + 1].subtractToRef(points[i], curvect);
  25501. curvect.normalize();
  25502. nb = Math.floor(curvect.length() / shft);
  25503. for (var j = 0; j < nb; j++) {
  25504. curshft = shft * j;
  25505. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25506. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25507. indices.push(idx, idx + 1);
  25508. idx += 2;
  25509. }
  25510. }
  25511. // Result
  25512. var vertexData = new VertexData();
  25513. vertexData.positions = positions;
  25514. vertexData.indices = indices;
  25515. return vertexData;
  25516. };
  25517. VertexData.CreateGround = function (width, height, subdivisions) {
  25518. var indices = [];
  25519. var positions = [];
  25520. var normals = [];
  25521. var uvs = [];
  25522. var row, col;
  25523. width = width || 1;
  25524. height = height || 1;
  25525. subdivisions = subdivisions || 1;
  25526. for (row = 0; row <= subdivisions; row++) {
  25527. for (col = 0; col <= subdivisions; col++) {
  25528. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25529. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25530. positions.push(position.x, position.y, position.z);
  25531. normals.push(normal.x, normal.y, normal.z);
  25532. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25533. }
  25534. }
  25535. for (row = 0; row < subdivisions; row++) {
  25536. for (col = 0; col < subdivisions; col++) {
  25537. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25538. indices.push(col + 1 + row * (subdivisions + 1));
  25539. indices.push(col + row * (subdivisions + 1));
  25540. indices.push(col + (row + 1) * (subdivisions + 1));
  25541. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25542. indices.push(col + row * (subdivisions + 1));
  25543. }
  25544. }
  25545. // Result
  25546. var vertexData = new VertexData();
  25547. vertexData.indices = indices;
  25548. vertexData.positions = positions;
  25549. vertexData.normals = normals;
  25550. vertexData.uvs = uvs;
  25551. return vertexData;
  25552. };
  25553. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25554. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25555. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25556. var indices = [];
  25557. var positions = [];
  25558. var normals = [];
  25559. var uvs = [];
  25560. var row, col, tileRow, tileCol;
  25561. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25562. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25563. precision.w = (precision.w < 1) ? 1 : precision.w;
  25564. precision.h = (precision.h < 1) ? 1 : precision.h;
  25565. var tileSize = {
  25566. 'w': (xmax - xmin) / subdivisions.w,
  25567. 'h': (zmax - zmin) / subdivisions.h
  25568. };
  25569. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25570. // Indices
  25571. var base = positions.length / 3;
  25572. var rowLength = precision.w + 1;
  25573. for (row = 0; row < precision.h; row++) {
  25574. for (col = 0; col < precision.w; col++) {
  25575. var square = [
  25576. base + col + row * rowLength,
  25577. base + (col + 1) + row * rowLength,
  25578. base + (col + 1) + (row + 1) * rowLength,
  25579. base + col + (row + 1) * rowLength
  25580. ];
  25581. indices.push(square[1]);
  25582. indices.push(square[2]);
  25583. indices.push(square[3]);
  25584. indices.push(square[0]);
  25585. indices.push(square[1]);
  25586. indices.push(square[3]);
  25587. }
  25588. }
  25589. // Position, normals and uvs
  25590. var position = BABYLON.Vector3.Zero();
  25591. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25592. for (row = 0; row <= precision.h; row++) {
  25593. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25594. for (col = 0; col <= precision.w; col++) {
  25595. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25596. position.y = 0;
  25597. positions.push(position.x, position.y, position.z);
  25598. normals.push(normal.x, normal.y, normal.z);
  25599. uvs.push(col / precision.w, row / precision.h);
  25600. }
  25601. }
  25602. }
  25603. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25604. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25605. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25606. }
  25607. }
  25608. // Result
  25609. var vertexData = new VertexData();
  25610. vertexData.indices = indices;
  25611. vertexData.positions = positions;
  25612. vertexData.normals = normals;
  25613. vertexData.uvs = uvs;
  25614. return vertexData;
  25615. };
  25616. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25617. var indices = [];
  25618. var positions = [];
  25619. var normals = [];
  25620. var uvs = [];
  25621. var row, col;
  25622. // Vertices
  25623. for (row = 0; row <= subdivisions; row++) {
  25624. for (col = 0; col <= subdivisions; col++) {
  25625. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25626. // Compute height
  25627. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25628. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25629. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25630. var r = buffer[pos] / 255.0;
  25631. var g = buffer[pos + 1] / 255.0;
  25632. var b = buffer[pos + 2] / 255.0;
  25633. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25634. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25635. // Add vertex
  25636. positions.push(position.x, position.y, position.z);
  25637. normals.push(0, 0, 0);
  25638. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25639. }
  25640. }
  25641. // Indices
  25642. for (row = 0; row < subdivisions; row++) {
  25643. for (col = 0; col < subdivisions; col++) {
  25644. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25645. indices.push(col + 1 + row * (subdivisions + 1));
  25646. indices.push(col + row * (subdivisions + 1));
  25647. indices.push(col + (row + 1) * (subdivisions + 1));
  25648. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25649. indices.push(col + row * (subdivisions + 1));
  25650. }
  25651. }
  25652. // Normals
  25653. VertexData.ComputeNormals(positions, indices, normals);
  25654. // Result
  25655. var vertexData = new VertexData();
  25656. vertexData.indices = indices;
  25657. vertexData.positions = positions;
  25658. vertexData.normals = normals;
  25659. vertexData.uvs = uvs;
  25660. return vertexData;
  25661. };
  25662. VertexData.CreatePlane = function (size, sideOrientation) {
  25663. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25664. var indices = [];
  25665. var positions = [];
  25666. var normals = [];
  25667. var uvs = [];
  25668. size = size || 1;
  25669. // Vertices
  25670. var halfSize = size / 2.0;
  25671. positions.push(-halfSize, -halfSize, 0);
  25672. normals.push(0, 0, -1.0);
  25673. uvs.push(0.0, 0.0);
  25674. positions.push(halfSize, -halfSize, 0);
  25675. normals.push(0, 0, -1.0);
  25676. uvs.push(1.0, 0.0);
  25677. positions.push(halfSize, halfSize, 0);
  25678. normals.push(0, 0, -1.0);
  25679. uvs.push(1.0, 1.0);
  25680. positions.push(-halfSize, halfSize, 0);
  25681. normals.push(0, 0, -1.0);
  25682. uvs.push(0.0, 1.0);
  25683. // Indices
  25684. indices.push(0);
  25685. indices.push(1);
  25686. indices.push(2);
  25687. indices.push(0);
  25688. indices.push(2);
  25689. indices.push(3);
  25690. // Sides
  25691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25692. // Result
  25693. var vertexData = new VertexData();
  25694. vertexData.indices = indices;
  25695. vertexData.positions = positions;
  25696. vertexData.normals = normals;
  25697. vertexData.uvs = uvs;
  25698. return vertexData;
  25699. };
  25700. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25701. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25702. var positions = [];
  25703. var indices = [];
  25704. var normals = [];
  25705. var uvs = [];
  25706. // positions and uvs
  25707. positions.push(0, 0, 0); // disc center first
  25708. uvs.push(0.5, 0.5);
  25709. var step = Math.PI * 2 / tessellation;
  25710. for (var a = 0; a < Math.PI * 2; a += step) {
  25711. var x = Math.cos(a);
  25712. var y = Math.sin(a);
  25713. var u = (x + 1) / 2;
  25714. var v = (1 - y) / 2;
  25715. positions.push(radius * x, radius * y, 0);
  25716. uvs.push(u, v);
  25717. }
  25718. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25719. uvs.push(uvs[2], uvs[3]);
  25720. //indices
  25721. var vertexNb = positions.length / 3;
  25722. for (var i = 1; i < vertexNb - 1; i++) {
  25723. indices.push(i + 1, 0, i);
  25724. }
  25725. // result
  25726. VertexData.ComputeNormals(positions, indices, normals);
  25727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25728. var vertexData = new VertexData();
  25729. vertexData.indices = indices;
  25730. vertexData.positions = positions;
  25731. vertexData.normals = normals;
  25732. vertexData.uvs = uvs;
  25733. return vertexData;
  25734. };
  25735. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25736. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25737. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25738. var indices = [];
  25739. var positions = [];
  25740. var normals = [];
  25741. var uvs = [];
  25742. radius = radius || 2;
  25743. tube = tube || 0.5;
  25744. radialSegments = radialSegments || 32;
  25745. tubularSegments = tubularSegments || 32;
  25746. p = p || 2;
  25747. q = q || 3;
  25748. // Helper
  25749. var getPos = function (angle) {
  25750. var cu = Math.cos(angle);
  25751. var su = Math.sin(angle);
  25752. var quOverP = q / p * angle;
  25753. var cs = Math.cos(quOverP);
  25754. var tx = radius * (2 + cs) * 0.5 * cu;
  25755. var ty = radius * (2 + cs) * su * 0.5;
  25756. var tz = radius * Math.sin(quOverP) * 0.5;
  25757. return new BABYLON.Vector3(tx, ty, tz);
  25758. };
  25759. // Vertices
  25760. for (var i = 0; i <= radialSegments; i++) {
  25761. var modI = i % radialSegments;
  25762. var u = modI / radialSegments * 2 * p * Math.PI;
  25763. var p1 = getPos(u);
  25764. var p2 = getPos(u + 0.01);
  25765. var tang = p2.subtract(p1);
  25766. var n = p2.add(p1);
  25767. var bitan = BABYLON.Vector3.Cross(tang, n);
  25768. n = BABYLON.Vector3.Cross(bitan, tang);
  25769. bitan.normalize();
  25770. n.normalize();
  25771. for (var j = 0; j < tubularSegments; j++) {
  25772. var modJ = j % tubularSegments;
  25773. var v = modJ / tubularSegments * 2 * Math.PI;
  25774. var cx = -tube * Math.cos(v);
  25775. var cy = tube * Math.sin(v);
  25776. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25777. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25778. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25779. uvs.push(i / radialSegments);
  25780. uvs.push(j / tubularSegments);
  25781. }
  25782. }
  25783. for (i = 0; i < radialSegments; i++) {
  25784. for (j = 0; j < tubularSegments; j++) {
  25785. var jNext = (j + 1) % tubularSegments;
  25786. var a = i * tubularSegments + j;
  25787. var b = (i + 1) * tubularSegments + j;
  25788. var c = (i + 1) * tubularSegments + jNext;
  25789. var d = i * tubularSegments + jNext;
  25790. indices.push(d);
  25791. indices.push(b);
  25792. indices.push(a);
  25793. indices.push(d);
  25794. indices.push(c);
  25795. indices.push(b);
  25796. }
  25797. }
  25798. // Normals
  25799. VertexData.ComputeNormals(positions, indices, normals);
  25800. // Sides
  25801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25802. // Result
  25803. var vertexData = new VertexData();
  25804. vertexData.indices = indices;
  25805. vertexData.positions = positions;
  25806. vertexData.normals = normals;
  25807. vertexData.uvs = uvs;
  25808. return vertexData;
  25809. };
  25810. // Tools
  25811. /**
  25812. * @param {any} - positions (number[] or Float32Array)
  25813. * @param {any} - indices (number[] or Uint16Array)
  25814. * @param {any} - normals (number[] or Float32Array)
  25815. */
  25816. VertexData.ComputeNormals = function (positions, indices, normals) {
  25817. var index = 0;
  25818. // temp Vector3
  25819. var p1 = BABYLON.Vector3.Zero();
  25820. var p2 = BABYLON.Vector3.Zero();
  25821. var p3 = BABYLON.Vector3.Zero();
  25822. var p1p2 = BABYLON.Vector3.Zero();
  25823. var p3p2 = BABYLON.Vector3.Zero();
  25824. var faceNormal = BABYLON.Vector3.Zero();
  25825. var vertexNormali1 = BABYLON.Vector3.Zero();
  25826. var vertexNormali2 = BABYLON.Vector3.Zero();
  25827. var vertexNormali3 = BABYLON.Vector3.Zero();
  25828. // indice triplet = 1 face
  25829. var nbFaces = indices.length / 3;
  25830. for (index = 0; index < nbFaces; index++) {
  25831. var i1 = indices[index * 3];
  25832. var i2 = indices[index * 3 + 1];
  25833. var i3 = indices[index * 3 + 2];
  25834. // setting the temp V3
  25835. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25836. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25837. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25838. p1.subtractToRef(p2, p1p2);
  25839. p3.subtractToRef(p2, p3p2);
  25840. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25841. faceNormal.normalize();
  25842. // All intermediate results are stored in the normals array :
  25843. // get the normals at i1, i2 and i3 indexes
  25844. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25845. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25846. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25847. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25848. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25849. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25850. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25851. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25852. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25853. // make intermediate vectors3 from normals values
  25854. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25855. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25856. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25857. // add the current face normals to these intermediate vectors3
  25858. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25859. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25860. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25861. // store back intermediate vectors3 into the normals array
  25862. normals[i1 * 3] = vertexNormali1.x;
  25863. normals[i1 * 3 + 1] = vertexNormali1.y;
  25864. normals[i1 * 3 + 2] = vertexNormali1.z;
  25865. normals[i2 * 3] = vertexNormali2.x;
  25866. normals[i2 * 3 + 1] = vertexNormali2.y;
  25867. normals[i2 * 3 + 2] = vertexNormali2.z;
  25868. normals[i3 * 3] = vertexNormali3.x;
  25869. normals[i3 * 3 + 1] = vertexNormali3.y;
  25870. normals[i3 * 3 + 2] = vertexNormali3.z;
  25871. }
  25872. // last normalization
  25873. for (index = 0; index < normals.length / 3; index++) {
  25874. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25875. vertexNormali1.normalize();
  25876. normals[index * 3] = vertexNormali1.x;
  25877. normals[index * 3 + 1] = vertexNormali1.y;
  25878. normals[index * 3 + 2] = vertexNormali1.z;
  25879. }
  25880. };
  25881. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25882. var li = indices.length;
  25883. var ln = normals.length;
  25884. var i;
  25885. var n;
  25886. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25887. switch (sideOrientation) {
  25888. case BABYLON.Mesh.FRONTSIDE:
  25889. // nothing changed
  25890. break;
  25891. case BABYLON.Mesh.BACKSIDE:
  25892. var tmp;
  25893. // indices
  25894. for (i = 0; i < li; i += 3) {
  25895. tmp = indices[i];
  25896. indices[i] = indices[i + 2];
  25897. indices[i + 2] = tmp;
  25898. }
  25899. // normals
  25900. for (n = 0; n < ln; n++) {
  25901. normals[n] = -normals[n];
  25902. }
  25903. break;
  25904. case BABYLON.Mesh.DOUBLESIDE:
  25905. // positions
  25906. var lp = positions.length;
  25907. var l = lp / 3;
  25908. for (var p = 0; p < lp; p++) {
  25909. positions[lp + p] = positions[p];
  25910. }
  25911. // indices
  25912. for (i = 0; i < li; i += 3) {
  25913. indices[i + li] = indices[i + 2] + l;
  25914. indices[i + 1 + li] = indices[i + 1] + l;
  25915. indices[i + 2 + li] = indices[i] + l;
  25916. }
  25917. // normals
  25918. for (n = 0; n < ln; n++) {
  25919. normals[ln + n] = -normals[n];
  25920. }
  25921. // uvs
  25922. var lu = uvs.length;
  25923. for (var u = 0; u < lu; u++) {
  25924. uvs[u + lu] = uvs[u];
  25925. }
  25926. break;
  25927. }
  25928. };
  25929. return VertexData;
  25930. })();
  25931. BABYLON.VertexData = VertexData;
  25932. })(BABYLON || (BABYLON = {}));
  25933. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25934. var __extends = this.__extends || function (d, b) {
  25935. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25936. function __() { this.constructor = d; }
  25937. __.prototype = b.prototype;
  25938. d.prototype = new __();
  25939. };
  25940. var BABYLON;
  25941. (function (BABYLON) {
  25942. var AnaglyphFreeCamera = (function (_super) {
  25943. __extends(AnaglyphFreeCamera, _super);
  25944. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25945. _super.call(this, name, position, scene);
  25946. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25947. }
  25948. return AnaglyphFreeCamera;
  25949. })(BABYLON.FreeCamera);
  25950. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25951. var AnaglyphArcRotateCamera = (function (_super) {
  25952. __extends(AnaglyphArcRotateCamera, _super);
  25953. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25954. _super.call(this, name, alpha, beta, radius, target, scene);
  25955. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25956. }
  25957. return AnaglyphArcRotateCamera;
  25958. })(BABYLON.ArcRotateCamera);
  25959. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25960. var AnaglyphGamepadCamera = (function (_super) {
  25961. __extends(AnaglyphGamepadCamera, _super);
  25962. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  25963. _super.call(this, name, position, scene);
  25964. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25965. }
  25966. return AnaglyphGamepadCamera;
  25967. })(BABYLON.GamepadCamera);
  25968. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  25969. })(BABYLON || (BABYLON = {}));
  25970. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25971. var __extends = this.__extends || function (d, b) {
  25972. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25973. function __() { this.constructor = d; }
  25974. __.prototype = b.prototype;
  25975. d.prototype = new __();
  25976. };
  25977. var BABYLON;
  25978. (function (BABYLON) {
  25979. var AnaglyphPostProcess = (function (_super) {
  25980. __extends(AnaglyphPostProcess, _super);
  25981. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25982. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25983. }
  25984. return AnaglyphPostProcess;
  25985. })(BABYLON.PostProcess);
  25986. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25987. })(BABYLON || (BABYLON = {}));
  25988. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25989. var BABYLON;
  25990. (function (BABYLON) {
  25991. var Tags = (function () {
  25992. function Tags() {
  25993. }
  25994. Tags.EnableFor = function (obj) {
  25995. obj._tags = obj._tags || {};
  25996. obj.hasTags = function () {
  25997. return Tags.HasTags(obj);
  25998. };
  25999. obj.addTags = function (tagsString) {
  26000. return Tags.AddTagsTo(obj, tagsString);
  26001. };
  26002. obj.removeTags = function (tagsString) {
  26003. return Tags.RemoveTagsFrom(obj, tagsString);
  26004. };
  26005. obj.matchesTagsQuery = function (tagsQuery) {
  26006. return Tags.MatchesQuery(obj, tagsQuery);
  26007. };
  26008. };
  26009. Tags.DisableFor = function (obj) {
  26010. delete obj._tags;
  26011. delete obj.hasTags;
  26012. delete obj.addTags;
  26013. delete obj.removeTags;
  26014. delete obj.matchesTagsQuery;
  26015. };
  26016. Tags.HasTags = function (obj) {
  26017. if (!obj._tags) {
  26018. return false;
  26019. }
  26020. return !BABYLON.Tools.IsEmpty(obj._tags);
  26021. };
  26022. Tags.GetTags = function (obj) {
  26023. if (!obj._tags) {
  26024. return null;
  26025. }
  26026. return obj._tags;
  26027. };
  26028. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26029. // a tag cannot start with '||', '&&', and '!'
  26030. // it cannot contain whitespaces
  26031. Tags.AddTagsTo = function (obj, tagsString) {
  26032. if (!tagsString) {
  26033. return;
  26034. }
  26035. var tags = tagsString.split(" ");
  26036. for (var t in tags) {
  26037. Tags._AddTagTo(obj, tags[t]);
  26038. }
  26039. };
  26040. Tags._AddTagTo = function (obj, tag) {
  26041. tag = tag.trim();
  26042. if (tag === "" || tag === "true" || tag === "false") {
  26043. return;
  26044. }
  26045. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26046. return;
  26047. }
  26048. Tags.EnableFor(obj);
  26049. obj._tags[tag] = true;
  26050. };
  26051. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26052. if (!Tags.HasTags(obj)) {
  26053. return;
  26054. }
  26055. var tags = tagsString.split(" ");
  26056. for (var t in tags) {
  26057. Tags._RemoveTagFrom(obj, tags[t]);
  26058. }
  26059. };
  26060. Tags._RemoveTagFrom = function (obj, tag) {
  26061. delete obj._tags[tag];
  26062. };
  26063. Tags.MatchesQuery = function (obj, tagsQuery) {
  26064. if (tagsQuery === undefined) {
  26065. return true;
  26066. }
  26067. if (tagsQuery === "") {
  26068. return Tags.HasTags(obj);
  26069. }
  26070. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26071. };
  26072. return Tags;
  26073. })();
  26074. BABYLON.Tags = Tags;
  26075. })(BABYLON || (BABYLON = {}));
  26076. //# sourceMappingURL=babylon.tags.js.map
  26077. var BABYLON;
  26078. (function (BABYLON) {
  26079. var Internals;
  26080. (function (Internals) {
  26081. var AndOrNotEvaluator = (function () {
  26082. function AndOrNotEvaluator() {
  26083. }
  26084. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26085. if (!query.match(/\([^\(\)]*\)/g)) {
  26086. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26087. }
  26088. else {
  26089. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26090. // remove parenthesis
  26091. r = r.slice(1, r.length - 1);
  26092. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26093. });
  26094. }
  26095. if (query === "true") {
  26096. return true;
  26097. }
  26098. if (query === "false") {
  26099. return false;
  26100. }
  26101. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26102. };
  26103. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26104. evaluateCallback = evaluateCallback || (function (r) {
  26105. return r === "true" ? true : false;
  26106. });
  26107. var result;
  26108. var or = parenthesisContent.split("||");
  26109. for (var i in or) {
  26110. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26111. var and = ori.split("&&");
  26112. if (and.length > 1) {
  26113. for (var j = 0; j < and.length; ++j) {
  26114. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26115. if (andj !== "true" && andj !== "false") {
  26116. if (andj[0] === "!") {
  26117. result = !evaluateCallback(andj.substring(1));
  26118. }
  26119. else {
  26120. result = evaluateCallback(andj);
  26121. }
  26122. }
  26123. else {
  26124. result = andj === "true" ? true : false;
  26125. }
  26126. if (!result) {
  26127. ori = "false";
  26128. break;
  26129. }
  26130. }
  26131. }
  26132. if (result || ori === "true") {
  26133. result = true;
  26134. break;
  26135. }
  26136. // result equals false (or undefined)
  26137. if (ori !== "true" && ori !== "false") {
  26138. if (ori[0] === "!") {
  26139. result = !evaluateCallback(ori.substring(1));
  26140. }
  26141. else {
  26142. result = evaluateCallback(ori);
  26143. }
  26144. }
  26145. else {
  26146. result = ori === "true" ? true : false;
  26147. }
  26148. }
  26149. // the whole parenthesis scope is replaced by 'true' or 'false'
  26150. return result ? "true" : "false";
  26151. };
  26152. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26153. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26154. // remove whitespaces
  26155. r = r.replace(/[\s]/g, function () { return ""; });
  26156. return r.length % 2 ? "!" : "";
  26157. });
  26158. booleanString = booleanString.trim();
  26159. if (booleanString === "!true") {
  26160. booleanString = "false";
  26161. }
  26162. else if (booleanString === "!false") {
  26163. booleanString = "true";
  26164. }
  26165. return booleanString;
  26166. };
  26167. return AndOrNotEvaluator;
  26168. })();
  26169. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26170. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26171. })(BABYLON || (BABYLON = {}));
  26172. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26173. var BABYLON;
  26174. (function (BABYLON) {
  26175. var PostProcessRenderPass = (function () {
  26176. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26177. this._enabled = true;
  26178. this._refCount = 0;
  26179. this._name = name;
  26180. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26181. this.setRenderList(renderList);
  26182. this._renderTexture.onBeforeRender = beforeRender;
  26183. this._renderTexture.onAfterRender = afterRender;
  26184. this._scene = scene;
  26185. this._renderList = renderList;
  26186. }
  26187. // private
  26188. PostProcessRenderPass.prototype._incRefCount = function () {
  26189. if (this._refCount === 0) {
  26190. this._scene.customRenderTargets.push(this._renderTexture);
  26191. }
  26192. return ++this._refCount;
  26193. };
  26194. PostProcessRenderPass.prototype._decRefCount = function () {
  26195. this._refCount--;
  26196. if (this._refCount <= 0) {
  26197. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26198. }
  26199. return this._refCount;
  26200. };
  26201. PostProcessRenderPass.prototype._update = function () {
  26202. this.setRenderList(this._renderList);
  26203. };
  26204. // public
  26205. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26206. this._renderTexture.renderList = renderList;
  26207. };
  26208. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26209. return this._renderTexture;
  26210. };
  26211. return PostProcessRenderPass;
  26212. })();
  26213. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26214. })(BABYLON || (BABYLON = {}));
  26215. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26216. var BABYLON;
  26217. (function (BABYLON) {
  26218. var PostProcessRenderEffect = (function () {
  26219. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26220. this._engine = engine;
  26221. this._name = name;
  26222. this._singleInstance = singleInstance || true;
  26223. this._getPostProcess = getPostProcess;
  26224. this._cameras = [];
  26225. this._indicesForCamera = [];
  26226. this._postProcesses = {};
  26227. this._renderPasses = {};
  26228. this._renderEffectAsPasses = {};
  26229. }
  26230. PostProcessRenderEffect.prototype._update = function () {
  26231. for (var renderPassName in this._renderPasses) {
  26232. this._renderPasses[renderPassName]._update();
  26233. }
  26234. };
  26235. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26236. this._renderPasses[renderPass._name] = renderPass;
  26237. this._linkParameters();
  26238. };
  26239. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26240. delete this._renderPasses[renderPass._name];
  26241. this._linkParameters();
  26242. };
  26243. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26244. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26245. this._linkParameters();
  26246. };
  26247. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26248. for (var renderPassName in this._renderPasses) {
  26249. if (renderPassName === passName) {
  26250. return this._renderPasses[passName];
  26251. }
  26252. }
  26253. };
  26254. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26255. this._renderPasses = {};
  26256. this._linkParameters();
  26257. };
  26258. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26259. var cameraKey;
  26260. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26261. for (var i = 0; i < _cam.length; i++) {
  26262. var camera = _cam[i];
  26263. var cameraName = camera.name;
  26264. if (this._singleInstance) {
  26265. cameraKey = 0;
  26266. }
  26267. else {
  26268. cameraKey = cameraName;
  26269. }
  26270. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26271. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26272. if (!this._indicesForCamera[cameraName]) {
  26273. this._indicesForCamera[cameraName] = [];
  26274. }
  26275. this._indicesForCamera[cameraName].push(index);
  26276. if (this._cameras.indexOf(camera) === -1) {
  26277. this._cameras[cameraName] = camera;
  26278. }
  26279. for (var passName in this._renderPasses) {
  26280. this._renderPasses[passName]._incRefCount();
  26281. }
  26282. }
  26283. this._linkParameters();
  26284. };
  26285. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26286. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26287. for (var i = 0; i < _cam.length; i++) {
  26288. var camera = _cam[i];
  26289. var cameraName = camera.name;
  26290. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26291. var index = this._cameras.indexOf(cameraName);
  26292. this._indicesForCamera.splice(index, 1);
  26293. this._cameras.splice(index, 1);
  26294. for (var passName in this._renderPasses) {
  26295. this._renderPasses[passName]._decRefCount();
  26296. }
  26297. }
  26298. };
  26299. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26300. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26301. for (var i = 0; i < _cam.length; i++) {
  26302. var camera = _cam[i];
  26303. var cameraName = camera.name;
  26304. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26305. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26306. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26307. }
  26308. }
  26309. for (var passName in this._renderPasses) {
  26310. this._renderPasses[passName]._incRefCount();
  26311. }
  26312. }
  26313. };
  26314. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26315. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26316. for (var i = 0; i < _cam.length; i++) {
  26317. var camera = _cam[i];
  26318. var cameraName = camera.Name;
  26319. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26320. for (var passName in this._renderPasses) {
  26321. this._renderPasses[passName]._decRefCount();
  26322. }
  26323. }
  26324. };
  26325. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26326. if (this._singleInstance) {
  26327. return this._postProcesses[0];
  26328. }
  26329. else {
  26330. return this._postProcesses[camera.name];
  26331. }
  26332. };
  26333. PostProcessRenderEffect.prototype._linkParameters = function () {
  26334. var _this = this;
  26335. for (var index in this._postProcesses) {
  26336. if (this.applyParameters) {
  26337. this.applyParameters(this._postProcesses[index]);
  26338. }
  26339. this._postProcesses[index].onBeforeRender = function (effect) {
  26340. _this._linkTextures(effect);
  26341. };
  26342. }
  26343. };
  26344. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26345. for (var renderPassName in this._renderPasses) {
  26346. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26347. }
  26348. for (var renderEffectName in this._renderEffectAsPasses) {
  26349. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26350. }
  26351. };
  26352. return PostProcessRenderEffect;
  26353. })();
  26354. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26355. })(BABYLON || (BABYLON = {}));
  26356. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26357. var BABYLON;
  26358. (function (BABYLON) {
  26359. var PostProcessRenderPipeline = (function () {
  26360. function PostProcessRenderPipeline(engine, name) {
  26361. this._engine = engine;
  26362. this._name = name;
  26363. this._renderEffects = {};
  26364. this._renderEffectsForIsolatedPass = {};
  26365. this._cameras = [];
  26366. }
  26367. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26368. this._renderEffects[renderEffect._name] = renderEffect;
  26369. };
  26370. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26371. var renderEffects = this._renderEffects[renderEffectName];
  26372. if (!renderEffects) {
  26373. return;
  26374. }
  26375. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26376. };
  26377. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26378. var renderEffects = this._renderEffects[renderEffectName];
  26379. if (!renderEffects) {
  26380. return;
  26381. }
  26382. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26383. };
  26384. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26385. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26386. var indicesToDelete = [];
  26387. for (var i = 0; i < _cam.length; i++) {
  26388. var camera = _cam[i];
  26389. var cameraName = camera.name;
  26390. if (this._cameras.indexOf(camera) === -1) {
  26391. this._cameras[cameraName] = camera;
  26392. }
  26393. else if (unique) {
  26394. indicesToDelete.push(i);
  26395. }
  26396. }
  26397. for (var i = 0; i < indicesToDelete.length; i++) {
  26398. cameras.splice(indicesToDelete[i], 1);
  26399. }
  26400. for (var renderEffectName in this._renderEffects) {
  26401. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26402. }
  26403. };
  26404. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26405. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26406. for (var renderEffectName in this._renderEffects) {
  26407. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26408. }
  26409. for (var i = 0; i < _cam.length; i++) {
  26410. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26411. }
  26412. };
  26413. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26414. var _this = this;
  26415. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26416. var pass = null;
  26417. for (var renderEffectName in this._renderEffects) {
  26418. pass = this._renderEffects[renderEffectName].getPass(passName);
  26419. if (pass != null) {
  26420. break;
  26421. }
  26422. }
  26423. if (pass === null) {
  26424. return;
  26425. }
  26426. for (var renderEffectName in this._renderEffects) {
  26427. this._renderEffects[renderEffectName]._disable(_cam);
  26428. }
  26429. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26430. for (var i = 0; i < _cam.length; i++) {
  26431. var camera = _cam[i];
  26432. var cameraName = camera.name;
  26433. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26434. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26435. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26436. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26437. }
  26438. };
  26439. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26440. var _this = this;
  26441. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26442. for (var i = 0; i < _cam.length; i++) {
  26443. var camera = _cam[i];
  26444. var cameraName = camera.name;
  26445. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26446. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26447. }
  26448. for (var renderEffectName in this._renderEffects) {
  26449. this._renderEffects[renderEffectName]._enable(_cam);
  26450. }
  26451. };
  26452. PostProcessRenderPipeline.prototype._update = function () {
  26453. for (var renderEffectName in this._renderEffects) {
  26454. this._renderEffects[renderEffectName]._update();
  26455. }
  26456. for (var i = 0; i < this._cameras.length; i++) {
  26457. var cameraName = this._cameras[i].name;
  26458. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26459. this._renderEffectsForIsolatedPass[cameraName]._update();
  26460. }
  26461. }
  26462. };
  26463. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26464. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26465. return PostProcessRenderPipeline;
  26466. })();
  26467. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26468. })(BABYLON || (BABYLON = {}));
  26469. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26470. var BABYLON;
  26471. (function (BABYLON) {
  26472. var PostProcessRenderPipelineManager = (function () {
  26473. function PostProcessRenderPipelineManager() {
  26474. this._renderPipelines = {};
  26475. }
  26476. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26477. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26478. };
  26479. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26480. var renderPipeline = this._renderPipelines[renderPipelineName];
  26481. if (!renderPipeline) {
  26482. return;
  26483. }
  26484. renderPipeline._attachCameras(cameras, unique);
  26485. };
  26486. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26487. var renderPipeline = this._renderPipelines[renderPipelineName];
  26488. if (!renderPipeline) {
  26489. return;
  26490. }
  26491. renderPipeline._detachCameras(cameras);
  26492. };
  26493. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26494. var renderPipeline = this._renderPipelines[renderPipelineName];
  26495. if (!renderPipeline) {
  26496. return;
  26497. }
  26498. renderPipeline._enableEffect(renderEffectName, cameras);
  26499. };
  26500. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26501. var renderPipeline = this._renderPipelines[renderPipelineName];
  26502. if (!renderPipeline) {
  26503. return;
  26504. }
  26505. renderPipeline._disableEffect(renderEffectName, cameras);
  26506. };
  26507. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26508. var renderPipeline = this._renderPipelines[renderPipelineName];
  26509. if (!renderPipeline) {
  26510. return;
  26511. }
  26512. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26513. };
  26514. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26515. var renderPipeline = this._renderPipelines[renderPipelineName];
  26516. if (!renderPipeline) {
  26517. return;
  26518. }
  26519. renderPipeline._disableDisplayOnlyPass(cameras);
  26520. };
  26521. PostProcessRenderPipelineManager.prototype.update = function () {
  26522. for (var renderPipelineName in this._renderPipelines) {
  26523. this._renderPipelines[renderPipelineName]._update();
  26524. }
  26525. };
  26526. return PostProcessRenderPipelineManager;
  26527. })();
  26528. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26529. })(BABYLON || (BABYLON = {}));
  26530. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26531. var __extends = this.__extends || function (d, b) {
  26532. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26533. function __() { this.constructor = d; }
  26534. __.prototype = b.prototype;
  26535. d.prototype = new __();
  26536. };
  26537. var BABYLON;
  26538. (function (BABYLON) {
  26539. var DisplayPassPostProcess = (function (_super) {
  26540. __extends(DisplayPassPostProcess, _super);
  26541. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26542. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26543. }
  26544. return DisplayPassPostProcess;
  26545. })(BABYLON.PostProcess);
  26546. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26547. })(BABYLON || (BABYLON = {}));
  26548. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26549. var BABYLON;
  26550. (function (BABYLON) {
  26551. var BoundingBoxRenderer = (function () {
  26552. function BoundingBoxRenderer(scene) {
  26553. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26554. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26555. this.showBackLines = true;
  26556. this.renderList = new BABYLON.SmartArray(32);
  26557. this._scene = scene;
  26558. }
  26559. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26560. if (this._colorShader) {
  26561. return;
  26562. }
  26563. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26564. attributes: ["position"],
  26565. uniforms: ["worldViewProjection", "color"]
  26566. });
  26567. var engine = this._scene.getEngine();
  26568. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26569. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26570. 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]);
  26571. };
  26572. BoundingBoxRenderer.prototype.reset = function () {
  26573. this.renderList.reset();
  26574. };
  26575. BoundingBoxRenderer.prototype.render = function () {
  26576. if (this.renderList.length === 0) {
  26577. return;
  26578. }
  26579. this._prepareRessources();
  26580. if (!this._colorShader.isReady()) {
  26581. return;
  26582. }
  26583. var engine = this._scene.getEngine();
  26584. engine.setDepthWrite(false);
  26585. this._colorShader._preBind();
  26586. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26587. var boundingBox = this.renderList.data[boundingBoxIndex];
  26588. var min = boundingBox.minimum;
  26589. var max = boundingBox.maximum;
  26590. var diff = max.subtract(min);
  26591. var median = min.add(diff.scale(0.5));
  26592. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26593. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26594. .multiply(boundingBox.getWorldMatrix());
  26595. // VBOs
  26596. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26597. if (this.showBackLines) {
  26598. // Back
  26599. engine.setDepthFunctionToGreaterOrEqual();
  26600. this._scene.resetCachedMaterial();
  26601. this._colorShader.setColor4("color", this.backColor.toColor4());
  26602. this._colorShader.bind(worldMatrix);
  26603. // Draw order
  26604. engine.draw(false, 0, 24);
  26605. }
  26606. // Front
  26607. engine.setDepthFunctionToLess();
  26608. this._scene.resetCachedMaterial();
  26609. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26610. this._colorShader.bind(worldMatrix);
  26611. // Draw order
  26612. engine.draw(false, 0, 24);
  26613. }
  26614. this._colorShader.unbind();
  26615. engine.setDepthFunctionToLessOrEqual();
  26616. engine.setDepthWrite(true);
  26617. };
  26618. BoundingBoxRenderer.prototype.dispose = function () {
  26619. if (!this._colorShader) {
  26620. return;
  26621. }
  26622. this._colorShader.dispose();
  26623. this._vb.dispose();
  26624. this._scene.getEngine()._releaseBuffer(this._ib);
  26625. };
  26626. return BoundingBoxRenderer;
  26627. })();
  26628. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26629. })(BABYLON || (BABYLON = {}));
  26630. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26631. var __extends = this.__extends || function (d, b) {
  26632. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26633. function __() { this.constructor = d; }
  26634. __.prototype = b.prototype;
  26635. d.prototype = new __();
  26636. };
  26637. var BABYLON;
  26638. (function (BABYLON) {
  26639. var Condition = (function () {
  26640. function Condition(actionManager) {
  26641. this._actionManager = actionManager;
  26642. }
  26643. Condition.prototype.isValid = function () {
  26644. return true;
  26645. };
  26646. Condition.prototype._getProperty = function (propertyPath) {
  26647. return this._actionManager._getProperty(propertyPath);
  26648. };
  26649. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26650. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26651. };
  26652. return Condition;
  26653. })();
  26654. BABYLON.Condition = Condition;
  26655. var ValueCondition = (function (_super) {
  26656. __extends(ValueCondition, _super);
  26657. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26658. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26659. _super.call(this, actionManager);
  26660. this.propertyPath = propertyPath;
  26661. this.value = value;
  26662. this.operator = operator;
  26663. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26664. this._property = this._getProperty(this.propertyPath);
  26665. }
  26666. Object.defineProperty(ValueCondition, "IsEqual", {
  26667. get: function () {
  26668. return ValueCondition._IsEqual;
  26669. },
  26670. enumerable: true,
  26671. configurable: true
  26672. });
  26673. Object.defineProperty(ValueCondition, "IsDifferent", {
  26674. get: function () {
  26675. return ValueCondition._IsDifferent;
  26676. },
  26677. enumerable: true,
  26678. configurable: true
  26679. });
  26680. Object.defineProperty(ValueCondition, "IsGreater", {
  26681. get: function () {
  26682. return ValueCondition._IsGreater;
  26683. },
  26684. enumerable: true,
  26685. configurable: true
  26686. });
  26687. Object.defineProperty(ValueCondition, "IsLesser", {
  26688. get: function () {
  26689. return ValueCondition._IsLesser;
  26690. },
  26691. enumerable: true,
  26692. configurable: true
  26693. });
  26694. // Methods
  26695. ValueCondition.prototype.isValid = function () {
  26696. switch (this.operator) {
  26697. case ValueCondition.IsGreater:
  26698. return this._target[this._property] > this.value;
  26699. case ValueCondition.IsLesser:
  26700. return this._target[this._property] < this.value;
  26701. case ValueCondition.IsEqual:
  26702. case ValueCondition.IsDifferent:
  26703. var check;
  26704. if (this.value.equals) {
  26705. check = this.value.equals(this._target[this._property]);
  26706. }
  26707. else {
  26708. check = this.value === this._target[this._property];
  26709. }
  26710. return this.operator === ValueCondition.IsEqual ? check : !check;
  26711. }
  26712. return false;
  26713. };
  26714. // Statics
  26715. ValueCondition._IsEqual = 0;
  26716. ValueCondition._IsDifferent = 1;
  26717. ValueCondition._IsGreater = 2;
  26718. ValueCondition._IsLesser = 3;
  26719. return ValueCondition;
  26720. })(Condition);
  26721. BABYLON.ValueCondition = ValueCondition;
  26722. var PredicateCondition = (function (_super) {
  26723. __extends(PredicateCondition, _super);
  26724. function PredicateCondition(actionManager, predicate) {
  26725. _super.call(this, actionManager);
  26726. this.predicate = predicate;
  26727. }
  26728. PredicateCondition.prototype.isValid = function () {
  26729. return this.predicate();
  26730. };
  26731. return PredicateCondition;
  26732. })(Condition);
  26733. BABYLON.PredicateCondition = PredicateCondition;
  26734. var StateCondition = (function (_super) {
  26735. __extends(StateCondition, _super);
  26736. function StateCondition(actionManager, target, value) {
  26737. _super.call(this, actionManager);
  26738. this.value = value;
  26739. this._target = target;
  26740. }
  26741. // Methods
  26742. StateCondition.prototype.isValid = function () {
  26743. return this._target.state === this.value;
  26744. };
  26745. return StateCondition;
  26746. })(Condition);
  26747. BABYLON.StateCondition = StateCondition;
  26748. })(BABYLON || (BABYLON = {}));
  26749. //# sourceMappingURL=babylon.condition.js.map
  26750. var BABYLON;
  26751. (function (BABYLON) {
  26752. var Action = (function () {
  26753. function Action(triggerOptions, condition) {
  26754. this.triggerOptions = triggerOptions;
  26755. if (triggerOptions.parameter) {
  26756. this.trigger = triggerOptions.trigger;
  26757. this._triggerParameter = triggerOptions.parameter;
  26758. }
  26759. else {
  26760. this.trigger = triggerOptions;
  26761. }
  26762. this._nextActiveAction = this;
  26763. this._condition = condition;
  26764. }
  26765. // Methods
  26766. Action.prototype._prepare = function () {
  26767. };
  26768. Action.prototype.getTriggerParameter = function () {
  26769. return this._triggerParameter;
  26770. };
  26771. Action.prototype._executeCurrent = function (evt) {
  26772. if (this._nextActiveAction._condition) {
  26773. var condition = this._nextActiveAction._condition;
  26774. var currentRenderId = this._actionManager.getScene().getRenderId();
  26775. // We cache the current evaluation for the current frame
  26776. if (condition._evaluationId === currentRenderId) {
  26777. if (!condition._currentResult) {
  26778. return;
  26779. }
  26780. }
  26781. else {
  26782. condition._evaluationId = currentRenderId;
  26783. if (!condition.isValid()) {
  26784. condition._currentResult = false;
  26785. return;
  26786. }
  26787. condition._currentResult = true;
  26788. }
  26789. }
  26790. this._nextActiveAction.execute(evt);
  26791. if (this._nextActiveAction._child) {
  26792. if (!this._nextActiveAction._child._actionManager) {
  26793. this._nextActiveAction._child._actionManager = this._actionManager;
  26794. }
  26795. this._nextActiveAction = this._nextActiveAction._child;
  26796. }
  26797. else {
  26798. this._nextActiveAction = this;
  26799. }
  26800. };
  26801. Action.prototype.execute = function (evt) {
  26802. };
  26803. Action.prototype.then = function (action) {
  26804. this._child = action;
  26805. action._actionManager = this._actionManager;
  26806. action._prepare();
  26807. return action;
  26808. };
  26809. Action.prototype._getProperty = function (propertyPath) {
  26810. return this._actionManager._getProperty(propertyPath);
  26811. };
  26812. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26813. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26814. };
  26815. return Action;
  26816. })();
  26817. BABYLON.Action = Action;
  26818. })(BABYLON || (BABYLON = {}));
  26819. //# sourceMappingURL=babylon.action.js.map
  26820. var BABYLON;
  26821. (function (BABYLON) {
  26822. /**
  26823. * ActionEvent is the event beint sent when an action is triggered.
  26824. */
  26825. var ActionEvent = (function () {
  26826. /**
  26827. * @constructor
  26828. * @param source The mesh that triggered the action.
  26829. * @param pointerX the X mouse cursor position at the time of the event
  26830. * @param pointerY the Y mouse cursor position at the time of the event
  26831. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26832. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26833. */
  26834. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26835. this.source = source;
  26836. this.pointerX = pointerX;
  26837. this.pointerY = pointerY;
  26838. this.meshUnderPointer = meshUnderPointer;
  26839. this.sourceEvent = sourceEvent;
  26840. }
  26841. /**
  26842. * Helper function to auto-create an ActionEvent from a source mesh.
  26843. * @param source the source mesh that triggered the event
  26844. * @param evt {Event} The original (browser) event
  26845. */
  26846. ActionEvent.CreateNew = function (source, evt) {
  26847. var scene = source.getScene();
  26848. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26849. };
  26850. /**
  26851. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26852. * @param scene the scene where the event occurred
  26853. * @param evt {Event} The original (browser) event
  26854. */
  26855. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26856. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26857. };
  26858. return ActionEvent;
  26859. })();
  26860. BABYLON.ActionEvent = ActionEvent;
  26861. /**
  26862. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26863. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26864. */
  26865. var ActionManager = (function () {
  26866. function ActionManager(scene) {
  26867. // Members
  26868. this.actions = new Array();
  26869. this._scene = scene;
  26870. scene._actionManagers.push(this);
  26871. }
  26872. Object.defineProperty(ActionManager, "NothingTrigger", {
  26873. get: function () {
  26874. return ActionManager._NothingTrigger;
  26875. },
  26876. enumerable: true,
  26877. configurable: true
  26878. });
  26879. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26880. get: function () {
  26881. return ActionManager._OnPickTrigger;
  26882. },
  26883. enumerable: true,
  26884. configurable: true
  26885. });
  26886. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26887. get: function () {
  26888. return ActionManager._OnLeftPickTrigger;
  26889. },
  26890. enumerable: true,
  26891. configurable: true
  26892. });
  26893. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26894. get: function () {
  26895. return ActionManager._OnRightPickTrigger;
  26896. },
  26897. enumerable: true,
  26898. configurable: true
  26899. });
  26900. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26901. get: function () {
  26902. return ActionManager._OnCenterPickTrigger;
  26903. },
  26904. enumerable: true,
  26905. configurable: true
  26906. });
  26907. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26908. get: function () {
  26909. return ActionManager._OnPointerOverTrigger;
  26910. },
  26911. enumerable: true,
  26912. configurable: true
  26913. });
  26914. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26915. get: function () {
  26916. return ActionManager._OnPointerOutTrigger;
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26922. get: function () {
  26923. return ActionManager._OnEveryFrameTrigger;
  26924. },
  26925. enumerable: true,
  26926. configurable: true
  26927. });
  26928. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26929. get: function () {
  26930. return ActionManager._OnIntersectionEnterTrigger;
  26931. },
  26932. enumerable: true,
  26933. configurable: true
  26934. });
  26935. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26936. get: function () {
  26937. return ActionManager._OnIntersectionExitTrigger;
  26938. },
  26939. enumerable: true,
  26940. configurable: true
  26941. });
  26942. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26943. get: function () {
  26944. return ActionManager._OnKeyDownTrigger;
  26945. },
  26946. enumerable: true,
  26947. configurable: true
  26948. });
  26949. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26950. get: function () {
  26951. return ActionManager._OnKeyUpTrigger;
  26952. },
  26953. enumerable: true,
  26954. configurable: true
  26955. });
  26956. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26957. get: function () {
  26958. return ActionManager._OnPickUpTrigger;
  26959. },
  26960. enumerable: true,
  26961. configurable: true
  26962. });
  26963. // Methods
  26964. ActionManager.prototype.dispose = function () {
  26965. var index = this._scene._actionManagers.indexOf(this);
  26966. if (index > -1) {
  26967. this._scene._actionManagers.splice(index, 1);
  26968. }
  26969. };
  26970. ActionManager.prototype.getScene = function () {
  26971. return this._scene;
  26972. };
  26973. /**
  26974. * Does this action manager handles actions of any of the given triggers
  26975. * @param {number[]} triggers - the triggers to be tested
  26976. * @return {boolean} whether one (or more) of the triggers is handeled
  26977. */
  26978. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26979. for (var index = 0; index < this.actions.length; index++) {
  26980. var action = this.actions[index];
  26981. if (triggers.indexOf(action.trigger) > -1) {
  26982. return true;
  26983. }
  26984. }
  26985. return false;
  26986. };
  26987. /**
  26988. * Does this action manager handles actions of a given trigger
  26989. * @param {number} trigger - the trigger to be tested
  26990. * @return {boolean} whether the trigger is handeled
  26991. */
  26992. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26993. for (var index = 0; index < this.actions.length; index++) {
  26994. var action = this.actions[index];
  26995. if (action.trigger === trigger) {
  26996. return true;
  26997. }
  26998. }
  26999. return false;
  27000. };
  27001. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27002. /**
  27003. * Does this action manager has pointer triggers
  27004. * @return {boolean} whether or not it has pointer triggers
  27005. */
  27006. get: function () {
  27007. for (var index = 0; index < this.actions.length; index++) {
  27008. var action = this.actions[index];
  27009. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27010. return true;
  27011. }
  27012. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27013. return true;
  27014. }
  27015. }
  27016. return false;
  27017. },
  27018. enumerable: true,
  27019. configurable: true
  27020. });
  27021. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27022. /**
  27023. * Does this action manager has pick triggers
  27024. * @return {boolean} whether or not it has pick triggers
  27025. */
  27026. get: function () {
  27027. for (var index = 0; index < this.actions.length; index++) {
  27028. var action = this.actions[index];
  27029. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27030. return true;
  27031. }
  27032. }
  27033. return false;
  27034. },
  27035. enumerable: true,
  27036. configurable: true
  27037. });
  27038. /**
  27039. * Registers an action to this action manager
  27040. * @param {BABYLON.Action} action - the action to be registered
  27041. * @return {BABYLON.Action} the action amended (prepared) after registration
  27042. */
  27043. ActionManager.prototype.registerAction = function (action) {
  27044. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27045. if (this.getScene().actionManager !== this) {
  27046. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27047. return null;
  27048. }
  27049. }
  27050. this.actions.push(action);
  27051. action._actionManager = this;
  27052. action._prepare();
  27053. return action;
  27054. };
  27055. /**
  27056. * Process a specific trigger
  27057. * @param {number} trigger - the trigger to process
  27058. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27059. */
  27060. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27061. for (var index = 0; index < this.actions.length; index++) {
  27062. var action = this.actions[index];
  27063. if (action.trigger === trigger) {
  27064. if (trigger === ActionManager.OnKeyUpTrigger
  27065. || trigger === ActionManager.OnKeyDownTrigger) {
  27066. var parameter = action.getTriggerParameter();
  27067. if (parameter) {
  27068. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27069. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27070. if (actualkey !== parameter.toLowerCase()) {
  27071. continue;
  27072. }
  27073. }
  27074. }
  27075. action._executeCurrent(evt);
  27076. }
  27077. }
  27078. };
  27079. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27080. var properties = propertyPath.split(".");
  27081. for (var index = 0; index < properties.length - 1; index++) {
  27082. target = target[properties[index]];
  27083. }
  27084. return target;
  27085. };
  27086. ActionManager.prototype._getProperty = function (propertyPath) {
  27087. var properties = propertyPath.split(".");
  27088. return properties[properties.length - 1];
  27089. };
  27090. // Statics
  27091. ActionManager._NothingTrigger = 0;
  27092. ActionManager._OnPickTrigger = 1;
  27093. ActionManager._OnLeftPickTrigger = 2;
  27094. ActionManager._OnRightPickTrigger = 3;
  27095. ActionManager._OnCenterPickTrigger = 4;
  27096. ActionManager._OnPointerOverTrigger = 5;
  27097. ActionManager._OnPointerOutTrigger = 6;
  27098. ActionManager._OnEveryFrameTrigger = 7;
  27099. ActionManager._OnIntersectionEnterTrigger = 8;
  27100. ActionManager._OnIntersectionExitTrigger = 9;
  27101. ActionManager._OnKeyDownTrigger = 10;
  27102. ActionManager._OnKeyUpTrigger = 11;
  27103. ActionManager._OnPickUpTrigger = 12;
  27104. return ActionManager;
  27105. })();
  27106. BABYLON.ActionManager = ActionManager;
  27107. })(BABYLON || (BABYLON = {}));
  27108. //# sourceMappingURL=babylon.actionManager.js.map
  27109. var __extends = this.__extends || function (d, b) {
  27110. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27111. function __() { this.constructor = d; }
  27112. __.prototype = b.prototype;
  27113. d.prototype = new __();
  27114. };
  27115. var BABYLON;
  27116. (function (BABYLON) {
  27117. var InterpolateValueAction = (function (_super) {
  27118. __extends(InterpolateValueAction, _super);
  27119. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27120. if (duration === void 0) { duration = 1000; }
  27121. _super.call(this, triggerOptions, condition);
  27122. this.propertyPath = propertyPath;
  27123. this.value = value;
  27124. this.duration = duration;
  27125. this.stopOtherAnimations = stopOtherAnimations;
  27126. this._target = target;
  27127. }
  27128. InterpolateValueAction.prototype._prepare = function () {
  27129. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27130. this._property = this._getProperty(this.propertyPath);
  27131. };
  27132. InterpolateValueAction.prototype.execute = function () {
  27133. var scene = this._actionManager.getScene();
  27134. var keys = [
  27135. {
  27136. frame: 0,
  27137. value: this._target[this._property]
  27138. }, {
  27139. frame: 100,
  27140. value: this.value
  27141. }
  27142. ];
  27143. var dataType;
  27144. if (typeof this.value === "number") {
  27145. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27146. }
  27147. else if (this.value instanceof BABYLON.Color3) {
  27148. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27149. }
  27150. else if (this.value instanceof BABYLON.Vector3) {
  27151. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27152. }
  27153. else if (this.value instanceof BABYLON.Matrix) {
  27154. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27155. }
  27156. else if (this.value instanceof BABYLON.Quaternion) {
  27157. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27158. }
  27159. else {
  27160. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27161. return;
  27162. }
  27163. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27164. animation.setKeys(keys);
  27165. if (this.stopOtherAnimations) {
  27166. scene.stopAnimation(this._target);
  27167. }
  27168. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27169. };
  27170. return InterpolateValueAction;
  27171. })(BABYLON.Action);
  27172. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27173. })(BABYLON || (BABYLON = {}));
  27174. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27175. var __extends = this.__extends || function (d, b) {
  27176. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27177. function __() { this.constructor = d; }
  27178. __.prototype = b.prototype;
  27179. d.prototype = new __();
  27180. };
  27181. var BABYLON;
  27182. (function (BABYLON) {
  27183. var SwitchBooleanAction = (function (_super) {
  27184. __extends(SwitchBooleanAction, _super);
  27185. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27186. _super.call(this, triggerOptions, condition);
  27187. this.propertyPath = propertyPath;
  27188. this._target = target;
  27189. }
  27190. SwitchBooleanAction.prototype._prepare = function () {
  27191. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27192. this._property = this._getProperty(this.propertyPath);
  27193. };
  27194. SwitchBooleanAction.prototype.execute = function () {
  27195. this._target[this._property] = !this._target[this._property];
  27196. };
  27197. return SwitchBooleanAction;
  27198. })(BABYLON.Action);
  27199. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27200. var SetStateAction = (function (_super) {
  27201. __extends(SetStateAction, _super);
  27202. function SetStateAction(triggerOptions, target, value, condition) {
  27203. _super.call(this, triggerOptions, condition);
  27204. this.value = value;
  27205. this._target = target;
  27206. }
  27207. SetStateAction.prototype.execute = function () {
  27208. this._target.state = this.value;
  27209. };
  27210. return SetStateAction;
  27211. })(BABYLON.Action);
  27212. BABYLON.SetStateAction = SetStateAction;
  27213. var SetValueAction = (function (_super) {
  27214. __extends(SetValueAction, _super);
  27215. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27216. _super.call(this, triggerOptions, condition);
  27217. this.propertyPath = propertyPath;
  27218. this.value = value;
  27219. this._target = target;
  27220. }
  27221. SetValueAction.prototype._prepare = function () {
  27222. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27223. this._property = this._getProperty(this.propertyPath);
  27224. };
  27225. SetValueAction.prototype.execute = function () {
  27226. this._target[this._property] = this.value;
  27227. };
  27228. return SetValueAction;
  27229. })(BABYLON.Action);
  27230. BABYLON.SetValueAction = SetValueAction;
  27231. var IncrementValueAction = (function (_super) {
  27232. __extends(IncrementValueAction, _super);
  27233. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27234. _super.call(this, triggerOptions, condition);
  27235. this.propertyPath = propertyPath;
  27236. this.value = value;
  27237. this._target = target;
  27238. }
  27239. IncrementValueAction.prototype._prepare = function () {
  27240. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27241. this._property = this._getProperty(this.propertyPath);
  27242. if (typeof this._target[this._property] !== "number") {
  27243. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27244. }
  27245. };
  27246. IncrementValueAction.prototype.execute = function () {
  27247. this._target[this._property] += this.value;
  27248. };
  27249. return IncrementValueAction;
  27250. })(BABYLON.Action);
  27251. BABYLON.IncrementValueAction = IncrementValueAction;
  27252. var PlayAnimationAction = (function (_super) {
  27253. __extends(PlayAnimationAction, _super);
  27254. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27255. _super.call(this, triggerOptions, condition);
  27256. this.from = from;
  27257. this.to = to;
  27258. this.loop = loop;
  27259. this._target = target;
  27260. }
  27261. PlayAnimationAction.prototype._prepare = function () {
  27262. };
  27263. PlayAnimationAction.prototype.execute = function () {
  27264. var scene = this._actionManager.getScene();
  27265. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27266. };
  27267. return PlayAnimationAction;
  27268. })(BABYLON.Action);
  27269. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27270. var StopAnimationAction = (function (_super) {
  27271. __extends(StopAnimationAction, _super);
  27272. function StopAnimationAction(triggerOptions, target, condition) {
  27273. _super.call(this, triggerOptions, condition);
  27274. this._target = target;
  27275. }
  27276. StopAnimationAction.prototype._prepare = function () {
  27277. };
  27278. StopAnimationAction.prototype.execute = function () {
  27279. var scene = this._actionManager.getScene();
  27280. scene.stopAnimation(this._target);
  27281. };
  27282. return StopAnimationAction;
  27283. })(BABYLON.Action);
  27284. BABYLON.StopAnimationAction = StopAnimationAction;
  27285. var DoNothingAction = (function (_super) {
  27286. __extends(DoNothingAction, _super);
  27287. function DoNothingAction(triggerOptions, condition) {
  27288. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27289. _super.call(this, triggerOptions, condition);
  27290. }
  27291. DoNothingAction.prototype.execute = function () {
  27292. };
  27293. return DoNothingAction;
  27294. })(BABYLON.Action);
  27295. BABYLON.DoNothingAction = DoNothingAction;
  27296. var CombineAction = (function (_super) {
  27297. __extends(CombineAction, _super);
  27298. function CombineAction(triggerOptions, children, condition) {
  27299. _super.call(this, triggerOptions, condition);
  27300. this.children = children;
  27301. }
  27302. CombineAction.prototype._prepare = function () {
  27303. for (var index = 0; index < this.children.length; index++) {
  27304. this.children[index]._actionManager = this._actionManager;
  27305. this.children[index]._prepare();
  27306. }
  27307. };
  27308. CombineAction.prototype.execute = function (evt) {
  27309. for (var index = 0; index < this.children.length; index++) {
  27310. this.children[index].execute(evt);
  27311. }
  27312. };
  27313. return CombineAction;
  27314. })(BABYLON.Action);
  27315. BABYLON.CombineAction = CombineAction;
  27316. var ExecuteCodeAction = (function (_super) {
  27317. __extends(ExecuteCodeAction, _super);
  27318. function ExecuteCodeAction(triggerOptions, func, condition) {
  27319. _super.call(this, triggerOptions, condition);
  27320. this.func = func;
  27321. }
  27322. ExecuteCodeAction.prototype.execute = function (evt) {
  27323. this.func(evt);
  27324. };
  27325. return ExecuteCodeAction;
  27326. })(BABYLON.Action);
  27327. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27328. var SetParentAction = (function (_super) {
  27329. __extends(SetParentAction, _super);
  27330. function SetParentAction(triggerOptions, target, parent, condition) {
  27331. _super.call(this, triggerOptions, condition);
  27332. this._target = target;
  27333. this._parent = parent;
  27334. }
  27335. SetParentAction.prototype._prepare = function () {
  27336. };
  27337. SetParentAction.prototype.execute = function () {
  27338. if (this._target.parent === this._parent) {
  27339. return;
  27340. }
  27341. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27342. invertParentWorldMatrix.invert();
  27343. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27344. this._target.parent = this._parent;
  27345. };
  27346. return SetParentAction;
  27347. })(BABYLON.Action);
  27348. BABYLON.SetParentAction = SetParentAction;
  27349. var PlaySoundAction = (function (_super) {
  27350. __extends(PlaySoundAction, _super);
  27351. function PlaySoundAction(triggerOptions, sound, condition) {
  27352. _super.call(this, triggerOptions, condition);
  27353. this._sound = sound;
  27354. }
  27355. PlaySoundAction.prototype._prepare = function () {
  27356. };
  27357. PlaySoundAction.prototype.execute = function () {
  27358. if (this._sound !== undefined)
  27359. this._sound.play();
  27360. };
  27361. return PlaySoundAction;
  27362. })(BABYLON.Action);
  27363. BABYLON.PlaySoundAction = PlaySoundAction;
  27364. var StopSoundAction = (function (_super) {
  27365. __extends(StopSoundAction, _super);
  27366. function StopSoundAction(triggerOptions, sound, condition) {
  27367. _super.call(this, triggerOptions, condition);
  27368. this._sound = sound;
  27369. }
  27370. StopSoundAction.prototype._prepare = function () {
  27371. };
  27372. StopSoundAction.prototype.execute = function () {
  27373. if (this._sound !== undefined)
  27374. this._sound.stop();
  27375. };
  27376. return StopSoundAction;
  27377. })(BABYLON.Action);
  27378. BABYLON.StopSoundAction = StopSoundAction;
  27379. })(BABYLON || (BABYLON = {}));
  27380. //# sourceMappingURL=babylon.directActions.js.map
  27381. var __extends = this.__extends || function (d, b) {
  27382. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27383. function __() { this.constructor = d; }
  27384. __.prototype = b.prototype;
  27385. d.prototype = new __();
  27386. };
  27387. var BABYLON;
  27388. (function (BABYLON) {
  27389. var Geometry = (function () {
  27390. function Geometry(id, scene, vertexData, updatable, mesh) {
  27391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27392. this._totalVertices = 0;
  27393. this._indices = [];
  27394. this._isDisposed = false;
  27395. this.id = id;
  27396. this._engine = scene.getEngine();
  27397. this._meshes = [];
  27398. this._scene = scene;
  27399. // vertexData
  27400. if (vertexData) {
  27401. this.setAllVerticesData(vertexData, updatable);
  27402. }
  27403. else {
  27404. this._totalVertices = 0;
  27405. this._indices = [];
  27406. }
  27407. // applyToMesh
  27408. if (mesh) {
  27409. this.applyToMesh(mesh);
  27410. mesh.computeWorldMatrix(true);
  27411. }
  27412. }
  27413. Geometry.prototype.getScene = function () {
  27414. return this._scene;
  27415. };
  27416. Geometry.prototype.getEngine = function () {
  27417. return this._engine;
  27418. };
  27419. Geometry.prototype.isReady = function () {
  27420. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27421. };
  27422. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27423. vertexData.applyToGeometry(this, updatable);
  27424. this.notifyUpdate();
  27425. };
  27426. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27427. this._vertexBuffers = this._vertexBuffers || {};
  27428. if (this._vertexBuffers[kind]) {
  27429. this._vertexBuffers[kind].dispose();
  27430. }
  27431. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27432. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27433. stride = this._vertexBuffers[kind].getStrideSize();
  27434. this._totalVertices = data.length / stride;
  27435. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27436. var meshes = this._meshes;
  27437. var numOfMeshes = meshes.length;
  27438. for (var index = 0; index < numOfMeshes; index++) {
  27439. var mesh = meshes[index];
  27440. mesh._resetPointsArrayCache();
  27441. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27442. mesh._createGlobalSubMesh();
  27443. mesh.computeWorldMatrix(true);
  27444. }
  27445. }
  27446. this.notifyUpdate(kind);
  27447. };
  27448. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27449. var vertexBuffer = this.getVertexBuffer(kind);
  27450. if (!vertexBuffer) {
  27451. return;
  27452. }
  27453. vertexBuffer.updateDirectly(data, offset);
  27454. this.notifyUpdate(kind);
  27455. };
  27456. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27457. var vertexBuffer = this.getVertexBuffer(kind);
  27458. if (!vertexBuffer) {
  27459. return;
  27460. }
  27461. vertexBuffer.update(data);
  27462. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27463. var extend;
  27464. var stride = vertexBuffer.getStrideSize();
  27465. this._totalVertices = data.length / stride;
  27466. if (updateExtends) {
  27467. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27468. }
  27469. var meshes = this._meshes;
  27470. var numOfMeshes = meshes.length;
  27471. for (var index = 0; index < numOfMeshes; index++) {
  27472. var mesh = meshes[index];
  27473. mesh._resetPointsArrayCache();
  27474. if (updateExtends) {
  27475. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27476. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27477. var subMesh = mesh.subMeshes[subIndex];
  27478. subMesh.refreshBoundingInfo();
  27479. }
  27480. }
  27481. }
  27482. }
  27483. this.notifyUpdate(kind);
  27484. };
  27485. Geometry.prototype.getTotalVertices = function () {
  27486. if (!this.isReady()) {
  27487. return 0;
  27488. }
  27489. return this._totalVertices;
  27490. };
  27491. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27492. var vertexBuffer = this.getVertexBuffer(kind);
  27493. if (!vertexBuffer) {
  27494. return null;
  27495. }
  27496. var orig = vertexBuffer.getData();
  27497. if (!copyWhenShared || this._meshes.length === 1) {
  27498. return orig;
  27499. }
  27500. else {
  27501. var len = orig.length;
  27502. var copy = [];
  27503. for (var i = 0; i < len; i++) {
  27504. copy.push(orig[i]);
  27505. }
  27506. return copy;
  27507. }
  27508. };
  27509. Geometry.prototype.getVertexBuffer = function (kind) {
  27510. if (!this.isReady()) {
  27511. return null;
  27512. }
  27513. return this._vertexBuffers[kind];
  27514. };
  27515. Geometry.prototype.getVertexBuffers = function () {
  27516. if (!this.isReady()) {
  27517. return null;
  27518. }
  27519. return this._vertexBuffers;
  27520. };
  27521. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27522. if (!this._vertexBuffers) {
  27523. if (this._delayInfo) {
  27524. return this._delayInfo.indexOf(kind) !== -1;
  27525. }
  27526. return false;
  27527. }
  27528. return this._vertexBuffers[kind] !== undefined;
  27529. };
  27530. Geometry.prototype.getVerticesDataKinds = function () {
  27531. var result = [];
  27532. if (!this._vertexBuffers && this._delayInfo) {
  27533. for (var kind in this._delayInfo) {
  27534. result.push(kind);
  27535. }
  27536. }
  27537. else {
  27538. for (kind in this._vertexBuffers) {
  27539. result.push(kind);
  27540. }
  27541. }
  27542. return result;
  27543. };
  27544. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27545. if (this._indexBuffer) {
  27546. this._engine._releaseBuffer(this._indexBuffer);
  27547. }
  27548. this._indices = indices;
  27549. if (this._meshes.length !== 0 && this._indices) {
  27550. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27551. }
  27552. if (totalVertices !== undefined) {
  27553. this._totalVertices = totalVertices;
  27554. }
  27555. var meshes = this._meshes;
  27556. var numOfMeshes = meshes.length;
  27557. for (var index = 0; index < numOfMeshes; index++) {
  27558. meshes[index]._createGlobalSubMesh();
  27559. }
  27560. this.notifyUpdate();
  27561. };
  27562. Geometry.prototype.getTotalIndices = function () {
  27563. if (!this.isReady()) {
  27564. return 0;
  27565. }
  27566. return this._indices.length;
  27567. };
  27568. Geometry.prototype.getIndices = function (copyWhenShared) {
  27569. if (!this.isReady()) {
  27570. return null;
  27571. }
  27572. var orig = this._indices;
  27573. if (!copyWhenShared || this._meshes.length === 1) {
  27574. return orig;
  27575. }
  27576. else {
  27577. var len = orig.length;
  27578. var copy = [];
  27579. for (var i = 0; i < len; i++) {
  27580. copy.push(orig[i]);
  27581. }
  27582. return copy;
  27583. }
  27584. };
  27585. Geometry.prototype.getIndexBuffer = function () {
  27586. if (!this.isReady()) {
  27587. return null;
  27588. }
  27589. return this._indexBuffer;
  27590. };
  27591. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27592. var meshes = this._meshes;
  27593. var index = meshes.indexOf(mesh);
  27594. if (index === -1) {
  27595. return;
  27596. }
  27597. for (var kind in this._vertexBuffers) {
  27598. this._vertexBuffers[kind].dispose();
  27599. }
  27600. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27601. this._indexBuffer = null;
  27602. }
  27603. meshes.splice(index, 1);
  27604. mesh._geometry = null;
  27605. if (meshes.length === 0 && shouldDispose) {
  27606. this.dispose();
  27607. }
  27608. };
  27609. Geometry.prototype.applyToMesh = function (mesh) {
  27610. if (mesh._geometry === this) {
  27611. return;
  27612. }
  27613. var previousGeometry = mesh._geometry;
  27614. if (previousGeometry) {
  27615. previousGeometry.releaseForMesh(mesh);
  27616. }
  27617. var meshes = this._meshes;
  27618. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27619. mesh._geometry = this;
  27620. this._scene.pushGeometry(this);
  27621. meshes.push(mesh);
  27622. if (this.isReady()) {
  27623. this._applyToMesh(mesh);
  27624. }
  27625. else {
  27626. mesh._boundingInfo = this._boundingInfo;
  27627. }
  27628. };
  27629. Geometry.prototype._applyToMesh = function (mesh) {
  27630. var numOfMeshes = this._meshes.length;
  27631. // vertexBuffers
  27632. for (var kind in this._vertexBuffers) {
  27633. if (numOfMeshes === 1) {
  27634. this._vertexBuffers[kind].create();
  27635. }
  27636. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27637. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27638. mesh._resetPointsArrayCache();
  27639. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27640. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27641. mesh._createGlobalSubMesh();
  27642. //bounding info was just created again, world matrix should be applied again.
  27643. mesh._updateBoundingInfo();
  27644. }
  27645. }
  27646. // indexBuffer
  27647. if (numOfMeshes === 1 && this._indices) {
  27648. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27649. }
  27650. if (this._indexBuffer) {
  27651. this._indexBuffer.references = numOfMeshes;
  27652. }
  27653. };
  27654. Geometry.prototype.notifyUpdate = function (kind) {
  27655. if (this.onGeometryUpdated) {
  27656. this.onGeometryUpdated(this, kind);
  27657. }
  27658. };
  27659. Geometry.prototype.load = function (scene, onLoaded) {
  27660. var _this = this;
  27661. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27662. return;
  27663. }
  27664. if (this.isReady()) {
  27665. if (onLoaded) {
  27666. onLoaded();
  27667. }
  27668. return;
  27669. }
  27670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27671. scene._addPendingData(this);
  27672. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27673. _this._delayLoadingFunction(JSON.parse(data), _this);
  27674. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27675. _this._delayInfo = [];
  27676. scene._removePendingData(_this);
  27677. var meshes = _this._meshes;
  27678. var numOfMeshes = meshes.length;
  27679. for (var index = 0; index < numOfMeshes; index++) {
  27680. _this._applyToMesh(meshes[index]);
  27681. }
  27682. if (onLoaded) {
  27683. onLoaded();
  27684. }
  27685. }, function () { }, scene.database);
  27686. };
  27687. Geometry.prototype.isDisposed = function () {
  27688. return this._isDisposed;
  27689. };
  27690. Geometry.prototype.dispose = function () {
  27691. var meshes = this._meshes;
  27692. var numOfMeshes = meshes.length;
  27693. var index;
  27694. for (index = 0; index < numOfMeshes; index++) {
  27695. this.releaseForMesh(meshes[index]);
  27696. }
  27697. this._meshes = [];
  27698. for (var kind in this._vertexBuffers) {
  27699. this._vertexBuffers[kind].dispose();
  27700. }
  27701. this._vertexBuffers = [];
  27702. this._totalVertices = 0;
  27703. if (this._indexBuffer) {
  27704. this._engine._releaseBuffer(this._indexBuffer);
  27705. }
  27706. this._indexBuffer = null;
  27707. this._indices = [];
  27708. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27709. this.delayLoadingFile = null;
  27710. this._delayLoadingFunction = null;
  27711. this._delayInfo = [];
  27712. this._boundingInfo = null; // todo: .dispose()
  27713. this._scene.removeGeometry(this);
  27714. this._isDisposed = true;
  27715. };
  27716. Geometry.prototype.copy = function (id) {
  27717. var vertexData = new BABYLON.VertexData();
  27718. vertexData.indices = [];
  27719. var indices = this.getIndices();
  27720. for (var index = 0; index < indices.length; index++) {
  27721. vertexData.indices.push(indices[index]);
  27722. }
  27723. var updatable = false;
  27724. var stopChecking = false;
  27725. for (var kind in this._vertexBuffers) {
  27726. // using slice() to make a copy of the array and not just reference it
  27727. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27728. if (!stopChecking) {
  27729. updatable = this.getVertexBuffer(kind).isUpdatable();
  27730. stopChecking = !updatable;
  27731. }
  27732. }
  27733. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27734. geometry.delayLoadState = this.delayLoadState;
  27735. geometry.delayLoadingFile = this.delayLoadingFile;
  27736. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27737. for (kind in this._delayInfo) {
  27738. geometry._delayInfo = geometry._delayInfo || [];
  27739. geometry._delayInfo.push(kind);
  27740. }
  27741. // Bounding info
  27742. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27743. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27744. return geometry;
  27745. };
  27746. // Statics
  27747. Geometry.ExtractFromMesh = function (mesh, id) {
  27748. var geometry = mesh._geometry;
  27749. if (!geometry) {
  27750. return null;
  27751. }
  27752. return geometry.copy(id);
  27753. };
  27754. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27755. // be aware Math.random() could cause collisions
  27756. Geometry.RandomId = function () {
  27757. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27758. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27759. return v.toString(16);
  27760. });
  27761. };
  27762. return Geometry;
  27763. })();
  27764. BABYLON.Geometry = Geometry;
  27765. /////// Primitives //////////////////////////////////////////////
  27766. var Geometry;
  27767. (function (Geometry) {
  27768. var Primitives;
  27769. (function (Primitives) {
  27770. /// Abstract class
  27771. var _Primitive = (function (_super) {
  27772. __extends(_Primitive, _super);
  27773. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27774. this._beingRegenerated = true;
  27775. this._canBeRegenerated = canBeRegenerated;
  27776. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27777. this._beingRegenerated = false;
  27778. }
  27779. _Primitive.prototype.canBeRegenerated = function () {
  27780. return this._canBeRegenerated;
  27781. };
  27782. _Primitive.prototype.regenerate = function () {
  27783. if (!this._canBeRegenerated) {
  27784. return;
  27785. }
  27786. this._beingRegenerated = true;
  27787. this.setAllVerticesData(this._regenerateVertexData(), false);
  27788. this._beingRegenerated = false;
  27789. };
  27790. _Primitive.prototype.asNewGeometry = function (id) {
  27791. return _super.prototype.copy.call(this, id);
  27792. };
  27793. // overrides
  27794. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27795. if (!this._beingRegenerated) {
  27796. return;
  27797. }
  27798. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27799. };
  27800. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27801. if (!this._beingRegenerated) {
  27802. return;
  27803. }
  27804. _super.prototype.setVerticesData.call(this, kind, data, false);
  27805. };
  27806. // to override
  27807. // protected
  27808. _Primitive.prototype._regenerateVertexData = function () {
  27809. throw new Error("Abstract method");
  27810. };
  27811. _Primitive.prototype.copy = function (id) {
  27812. throw new Error("Must be overriden in sub-classes.");
  27813. };
  27814. return _Primitive;
  27815. })(Geometry);
  27816. Primitives._Primitive = _Primitive;
  27817. var Ribbon = (function (_super) {
  27818. __extends(Ribbon, _super);
  27819. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27821. this.pathArray = pathArray;
  27822. this.closeArray = closeArray;
  27823. this.closePath = closePath;
  27824. this.offset = offset;
  27825. this.side = side;
  27826. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27827. }
  27828. Ribbon.prototype._regenerateVertexData = function () {
  27829. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27830. };
  27831. Ribbon.prototype.copy = function (id) {
  27832. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27833. };
  27834. return Ribbon;
  27835. })(_Primitive);
  27836. Primitives.Ribbon = Ribbon;
  27837. var Box = (function (_super) {
  27838. __extends(Box, _super);
  27839. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27840. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27841. this.size = size;
  27842. this.side = side;
  27843. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27844. }
  27845. Box.prototype._regenerateVertexData = function () {
  27846. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27847. };
  27848. Box.prototype.copy = function (id) {
  27849. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27850. };
  27851. return Box;
  27852. })(_Primitive);
  27853. Primitives.Box = Box;
  27854. var Sphere = (function (_super) {
  27855. __extends(Sphere, _super);
  27856. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27857. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27858. this.segments = segments;
  27859. this.diameter = diameter;
  27860. this.side = side;
  27861. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27862. }
  27863. Sphere.prototype._regenerateVertexData = function () {
  27864. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27865. };
  27866. Sphere.prototype.copy = function (id) {
  27867. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27868. };
  27869. return Sphere;
  27870. })(_Primitive);
  27871. Primitives.Sphere = Sphere;
  27872. var Cylinder = (function (_super) {
  27873. __extends(Cylinder, _super);
  27874. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27875. if (subdivisions === void 0) { subdivisions = 1; }
  27876. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27877. this.height = height;
  27878. this.diameterTop = diameterTop;
  27879. this.diameterBottom = diameterBottom;
  27880. this.tessellation = tessellation;
  27881. this.subdivisions = subdivisions;
  27882. this.side = side;
  27883. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27884. }
  27885. Cylinder.prototype._regenerateVertexData = function () {
  27886. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27887. };
  27888. Cylinder.prototype.copy = function (id) {
  27889. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27890. };
  27891. return Cylinder;
  27892. })(_Primitive);
  27893. Primitives.Cylinder = Cylinder;
  27894. var Torus = (function (_super) {
  27895. __extends(Torus, _super);
  27896. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27898. this.diameter = diameter;
  27899. this.thickness = thickness;
  27900. this.tessellation = tessellation;
  27901. this.side = side;
  27902. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27903. }
  27904. Torus.prototype._regenerateVertexData = function () {
  27905. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27906. };
  27907. Torus.prototype.copy = function (id) {
  27908. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27909. };
  27910. return Torus;
  27911. })(_Primitive);
  27912. Primitives.Torus = Torus;
  27913. var Ground = (function (_super) {
  27914. __extends(Ground, _super);
  27915. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27916. this.width = width;
  27917. this.height = height;
  27918. this.subdivisions = subdivisions;
  27919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27920. }
  27921. Ground.prototype._regenerateVertexData = function () {
  27922. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27923. };
  27924. Ground.prototype.copy = function (id) {
  27925. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27926. };
  27927. return Ground;
  27928. })(_Primitive);
  27929. Primitives.Ground = Ground;
  27930. var TiledGround = (function (_super) {
  27931. __extends(TiledGround, _super);
  27932. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27933. this.xmin = xmin;
  27934. this.zmin = zmin;
  27935. this.xmax = xmax;
  27936. this.zmax = zmax;
  27937. this.subdivisions = subdivisions;
  27938. this.precision = precision;
  27939. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27940. }
  27941. TiledGround.prototype._regenerateVertexData = function () {
  27942. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27943. };
  27944. TiledGround.prototype.copy = function (id) {
  27945. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27946. };
  27947. return TiledGround;
  27948. })(_Primitive);
  27949. Primitives.TiledGround = TiledGround;
  27950. var Plane = (function (_super) {
  27951. __extends(Plane, _super);
  27952. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27953. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27954. this.size = size;
  27955. this.side = side;
  27956. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27957. }
  27958. Plane.prototype._regenerateVertexData = function () {
  27959. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27960. };
  27961. Plane.prototype.copy = function (id) {
  27962. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27963. };
  27964. return Plane;
  27965. })(_Primitive);
  27966. Primitives.Plane = Plane;
  27967. var TorusKnot = (function (_super) {
  27968. __extends(TorusKnot, _super);
  27969. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27970. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27971. this.radius = radius;
  27972. this.tube = tube;
  27973. this.radialSegments = radialSegments;
  27974. this.tubularSegments = tubularSegments;
  27975. this.p = p;
  27976. this.q = q;
  27977. this.side = side;
  27978. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27979. }
  27980. TorusKnot.prototype._regenerateVertexData = function () {
  27981. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27982. };
  27983. TorusKnot.prototype.copy = function (id) {
  27984. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27985. };
  27986. return TorusKnot;
  27987. })(_Primitive);
  27988. Primitives.TorusKnot = TorusKnot;
  27989. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27990. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27991. })(BABYLON || (BABYLON = {}));
  27992. //# sourceMappingURL=babylon.geometry.js.map
  27993. var __extends = this.__extends || function (d, b) {
  27994. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27995. function __() { this.constructor = d; }
  27996. __.prototype = b.prototype;
  27997. d.prototype = new __();
  27998. };
  27999. var BABYLON;
  28000. (function (BABYLON) {
  28001. var GroundMesh = (function (_super) {
  28002. __extends(GroundMesh, _super);
  28003. function GroundMesh(name, scene) {
  28004. _super.call(this, name, scene);
  28005. this.generateOctree = false;
  28006. this._worldInverse = new BABYLON.Matrix();
  28007. }
  28008. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28009. get: function () {
  28010. return this._subdivisions;
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. GroundMesh.prototype.optimize = function (chunksCount) {
  28016. this.subdivide(this._subdivisions);
  28017. this.createOrUpdateSubmeshesOctree(32);
  28018. };
  28019. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28020. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28021. this.getWorldMatrix().invertToRef(this._worldInverse);
  28022. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28023. var pickInfo = this.intersects(ray);
  28024. if (pickInfo.hit) {
  28025. return pickInfo.pickedPoint.y;
  28026. }
  28027. return 0;
  28028. };
  28029. return GroundMesh;
  28030. })(BABYLON.Mesh);
  28031. BABYLON.GroundMesh = GroundMesh;
  28032. })(BABYLON || (BABYLON = {}));
  28033. //# sourceMappingURL=babylon.groundMesh.js.map
  28034. var __extends = this.__extends || function (d, b) {
  28035. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28036. function __() { this.constructor = d; }
  28037. __.prototype = b.prototype;
  28038. d.prototype = new __();
  28039. };
  28040. var BABYLON;
  28041. (function (BABYLON) {
  28042. var LinesMesh = (function (_super) {
  28043. __extends(LinesMesh, _super);
  28044. function LinesMesh(name, scene, updatable) {
  28045. if (updatable === void 0) { updatable = false; }
  28046. _super.call(this, name, scene);
  28047. this.color = new BABYLON.Color3(1, 1, 1);
  28048. this.alpha = 1;
  28049. this._indices = new Array();
  28050. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28051. attributes: ["position"],
  28052. uniforms: ["worldViewProjection", "color"],
  28053. needAlphaBlending: true
  28054. });
  28055. }
  28056. Object.defineProperty(LinesMesh.prototype, "material", {
  28057. get: function () {
  28058. return this._colorShader;
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28064. get: function () {
  28065. return false;
  28066. },
  28067. enumerable: true,
  28068. configurable: true
  28069. });
  28070. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28071. get: function () {
  28072. return false;
  28073. },
  28074. enumerable: true,
  28075. configurable: true
  28076. });
  28077. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28078. var engine = this.getScene().getEngine();
  28079. var indexToBind = this._geometry.getIndexBuffer();
  28080. // VBOs
  28081. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28082. // Color
  28083. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28084. };
  28085. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28086. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28087. return;
  28088. }
  28089. var engine = this.getScene().getEngine();
  28090. // Draw order
  28091. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28092. };
  28093. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28094. return null;
  28095. };
  28096. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28097. this._colorShader.dispose();
  28098. _super.prototype.dispose.call(this, doNotRecurse);
  28099. };
  28100. return LinesMesh;
  28101. })(BABYLON.Mesh);
  28102. BABYLON.LinesMesh = LinesMesh;
  28103. })(BABYLON || (BABYLON = {}));
  28104. //# sourceMappingURL=babylon.linesMesh.js.map
  28105. var BABYLON;
  28106. (function (BABYLON) {
  28107. var OutlineRenderer = (function () {
  28108. function OutlineRenderer(scene) {
  28109. this._scene = scene;
  28110. }
  28111. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28112. var _this = this;
  28113. if (useOverlay === void 0) { useOverlay = false; }
  28114. var scene = this._scene;
  28115. var engine = this._scene.getEngine();
  28116. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28117. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28118. return;
  28119. }
  28120. var mesh = subMesh.getRenderingMesh();
  28121. var material = subMesh.getMaterial();
  28122. engine.enableEffect(this._effect);
  28123. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28124. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28125. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28126. // Bones
  28127. if (mesh.useBones) {
  28128. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28129. }
  28130. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28131. // Alpha test
  28132. if (material && material.needAlphaTesting()) {
  28133. var alphaTexture = material.getAlphaTestTexture();
  28134. this._effect.setTexture("diffuseSampler", alphaTexture);
  28135. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28136. }
  28137. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28138. };
  28139. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28140. var defines = [];
  28141. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28142. var mesh = subMesh.getMesh();
  28143. var material = subMesh.getMaterial();
  28144. // Alpha test
  28145. if (material && material.needAlphaTesting()) {
  28146. defines.push("#define ALPHATEST");
  28147. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28148. attribs.push(BABYLON.VertexBuffer.UVKind);
  28149. defines.push("#define UV1");
  28150. }
  28151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28152. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28153. defines.push("#define UV2");
  28154. }
  28155. }
  28156. // Bones
  28157. if (mesh.useBones) {
  28158. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28159. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28160. defines.push("#define BONES");
  28161. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28162. }
  28163. // Instances
  28164. if (useInstances) {
  28165. defines.push("#define INSTANCES");
  28166. attribs.push("world0");
  28167. attribs.push("world1");
  28168. attribs.push("world2");
  28169. attribs.push("world3");
  28170. }
  28171. // Get correct effect
  28172. var join = defines.join("\n");
  28173. if (this._cachedDefines !== join) {
  28174. this._cachedDefines = join;
  28175. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28176. }
  28177. return this._effect.isReady();
  28178. };
  28179. return OutlineRenderer;
  28180. })();
  28181. BABYLON.OutlineRenderer = OutlineRenderer;
  28182. })(BABYLON || (BABYLON = {}));
  28183. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28184. var BABYLON;
  28185. (function (BABYLON) {
  28186. var MeshAssetTask = (function () {
  28187. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28188. this.name = name;
  28189. this.meshesNames = meshesNames;
  28190. this.rootUrl = rootUrl;
  28191. this.sceneFilename = sceneFilename;
  28192. this.isCompleted = false;
  28193. }
  28194. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28195. var _this = this;
  28196. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28197. _this.loadedMeshes = meshes;
  28198. _this.loadedParticleSystems = particleSystems;
  28199. _this.loadedSkeletons = skeletons;
  28200. _this.isCompleted = true;
  28201. if (_this.onSuccess) {
  28202. _this.onSuccess(_this);
  28203. }
  28204. onSuccess();
  28205. }, null, function () {
  28206. if (_this.onError) {
  28207. _this.onError(_this);
  28208. }
  28209. onError();
  28210. });
  28211. };
  28212. return MeshAssetTask;
  28213. })();
  28214. BABYLON.MeshAssetTask = MeshAssetTask;
  28215. var TextFileAssetTask = (function () {
  28216. function TextFileAssetTask(name, url) {
  28217. this.name = name;
  28218. this.url = url;
  28219. this.isCompleted = false;
  28220. }
  28221. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28222. var _this = this;
  28223. BABYLON.Tools.LoadFile(this.url, function (data) {
  28224. _this.text = data;
  28225. _this.isCompleted = true;
  28226. if (_this.onSuccess) {
  28227. _this.onSuccess(_this);
  28228. }
  28229. onSuccess();
  28230. }, null, scene.database, false, function () {
  28231. if (_this.onError) {
  28232. _this.onError(_this);
  28233. }
  28234. onError();
  28235. });
  28236. };
  28237. return TextFileAssetTask;
  28238. })();
  28239. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28240. var BinaryFileAssetTask = (function () {
  28241. function BinaryFileAssetTask(name, url) {
  28242. this.name = name;
  28243. this.url = url;
  28244. this.isCompleted = false;
  28245. }
  28246. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28247. var _this = this;
  28248. BABYLON.Tools.LoadFile(this.url, function (data) {
  28249. _this.data = data;
  28250. _this.isCompleted = true;
  28251. if (_this.onSuccess) {
  28252. _this.onSuccess(_this);
  28253. }
  28254. onSuccess();
  28255. }, null, scene.database, true, function () {
  28256. if (_this.onError) {
  28257. _this.onError(_this);
  28258. }
  28259. onError();
  28260. });
  28261. };
  28262. return BinaryFileAssetTask;
  28263. })();
  28264. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28265. var ImageAssetTask = (function () {
  28266. function ImageAssetTask(name, url) {
  28267. this.name = name;
  28268. this.url = url;
  28269. this.isCompleted = false;
  28270. }
  28271. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28272. var _this = this;
  28273. var img = new Image();
  28274. img.onload = function () {
  28275. _this.image = img;
  28276. _this.isCompleted = true;
  28277. if (_this.onSuccess) {
  28278. _this.onSuccess(_this);
  28279. }
  28280. onSuccess();
  28281. };
  28282. img.onerror = function () {
  28283. if (_this.onError) {
  28284. _this.onError(_this);
  28285. }
  28286. onError();
  28287. };
  28288. img.src = this.url;
  28289. };
  28290. return ImageAssetTask;
  28291. })();
  28292. BABYLON.ImageAssetTask = ImageAssetTask;
  28293. var TextureAssetTask = (function () {
  28294. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28296. this.name = name;
  28297. this.url = url;
  28298. this.noMipmap = noMipmap;
  28299. this.invertY = invertY;
  28300. this.samplingMode = samplingMode;
  28301. this.isCompleted = false;
  28302. }
  28303. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28304. var _this = this;
  28305. var onload = function () {
  28306. _this.isCompleted = true;
  28307. if (_this.onSuccess) {
  28308. _this.onSuccess(_this);
  28309. }
  28310. onSuccess();
  28311. };
  28312. var onerror = function () {
  28313. if (_this.onError) {
  28314. _this.onError(_this);
  28315. }
  28316. onError();
  28317. };
  28318. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28319. };
  28320. return TextureAssetTask;
  28321. })();
  28322. BABYLON.TextureAssetTask = TextureAssetTask;
  28323. var AssetsManager = (function () {
  28324. function AssetsManager(scene) {
  28325. this._tasks = new Array();
  28326. this._waitingTasksCount = 0;
  28327. this.useDefaultLoadingScreen = true;
  28328. this._scene = scene;
  28329. }
  28330. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28331. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28332. this._tasks.push(task);
  28333. return task;
  28334. };
  28335. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28336. var task = new TextFileAssetTask(taskName, url);
  28337. this._tasks.push(task);
  28338. return task;
  28339. };
  28340. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28341. var task = new BinaryFileAssetTask(taskName, url);
  28342. this._tasks.push(task);
  28343. return task;
  28344. };
  28345. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28346. var task = new ImageAssetTask(taskName, url);
  28347. this._tasks.push(task);
  28348. return task;
  28349. };
  28350. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28352. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28353. this._tasks.push(task);
  28354. return task;
  28355. };
  28356. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28357. this._waitingTasksCount--;
  28358. if (this._waitingTasksCount === 0) {
  28359. if (this.onFinish) {
  28360. this.onFinish(this._tasks);
  28361. }
  28362. this._scene.getEngine().hideLoadingUI();
  28363. }
  28364. };
  28365. AssetsManager.prototype._runTask = function (task) {
  28366. var _this = this;
  28367. task.run(this._scene, function () {
  28368. if (_this.onTaskSuccess) {
  28369. _this.onTaskSuccess(task);
  28370. }
  28371. _this._decreaseWaitingTasksCount();
  28372. }, function () {
  28373. if (_this.onTaskError) {
  28374. _this.onTaskError(task);
  28375. }
  28376. _this._decreaseWaitingTasksCount();
  28377. });
  28378. };
  28379. AssetsManager.prototype.reset = function () {
  28380. this._tasks = new Array();
  28381. return this;
  28382. };
  28383. AssetsManager.prototype.load = function () {
  28384. this._waitingTasksCount = this._tasks.length;
  28385. if (this._waitingTasksCount === 0) {
  28386. if (this.onFinish) {
  28387. this.onFinish(this._tasks);
  28388. }
  28389. return this;
  28390. }
  28391. if (this.useDefaultLoadingScreen) {
  28392. this._scene.getEngine().displayLoadingUI();
  28393. }
  28394. for (var index = 0; index < this._tasks.length; index++) {
  28395. var task = this._tasks[index];
  28396. this._runTask(task);
  28397. }
  28398. return this;
  28399. };
  28400. return AssetsManager;
  28401. })();
  28402. BABYLON.AssetsManager = AssetsManager;
  28403. })(BABYLON || (BABYLON = {}));
  28404. //# sourceMappingURL=babylon.assetsManager.js.map
  28405. var __extends = this.__extends || function (d, b) {
  28406. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28407. function __() { this.constructor = d; }
  28408. __.prototype = b.prototype;
  28409. d.prototype = new __();
  28410. };
  28411. var BABYLON;
  28412. (function (BABYLON) {
  28413. var VRDeviceOrientationFreeCamera = (function (_super) {
  28414. __extends(VRDeviceOrientationFreeCamera, _super);
  28415. function VRDeviceOrientationFreeCamera(name, position, scene) {
  28416. _super.call(this, name, position, scene);
  28417. this._alpha = 0;
  28418. this._beta = 0;
  28419. this._gamma = 0;
  28420. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28421. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28422. }
  28423. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28424. this._alpha = +evt.alpha | 0;
  28425. this._beta = +evt.beta | 0;
  28426. this._gamma = +evt.gamma | 0;
  28427. if (this._gamma < 0) {
  28428. this._gamma = 90 + this._gamma;
  28429. }
  28430. else {
  28431. // Incline it in the correct angle.
  28432. this._gamma = 270 - this._gamma;
  28433. }
  28434. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28435. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28436. this.rotation.z = this._beta / 180.0 * Math.PI;
  28437. };
  28438. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28439. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28440. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28441. };
  28442. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28443. _super.prototype.detachControl.call(this, element);
  28444. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28445. };
  28446. return VRDeviceOrientationFreeCamera;
  28447. })(BABYLON.FreeCamera);
  28448. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28449. })(BABYLON || (BABYLON = {}));
  28450. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28451. var __extends = this.__extends || function (d, b) {
  28452. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28453. function __() { this.constructor = d; }
  28454. __.prototype = b.prototype;
  28455. d.prototype = new __();
  28456. };
  28457. var BABYLON;
  28458. (function (BABYLON) {
  28459. var WebVRFreeCamera = (function (_super) {
  28460. __extends(WebVRFreeCamera, _super);
  28461. function WebVRFreeCamera(name, position, scene) {
  28462. _super.call(this, name, position, scene);
  28463. this._hmdDevice = null;
  28464. this._sensorDevice = null;
  28465. this._cacheState = null;
  28466. this._cacheQuaternion = new BABYLON.Quaternion();
  28467. this._cacheRotation = BABYLON.Vector3.Zero();
  28468. this._vrEnabled = false;
  28469. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28470. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28471. }
  28472. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28473. var size = devices.length;
  28474. var i = 0;
  28475. // Reset devices.
  28476. this._sensorDevice = null;
  28477. this._hmdDevice = null;
  28478. // Search for a HmdDevice.
  28479. while (i < size && this._hmdDevice === null) {
  28480. if (devices[i] instanceof HMDVRDevice) {
  28481. this._hmdDevice = devices[i];
  28482. }
  28483. i++;
  28484. }
  28485. i = 0;
  28486. while (i < size && this._sensorDevice === null) {
  28487. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28488. this._sensorDevice = devices[i];
  28489. }
  28490. i++;
  28491. }
  28492. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28493. };
  28494. WebVRFreeCamera.prototype._checkInputs = function () {
  28495. if (this._vrEnabled) {
  28496. this._cacheState = this._sensorDevice.getState();
  28497. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28498. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28499. this.rotation.x = -this._cacheRotation.z;
  28500. this.rotation.y = -this._cacheRotation.y;
  28501. this.rotation.z = this._cacheRotation.x;
  28502. }
  28503. _super.prototype._checkInputs.call(this);
  28504. };
  28505. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28506. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28507. if (navigator.getVRDevices) {
  28508. navigator.getVRDevices().then(this._getWebVRDevices);
  28509. }
  28510. else if (navigator.mozGetVRDevices) {
  28511. navigator.mozGetVRDevices(this._getWebVRDevices);
  28512. }
  28513. };
  28514. WebVRFreeCamera.prototype.detachControl = function (element) {
  28515. _super.prototype.detachControl.call(this, element);
  28516. this._vrEnabled = false;
  28517. };
  28518. return WebVRFreeCamera;
  28519. })(BABYLON.FreeCamera);
  28520. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28521. })(BABYLON || (BABYLON = {}));
  28522. //# sourceMappingURL=babylon.webVRCamera.js.map
  28523. var __extends = this.__extends || function (d, b) {
  28524. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28525. function __() { this.constructor = d; }
  28526. __.prototype = b.prototype;
  28527. d.prototype = new __();
  28528. };
  28529. var BABYLON;
  28530. (function (BABYLON) {
  28531. // Standard optimizations
  28532. var SceneOptimization = (function () {
  28533. function SceneOptimization(priority) {
  28534. if (priority === void 0) { priority = 0; }
  28535. this.priority = priority;
  28536. this.apply = function (scene) {
  28537. return true; // Return true if everything that can be done was applied
  28538. };
  28539. }
  28540. return SceneOptimization;
  28541. })();
  28542. BABYLON.SceneOptimization = SceneOptimization;
  28543. var TextureOptimization = (function (_super) {
  28544. __extends(TextureOptimization, _super);
  28545. function TextureOptimization(priority, maximumSize) {
  28546. var _this = this;
  28547. if (priority === void 0) { priority = 0; }
  28548. if (maximumSize === void 0) { maximumSize = 1024; }
  28549. _super.call(this, priority);
  28550. this.priority = priority;
  28551. this.maximumSize = maximumSize;
  28552. this.apply = function (scene) {
  28553. var allDone = true;
  28554. for (var index = 0; index < scene.textures.length; index++) {
  28555. var texture = scene.textures[index];
  28556. if (!texture.canRescale) {
  28557. continue;
  28558. }
  28559. var currentSize = texture.getSize();
  28560. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28561. if (maxDimension > _this.maximumSize) {
  28562. texture.scale(0.5);
  28563. allDone = false;
  28564. }
  28565. }
  28566. return allDone;
  28567. };
  28568. }
  28569. return TextureOptimization;
  28570. })(SceneOptimization);
  28571. BABYLON.TextureOptimization = TextureOptimization;
  28572. var HardwareScalingOptimization = (function (_super) {
  28573. __extends(HardwareScalingOptimization, _super);
  28574. function HardwareScalingOptimization(priority, maximumScale) {
  28575. var _this = this;
  28576. if (priority === void 0) { priority = 0; }
  28577. if (maximumScale === void 0) { maximumScale = 2; }
  28578. _super.call(this, priority);
  28579. this.priority = priority;
  28580. this.maximumScale = maximumScale;
  28581. this._currentScale = 1;
  28582. this.apply = function (scene) {
  28583. _this._currentScale++;
  28584. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28585. return _this._currentScale >= _this.maximumScale;
  28586. };
  28587. }
  28588. return HardwareScalingOptimization;
  28589. })(SceneOptimization);
  28590. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28591. var ShadowsOptimization = (function (_super) {
  28592. __extends(ShadowsOptimization, _super);
  28593. function ShadowsOptimization() {
  28594. _super.apply(this, arguments);
  28595. this.apply = function (scene) {
  28596. scene.shadowsEnabled = false;
  28597. return true;
  28598. };
  28599. }
  28600. return ShadowsOptimization;
  28601. })(SceneOptimization);
  28602. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28603. var PostProcessesOptimization = (function (_super) {
  28604. __extends(PostProcessesOptimization, _super);
  28605. function PostProcessesOptimization() {
  28606. _super.apply(this, arguments);
  28607. this.apply = function (scene) {
  28608. scene.postProcessesEnabled = false;
  28609. return true;
  28610. };
  28611. }
  28612. return PostProcessesOptimization;
  28613. })(SceneOptimization);
  28614. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28615. var LensFlaresOptimization = (function (_super) {
  28616. __extends(LensFlaresOptimization, _super);
  28617. function LensFlaresOptimization() {
  28618. _super.apply(this, arguments);
  28619. this.apply = function (scene) {
  28620. scene.lensFlaresEnabled = false;
  28621. return true;
  28622. };
  28623. }
  28624. return LensFlaresOptimization;
  28625. })(SceneOptimization);
  28626. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28627. var ParticlesOptimization = (function (_super) {
  28628. __extends(ParticlesOptimization, _super);
  28629. function ParticlesOptimization() {
  28630. _super.apply(this, arguments);
  28631. this.apply = function (scene) {
  28632. scene.particlesEnabled = false;
  28633. return true;
  28634. };
  28635. }
  28636. return ParticlesOptimization;
  28637. })(SceneOptimization);
  28638. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28639. var RenderTargetsOptimization = (function (_super) {
  28640. __extends(RenderTargetsOptimization, _super);
  28641. function RenderTargetsOptimization() {
  28642. _super.apply(this, arguments);
  28643. this.apply = function (scene) {
  28644. scene.renderTargetsEnabled = false;
  28645. return true;
  28646. };
  28647. }
  28648. return RenderTargetsOptimization;
  28649. })(SceneOptimization);
  28650. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28651. var MergeMeshesOptimization = (function (_super) {
  28652. __extends(MergeMeshesOptimization, _super);
  28653. function MergeMeshesOptimization() {
  28654. var _this = this;
  28655. _super.apply(this, arguments);
  28656. this._canBeMerged = function (abstractMesh) {
  28657. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28658. return false;
  28659. }
  28660. var mesh = abstractMesh;
  28661. if (!mesh.isVisible || !mesh.isEnabled()) {
  28662. return false;
  28663. }
  28664. if (mesh.instances.length > 0) {
  28665. return false;
  28666. }
  28667. if (mesh.skeleton || mesh.hasLODLevels) {
  28668. return false;
  28669. }
  28670. return true;
  28671. };
  28672. this.apply = function (scene) {
  28673. var globalPool = scene.meshes.slice(0);
  28674. var globalLength = globalPool.length;
  28675. for (var index = 0; index < globalLength; index++) {
  28676. var currentPool = new Array();
  28677. var current = globalPool[index];
  28678. // Checks
  28679. if (!_this._canBeMerged(current)) {
  28680. continue;
  28681. }
  28682. currentPool.push(current);
  28683. // Find compatible meshes
  28684. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28685. var otherMesh = globalPool[subIndex];
  28686. if (!_this._canBeMerged(otherMesh)) {
  28687. continue;
  28688. }
  28689. if (otherMesh.material !== current.material) {
  28690. continue;
  28691. }
  28692. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28693. continue;
  28694. }
  28695. currentPool.push(otherMesh);
  28696. globalLength--;
  28697. globalPool.splice(subIndex, 1);
  28698. subIndex--;
  28699. }
  28700. if (currentPool.length < 2) {
  28701. continue;
  28702. }
  28703. // Merge meshes
  28704. BABYLON.Mesh.MergeMeshes(currentPool);
  28705. }
  28706. return true;
  28707. };
  28708. }
  28709. return MergeMeshesOptimization;
  28710. })(SceneOptimization);
  28711. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28712. // Options
  28713. var SceneOptimizerOptions = (function () {
  28714. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28715. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28716. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28717. this.targetFrameRate = targetFrameRate;
  28718. this.trackerDuration = trackerDuration;
  28719. this.optimizations = new Array();
  28720. }
  28721. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28722. var result = new SceneOptimizerOptions(targetFrameRate);
  28723. var priority = 0;
  28724. result.optimizations.push(new MergeMeshesOptimization(priority));
  28725. result.optimizations.push(new ShadowsOptimization(priority));
  28726. result.optimizations.push(new LensFlaresOptimization(priority));
  28727. // Next priority
  28728. priority++;
  28729. result.optimizations.push(new PostProcessesOptimization(priority));
  28730. result.optimizations.push(new ParticlesOptimization(priority));
  28731. // Next priority
  28732. priority++;
  28733. result.optimizations.push(new TextureOptimization(priority, 1024));
  28734. return result;
  28735. };
  28736. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28737. var result = new SceneOptimizerOptions(targetFrameRate);
  28738. var priority = 0;
  28739. result.optimizations.push(new MergeMeshesOptimization(priority));
  28740. result.optimizations.push(new ShadowsOptimization(priority));
  28741. result.optimizations.push(new LensFlaresOptimization(priority));
  28742. // Next priority
  28743. priority++;
  28744. result.optimizations.push(new PostProcessesOptimization(priority));
  28745. result.optimizations.push(new ParticlesOptimization(priority));
  28746. // Next priority
  28747. priority++;
  28748. result.optimizations.push(new TextureOptimization(priority, 512));
  28749. // Next priority
  28750. priority++;
  28751. result.optimizations.push(new RenderTargetsOptimization(priority));
  28752. // Next priority
  28753. priority++;
  28754. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28755. return result;
  28756. };
  28757. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28758. var result = new SceneOptimizerOptions(targetFrameRate);
  28759. var priority = 0;
  28760. result.optimizations.push(new MergeMeshesOptimization(priority));
  28761. result.optimizations.push(new ShadowsOptimization(priority));
  28762. result.optimizations.push(new LensFlaresOptimization(priority));
  28763. // Next priority
  28764. priority++;
  28765. result.optimizations.push(new PostProcessesOptimization(priority));
  28766. result.optimizations.push(new ParticlesOptimization(priority));
  28767. // Next priority
  28768. priority++;
  28769. result.optimizations.push(new TextureOptimization(priority, 256));
  28770. // Next priority
  28771. priority++;
  28772. result.optimizations.push(new RenderTargetsOptimization(priority));
  28773. // Next priority
  28774. priority++;
  28775. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28776. return result;
  28777. };
  28778. return SceneOptimizerOptions;
  28779. })();
  28780. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28781. // Scene optimizer tool
  28782. var SceneOptimizer = (function () {
  28783. function SceneOptimizer() {
  28784. }
  28785. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28786. // TODO: add an epsilon
  28787. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28788. if (onSuccess) {
  28789. onSuccess();
  28790. }
  28791. return;
  28792. }
  28793. // Apply current level of optimizations
  28794. var allDone = true;
  28795. var noOptimizationApplied = true;
  28796. for (var index = 0; index < options.optimizations.length; index++) {
  28797. var optimization = options.optimizations[index];
  28798. if (optimization.priority === currentPriorityLevel) {
  28799. noOptimizationApplied = false;
  28800. allDone = allDone && optimization.apply(scene);
  28801. }
  28802. }
  28803. // If no optimization was applied, this is a failure :(
  28804. if (noOptimizationApplied) {
  28805. if (onFailure) {
  28806. onFailure();
  28807. }
  28808. return;
  28809. }
  28810. // If all optimizations were done, move to next level
  28811. if (allDone) {
  28812. currentPriorityLevel++;
  28813. }
  28814. // Let's the system running for a specific amount of time before checking FPS
  28815. scene.executeWhenReady(function () {
  28816. setTimeout(function () {
  28817. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28818. }, options.trackerDuration);
  28819. });
  28820. };
  28821. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28822. if (!options) {
  28823. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28824. }
  28825. // Let's the system running for a specific amount of time before checking FPS
  28826. scene.executeWhenReady(function () {
  28827. setTimeout(function () {
  28828. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28829. }, options.trackerDuration);
  28830. });
  28831. };
  28832. return SceneOptimizer;
  28833. })();
  28834. BABYLON.SceneOptimizer = SceneOptimizer;
  28835. })(BABYLON || (BABYLON = {}));
  28836. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28837. var BABYLON;
  28838. (function (BABYLON) {
  28839. var Internals;
  28840. (function (Internals) {
  28841. var MeshLODLevel = (function () {
  28842. function MeshLODLevel(distance, mesh) {
  28843. this.distance = distance;
  28844. this.mesh = mesh;
  28845. }
  28846. return MeshLODLevel;
  28847. })();
  28848. Internals.MeshLODLevel = MeshLODLevel;
  28849. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28850. })(BABYLON || (BABYLON = {}));
  28851. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28852. var BABYLON;
  28853. (function (BABYLON) {
  28854. var AudioEngine = (function () {
  28855. function AudioEngine() {
  28856. this._audioContext = null;
  28857. this._audioContextInitialized = false;
  28858. this.canUseWebAudio = false;
  28859. this.WarnedWebAudioUnsupported = false;
  28860. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28861. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28862. this.canUseWebAudio = true;
  28863. }
  28864. }
  28865. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28866. get: function () {
  28867. if (!this._audioContextInitialized) {
  28868. this._initializeAudioContext();
  28869. }
  28870. return this._audioContext;
  28871. },
  28872. enumerable: true,
  28873. configurable: true
  28874. });
  28875. AudioEngine.prototype._initializeAudioContext = function () {
  28876. try {
  28877. if (this.canUseWebAudio) {
  28878. this._audioContext = new AudioContext();
  28879. // create a global volume gain node
  28880. this.masterGain = this._audioContext.createGain();
  28881. this.masterGain.gain.value = 1;
  28882. this.masterGain.connect(this._audioContext.destination);
  28883. this._audioContextInitialized = true;
  28884. }
  28885. }
  28886. catch (e) {
  28887. this.canUseWebAudio = false;
  28888. BABYLON.Tools.Error("Web Audio: " + e.message);
  28889. }
  28890. };
  28891. AudioEngine.prototype.dispose = function () {
  28892. if (this.canUseWebAudio && this._audioContextInitialized) {
  28893. if (this._connectedAnalyser) {
  28894. this._connectedAnalyser.stopDebugCanvas();
  28895. this._connectedAnalyser.dispose();
  28896. this.masterGain.disconnect();
  28897. this.masterGain.connect(this._audioContext.destination);
  28898. this._connectedAnalyser = null;
  28899. }
  28900. this.masterGain.gain.value = 1;
  28901. }
  28902. this.WarnedWebAudioUnsupported = false;
  28903. };
  28904. AudioEngine.prototype.getGlobalVolume = function () {
  28905. if (this.canUseWebAudio && this._audioContextInitialized) {
  28906. return this.masterGain.gain.value;
  28907. }
  28908. else {
  28909. return -1;
  28910. }
  28911. };
  28912. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28913. if (this.canUseWebAudio && this._audioContextInitialized) {
  28914. this.masterGain.gain.value = newVolume;
  28915. }
  28916. };
  28917. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28918. if (this._connectedAnalyser) {
  28919. this._connectedAnalyser.stopDebugCanvas();
  28920. }
  28921. if (this.canUseWebAudio && this._audioContextInitialized) {
  28922. this._connectedAnalyser = analyser;
  28923. this.masterGain.disconnect();
  28924. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28925. }
  28926. };
  28927. return AudioEngine;
  28928. })();
  28929. BABYLON.AudioEngine = AudioEngine;
  28930. })(BABYLON || (BABYLON = {}));
  28931. //# sourceMappingURL=babylon.audioEngine.js.map
  28932. var BABYLON;
  28933. (function (BABYLON) {
  28934. var Sound = (function () {
  28935. /**
  28936. * Create a sound and attach it to a scene
  28937. * @param name Name of your sound
  28938. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28939. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28940. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28941. */
  28942. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28943. var _this = this;
  28944. this.autoplay = false;
  28945. this.loop = false;
  28946. this.useCustomAttenuation = false;
  28947. this.spatialSound = false;
  28948. this.refDistance = 1;
  28949. this.rolloffFactor = 1;
  28950. this.maxDistance = 100;
  28951. this.distanceModel = "linear";
  28952. this._panningModel = "equalpower";
  28953. this._playbackRate = 1;
  28954. this._startTime = 0;
  28955. this._startOffset = 0;
  28956. this._position = BABYLON.Vector3.Zero();
  28957. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28958. this._volume = 1;
  28959. this._isLoaded = false;
  28960. this._isReadyToPlay = false;
  28961. this.isPlaying = false;
  28962. this.isPaused = false;
  28963. this._isDirectional = false;
  28964. // Used if you'd like to create a directional sound.
  28965. // If not set, the sound will be omnidirectional
  28966. this._coneInnerAngle = 360;
  28967. this._coneOuterAngle = 360;
  28968. this._coneOuterGain = 0;
  28969. this.name = name;
  28970. this._scene = scene;
  28971. this._readyToPlayCallback = readyToPlayCallback;
  28972. // Default custom attenuation function is a linear attenuation
  28973. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28974. if (currentDistance < maxDistance) {
  28975. return currentVolume * (1 - currentDistance / maxDistance);
  28976. }
  28977. else {
  28978. return 0;
  28979. }
  28980. };
  28981. if (options) {
  28982. this.autoplay = options.autoplay || false;
  28983. this.loop = options.loop || false;
  28984. // if volume === 0, we need another way to check this option
  28985. if (options.volume !== undefined) {
  28986. this._volume = options.volume;
  28987. }
  28988. this.spatialSound = options.spatialSound || false;
  28989. this.maxDistance = options.maxDistance || 100;
  28990. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28991. this.rolloffFactor = options.rolloffFactor || 1;
  28992. this.refDistance = options.refDistance || 1;
  28993. this.distanceModel = options.distanceModel || "linear";
  28994. this._playbackRate = options.playbackRate || 1;
  28995. }
  28996. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28997. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28998. this._soundGain.gain.value = this._volume;
  28999. this._inputAudioNode = this._soundGain;
  29000. this._ouputAudioNode = this._soundGain;
  29001. if (this.spatialSound) {
  29002. this._createSpatialParameters();
  29003. }
  29004. this._scene.mainSoundTrack.AddSound(this);
  29005. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29006. if (urlOrArrayBuffer) {
  29007. // If it's an URL
  29008. if (typeof (urlOrArrayBuffer) === "string") {
  29009. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29010. }
  29011. else {
  29012. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29013. this._soundLoaded(urlOrArrayBuffer);
  29014. }
  29015. else {
  29016. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29017. }
  29018. }
  29019. }
  29020. }
  29021. else {
  29022. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29023. this._scene.mainSoundTrack.AddSound(this);
  29024. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29025. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29026. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29027. }
  29028. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29029. if (this._readyToPlayCallback) {
  29030. window.setTimeout(function () {
  29031. _this._readyToPlayCallback();
  29032. }, 1000);
  29033. }
  29034. }
  29035. }
  29036. Sound.prototype.dispose = function () {
  29037. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29038. if (this.isPlaying) {
  29039. this.stop();
  29040. }
  29041. this._isReadyToPlay = false;
  29042. if (this.soundTrackId === -1) {
  29043. this._scene.mainSoundTrack.RemoveSound(this);
  29044. }
  29045. else {
  29046. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29047. }
  29048. if (this._soundGain) {
  29049. this._soundGain.disconnect();
  29050. this._soundGain = null;
  29051. }
  29052. if (this._soundPanner) {
  29053. this._soundPanner.disconnect();
  29054. this._soundPanner = null;
  29055. }
  29056. if (this._soundSource) {
  29057. this._soundSource.disconnect();
  29058. this._soundSource = null;
  29059. }
  29060. this._audioBuffer = null;
  29061. if (this._connectedMesh) {
  29062. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29063. this._connectedMesh = null;
  29064. }
  29065. }
  29066. };
  29067. Sound.prototype._soundLoaded = function (audioData) {
  29068. var _this = this;
  29069. this._isLoaded = true;
  29070. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29071. _this._audioBuffer = buffer;
  29072. _this._isReadyToPlay = true;
  29073. if (_this.autoplay) {
  29074. _this.play();
  29075. }
  29076. if (_this._readyToPlayCallback) {
  29077. _this._readyToPlayCallback();
  29078. }
  29079. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  29080. };
  29081. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29083. this._audioBuffer = audioBuffer;
  29084. this._isReadyToPlay = true;
  29085. }
  29086. };
  29087. Sound.prototype.updateOptions = function (options) {
  29088. if (options) {
  29089. this.loop = options.loop || this.loop;
  29090. this.maxDistance = options.maxDistance || this.maxDistance;
  29091. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29092. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29093. this.refDistance = options.refDistance || this.refDistance;
  29094. this.distanceModel = options.distanceModel || this.distanceModel;
  29095. this._playbackRate = options.playbackRate || this._playbackRate;
  29096. }
  29097. };
  29098. Sound.prototype._createSpatialParameters = function () {
  29099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29100. if (this._scene.headphone) {
  29101. this._panningModel = "HRTF";
  29102. }
  29103. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29104. if (this.useCustomAttenuation) {
  29105. // Tricks to disable in a way embedded Web Audio attenuation
  29106. this._soundPanner.distanceModel = "linear";
  29107. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29108. this._soundPanner.refDistance = 1;
  29109. this._soundPanner.rolloffFactor = 1;
  29110. this._soundPanner.panningModel = this._panningModel;
  29111. }
  29112. else {
  29113. this._soundPanner.distanceModel = this.distanceModel;
  29114. this._soundPanner.maxDistance = this.maxDistance;
  29115. this._soundPanner.refDistance = this.refDistance;
  29116. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29117. this._soundPanner.panningModel = this._panningModel;
  29118. }
  29119. this._soundPanner.connect(this._ouputAudioNode);
  29120. this._inputAudioNode = this._soundPanner;
  29121. }
  29122. };
  29123. Sound.prototype.switchPanningModelToHRTF = function () {
  29124. this._panningModel = "HRTF";
  29125. this._switchPanningModel();
  29126. };
  29127. Sound.prototype.switchPanningModelToEqualPower = function () {
  29128. this._panningModel = "equalpower";
  29129. this._switchPanningModel();
  29130. };
  29131. Sound.prototype._switchPanningModel = function () {
  29132. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29133. this._soundPanner.panningModel = this._panningModel;
  29134. }
  29135. };
  29136. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29137. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29138. this._ouputAudioNode.disconnect();
  29139. this._ouputAudioNode.connect(soundTrackAudioNode);
  29140. }
  29141. };
  29142. /**
  29143. * Transform this sound into a directional source
  29144. * @param coneInnerAngle Size of the inner cone in degree
  29145. * @param coneOuterAngle Size of the outer cone in degree
  29146. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29147. */
  29148. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29149. if (coneOuterAngle < coneInnerAngle) {
  29150. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29151. return;
  29152. }
  29153. this._coneInnerAngle = coneInnerAngle;
  29154. this._coneOuterAngle = coneOuterAngle;
  29155. this._coneOuterGain = coneOuterGain;
  29156. this._isDirectional = true;
  29157. if (this.isPlaying && this.loop) {
  29158. this.stop();
  29159. this.play();
  29160. }
  29161. };
  29162. Sound.prototype.setPosition = function (newPosition) {
  29163. this._position = newPosition;
  29164. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29165. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29166. }
  29167. };
  29168. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29169. this._localDirection = newLocalDirection;
  29170. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29171. this._updateDirection();
  29172. }
  29173. };
  29174. Sound.prototype._updateDirection = function () {
  29175. var mat = this._connectedMesh.getWorldMatrix();
  29176. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29177. direction.normalize();
  29178. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29179. };
  29180. Sound.prototype.updateDistanceFromListener = function () {
  29181. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29182. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29183. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29184. }
  29185. };
  29186. Sound.prototype.setAttenuationFunction = function (callback) {
  29187. this._customAttenuationFunction = callback;
  29188. };
  29189. /**
  29190. * Play the sound
  29191. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29192. */
  29193. Sound.prototype.play = function (time) {
  29194. var _this = this;
  29195. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29196. try {
  29197. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29198. if (!this._soundSource) {
  29199. if (this.spatialSound) {
  29200. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29201. if (this._isDirectional) {
  29202. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29203. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29204. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29205. if (this._connectedMesh) {
  29206. this._updateDirection();
  29207. }
  29208. else {
  29209. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29210. }
  29211. }
  29212. }
  29213. }
  29214. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29215. this._soundSource.buffer = this._audioBuffer;
  29216. this._soundSource.connect(this._inputAudioNode);
  29217. this._soundSource.loop = this.loop;
  29218. this._soundSource.playbackRate.value = this._playbackRate;
  29219. this._startTime = startTime;
  29220. this._soundSource.onended = function () { _this._onended(); };
  29221. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29222. this.isPlaying = true;
  29223. this.isPaused = false;
  29224. }
  29225. catch (ex) {
  29226. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29227. }
  29228. }
  29229. };
  29230. Sound.prototype._onended = function () {
  29231. this.isPlaying = false;
  29232. if (this.onended) {
  29233. this.onended();
  29234. }
  29235. };
  29236. /**
  29237. * Stop the sound
  29238. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29239. */
  29240. Sound.prototype.stop = function (time) {
  29241. if (this.isPlaying) {
  29242. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29243. this._soundSource.stop(stopTime);
  29244. this.isPlaying = false;
  29245. }
  29246. };
  29247. Sound.prototype.pause = function () {
  29248. if (this.isPlaying) {
  29249. this.stop(0);
  29250. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29251. this.isPaused = true;
  29252. }
  29253. };
  29254. Sound.prototype.setVolume = function (newVolume, time) {
  29255. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  29256. if (time) {
  29257. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29258. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29259. }
  29260. else {
  29261. this._soundGain.gain.value = newVolume;
  29262. }
  29263. }
  29264. this._volume = newVolume;
  29265. };
  29266. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29267. this._playbackRate = newPlaybackRate;
  29268. if (this.isPlaying) {
  29269. this._soundSource.playbackRate.value = this._playbackRate;
  29270. }
  29271. };
  29272. Sound.prototype.getVolume = function () {
  29273. return this._volume;
  29274. };
  29275. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29276. var _this = this;
  29277. this._connectedMesh = meshToConnectTo;
  29278. if (!this.spatialSound) {
  29279. this._createSpatialParameters();
  29280. this.spatialSound = true;
  29281. if (this.isPlaying && this.loop) {
  29282. this.stop();
  29283. this.play();
  29284. }
  29285. }
  29286. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29287. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29288. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29289. };
  29290. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29291. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29292. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29293. this._updateDirection();
  29294. }
  29295. };
  29296. return Sound;
  29297. })();
  29298. BABYLON.Sound = Sound;
  29299. })(BABYLON || (BABYLON = {}));
  29300. //# sourceMappingURL=babylon.sound.js.map
  29301. var BABYLON;
  29302. (function (BABYLON) {
  29303. var SoundTrack = (function () {
  29304. function SoundTrack(scene, options) {
  29305. this.id = -1;
  29306. this._isMainTrack = false;
  29307. this._scene = scene;
  29308. this._audioEngine = BABYLON.Engine.audioEngine;
  29309. this.soundCollection = new Array();
  29310. if (this._audioEngine.canUseWebAudio) {
  29311. this._trackGain = this._audioEngine.audioContext.createGain();
  29312. this._trackGain.connect(this._audioEngine.masterGain);
  29313. if (options) {
  29314. if (options.volume) {
  29315. this._trackGain.gain.value = options.volume;
  29316. }
  29317. if (options.mainTrack) {
  29318. this._isMainTrack = options.mainTrack;
  29319. }
  29320. }
  29321. }
  29322. if (!this._isMainTrack) {
  29323. this._scene.soundTracks.push(this);
  29324. this.id = this._scene.soundTracks.length - 1;
  29325. }
  29326. }
  29327. SoundTrack.prototype.dispose = function () {
  29328. if (this._audioEngine.canUseWebAudio) {
  29329. if (this._connectedAnalyser) {
  29330. this._connectedAnalyser.stopDebugCanvas();
  29331. }
  29332. while (this.soundCollection.length) {
  29333. this.soundCollection[0].dispose();
  29334. }
  29335. this._trackGain.disconnect();
  29336. this._trackGain = null;
  29337. }
  29338. };
  29339. SoundTrack.prototype.AddSound = function (sound) {
  29340. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29341. sound.connectToSoundTrackAudioNode(this._trackGain);
  29342. }
  29343. if (sound.soundTrackId) {
  29344. if (sound.soundTrackId === -1) {
  29345. this._scene.mainSoundTrack.RemoveSound(sound);
  29346. }
  29347. else {
  29348. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29349. }
  29350. }
  29351. this.soundCollection.push(sound);
  29352. sound.soundTrackId = this.id;
  29353. };
  29354. SoundTrack.prototype.RemoveSound = function (sound) {
  29355. var index = this.soundCollection.indexOf(sound);
  29356. if (index !== -1) {
  29357. this.soundCollection.splice(index, 1);
  29358. }
  29359. };
  29360. SoundTrack.prototype.setVolume = function (newVolume) {
  29361. if (this._audioEngine.canUseWebAudio) {
  29362. this._trackGain.gain.value = newVolume;
  29363. }
  29364. };
  29365. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29366. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29367. for (var i = 0; i < this.soundCollection.length; i++) {
  29368. this.soundCollection[i].switchPanningModelToHRTF();
  29369. }
  29370. }
  29371. };
  29372. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29373. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29374. for (var i = 0; i < this.soundCollection.length; i++) {
  29375. this.soundCollection[i].switchPanningModelToEqualPower();
  29376. }
  29377. }
  29378. };
  29379. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29380. if (this._connectedAnalyser) {
  29381. this._connectedAnalyser.stopDebugCanvas();
  29382. }
  29383. this._connectedAnalyser = analyser;
  29384. if (this._audioEngine.canUseWebAudio) {
  29385. this._trackGain.disconnect();
  29386. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  29387. }
  29388. };
  29389. return SoundTrack;
  29390. })();
  29391. BABYLON.SoundTrack = SoundTrack;
  29392. })(BABYLON || (BABYLON = {}));
  29393. //# sourceMappingURL=babylon.soundtrack.js.map
  29394. var BABYLON;
  29395. (function (BABYLON) {
  29396. var DebugLayer = (function () {
  29397. function DebugLayer(scene) {
  29398. var _this = this;
  29399. this._transformationMatrix = BABYLON.Matrix.Identity();
  29400. this._enabled = false;
  29401. this._labelsEnabled = false;
  29402. this._displayStatistics = true;
  29403. this._displayTree = false;
  29404. this._displayLogs = false;
  29405. this._identityMatrix = BABYLON.Matrix.Identity();
  29406. this.axisRatio = 0.02;
  29407. this.accentColor = "orange";
  29408. this._scene = scene;
  29409. this._syncPositions = function () {
  29410. var engine = _this._scene.getEngine();
  29411. var canvasRect = engine.getRenderingCanvasClientRect();
  29412. if (_this._showUI) {
  29413. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29414. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29415. _this._statsDiv.style.width = "400px";
  29416. _this._statsDiv.style.height = "auto";
  29417. _this._statsSubsetDiv.style.maxHeight = "240px";
  29418. _this._optionsDiv.style.left = "0px";
  29419. _this._optionsDiv.style.top = "10px";
  29420. _this._optionsDiv.style.width = "200px";
  29421. _this._optionsDiv.style.height = "auto";
  29422. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29423. _this._logDiv.style.left = "0px";
  29424. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29425. _this._logDiv.style.width = "600px";
  29426. _this._logDiv.style.height = "160px";
  29427. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29428. _this._treeDiv.style.top = "10px";
  29429. _this._treeDiv.style.width = "300px";
  29430. _this._treeDiv.style.height = "auto";
  29431. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29432. }
  29433. _this._globalDiv.style.left = canvasRect.left + "px";
  29434. _this._globalDiv.style.top = canvasRect.top + "px";
  29435. _this._drawingCanvas.style.left = "0px";
  29436. _this._drawingCanvas.style.top = "0px";
  29437. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29438. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29439. var devicePixelRatio = window.devicePixelRatio || 1;
  29440. var context = _this._drawingContext;
  29441. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29442. context.mozBackingStorePixelRatio ||
  29443. context.msBackingStorePixelRatio ||
  29444. context.oBackingStorePixelRatio ||
  29445. context.backingStorePixelRatio || 1;
  29446. _this._ratio = devicePixelRatio / backingStoreRatio;
  29447. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29448. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29449. };
  29450. this._onCanvasClick = function (evt) {
  29451. _this._clickPosition = {
  29452. x: evt.clientX * _this._ratio,
  29453. y: evt.clientY * _this._ratio
  29454. };
  29455. };
  29456. this._syncUI = function () {
  29457. if (_this._showUI) {
  29458. if (_this._displayStatistics) {
  29459. _this._displayStats();
  29460. _this._statsDiv.style.display = "";
  29461. }
  29462. else {
  29463. _this._statsDiv.style.display = "none";
  29464. }
  29465. if (_this._displayLogs) {
  29466. _this._logDiv.style.display = "";
  29467. }
  29468. else {
  29469. _this._logDiv.style.display = "none";
  29470. }
  29471. if (_this._displayTree) {
  29472. _this._treeDiv.style.display = "";
  29473. if (_this._needToRefreshMeshesTree) {
  29474. _this._needToRefreshMeshesTree = false;
  29475. _this._refreshMeshesTreeContent();
  29476. }
  29477. }
  29478. else {
  29479. _this._treeDiv.style.display = "none";
  29480. }
  29481. }
  29482. };
  29483. this._syncData = function () {
  29484. if (_this._labelsEnabled || !_this._showUI) {
  29485. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29486. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29487. var engine = _this._scene.getEngine();
  29488. var viewport = _this._camera.viewport;
  29489. var globalViewport = viewport.toGlobal(engine);
  29490. // Meshes
  29491. var meshes = _this._camera.getActiveMeshes();
  29492. for (var index = 0; index < meshes.length; index++) {
  29493. var mesh = meshes.data[index];
  29494. var position = mesh.getBoundingInfo().boundingSphere.center;
  29495. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29496. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29497. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29498. }
  29499. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29500. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29501. }
  29502. }
  29503. // Cameras
  29504. var cameras = _this._scene.cameras;
  29505. for (index = 0; index < cameras.length; index++) {
  29506. var camera = cameras[index];
  29507. if (camera === _this._camera) {
  29508. continue;
  29509. }
  29510. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29511. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29512. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29513. _this._camera.detachControl(engine.getRenderingCanvas());
  29514. _this._camera = camera;
  29515. _this._camera.attachControl(engine.getRenderingCanvas());
  29516. }, function () { return "purple"; });
  29517. }
  29518. }
  29519. // Lights
  29520. var lights = _this._scene.lights;
  29521. for (index = 0; index < lights.length; index++) {
  29522. var light = lights[index];
  29523. if (light.position) {
  29524. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29525. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29526. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29527. light.setEnabled(!light.isEnabled());
  29528. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29529. }
  29530. }
  29531. }
  29532. }
  29533. _this._clickPosition = undefined;
  29534. };
  29535. }
  29536. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29537. while (this._treeSubsetDiv.hasChildNodes()) {
  29538. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29539. }
  29540. // Add meshes
  29541. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29542. sortedArray.sort(function (a, b) {
  29543. if (a.name === b.name) {
  29544. return 0;
  29545. }
  29546. return (a.name > b.name) ? 1 : -1;
  29547. });
  29548. for (var index = 0; index < sortedArray.length; index++) {
  29549. var mesh = sortedArray[index];
  29550. if (!mesh.isEnabled()) {
  29551. continue;
  29552. }
  29553. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29554. m.isVisible = element.checked;
  29555. }, mesh);
  29556. }
  29557. };
  29558. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29559. this._drawingContext.beginPath();
  29560. this._drawingContext.moveTo(zero.x, zero.y);
  29561. this._drawingContext.lineTo(unit.x, unit.y);
  29562. this._drawingContext.strokeStyle = color;
  29563. this._drawingContext.lineWidth = 4;
  29564. this._drawingContext.stroke();
  29565. this._drawingContext.font = "normal 14px Segoe UI";
  29566. this._drawingContext.fillStyle = color;
  29567. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29568. };
  29569. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29570. var position = mesh.getBoundingInfo().boundingSphere.center;
  29571. var worldMatrix = mesh.getWorldMatrix();
  29572. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29573. var unit = (unprojectedVector.subtract(position)).length();
  29574. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29575. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29576. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29577. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29578. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29579. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29580. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29581. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29582. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29583. };
  29584. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29585. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29586. this._drawingContext.font = "normal 12px Segoe UI";
  29587. var textMetrics = this._drawingContext.measureText(text);
  29588. var centerX = projectedPosition.x - textMetrics.width / 2;
  29589. var centerY = projectedPosition.y;
  29590. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29591. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29592. onClick();
  29593. }
  29594. this._drawingContext.beginPath();
  29595. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29596. this._drawingContext.fillStyle = getFillStyle();
  29597. this._drawingContext.globalAlpha = 0.5;
  29598. this._drawingContext.fill();
  29599. this._drawingContext.globalAlpha = 1.0;
  29600. this._drawingContext.strokeStyle = '#FFFFFF';
  29601. this._drawingContext.lineWidth = 1;
  29602. this._drawingContext.stroke();
  29603. this._drawingContext.fillStyle = "#FFFFFF";
  29604. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29605. this._drawingContext.beginPath();
  29606. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29607. this._drawingContext.fill();
  29608. }
  29609. };
  29610. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29611. if (!this._clickPosition) {
  29612. return false;
  29613. }
  29614. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29615. return false;
  29616. }
  29617. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29618. return false;
  29619. }
  29620. return true;
  29621. };
  29622. DebugLayer.prototype.isVisible = function () {
  29623. return this._enabled;
  29624. };
  29625. DebugLayer.prototype.hide = function () {
  29626. if (!this._enabled) {
  29627. return;
  29628. }
  29629. this._enabled = false;
  29630. var engine = this._scene.getEngine();
  29631. this._scene.unregisterBeforeRender(this._syncData);
  29632. this._scene.unregisterAfterRender(this._syncUI);
  29633. document.body.removeChild(this._globalDiv);
  29634. window.removeEventListener("resize", this._syncPositions);
  29635. this._scene.forceShowBoundingBoxes = false;
  29636. this._scene.forceWireframe = false;
  29637. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29638. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29639. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29640. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29641. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29642. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29643. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29644. this._scene.shadowsEnabled = true;
  29645. this._scene.particlesEnabled = true;
  29646. this._scene.postProcessesEnabled = true;
  29647. this._scene.collisionsEnabled = true;
  29648. this._scene.lightsEnabled = true;
  29649. this._scene.texturesEnabled = true;
  29650. this._scene.lensFlaresEnabled = true;
  29651. this._scene.proceduralTexturesEnabled = true;
  29652. this._scene.renderTargetsEnabled = true;
  29653. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29654. };
  29655. DebugLayer.prototype.show = function (showUI, camera) {
  29656. if (showUI === void 0) { showUI = true; }
  29657. if (camera === void 0) { camera = null; }
  29658. if (this._enabled) {
  29659. return;
  29660. }
  29661. this._enabled = true;
  29662. if (camera) {
  29663. this._camera = camera;
  29664. }
  29665. else {
  29666. this._camera = this._scene.activeCamera;
  29667. }
  29668. this._showUI = showUI;
  29669. var engine = this._scene.getEngine();
  29670. this._globalDiv = document.createElement("div");
  29671. document.body.appendChild(this._globalDiv);
  29672. this._generateDOMelements();
  29673. window.addEventListener("resize", this._syncPositions);
  29674. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29675. this._syncPositions();
  29676. this._scene.registerBeforeRender(this._syncData);
  29677. this._scene.registerAfterRender(this._syncUI);
  29678. };
  29679. DebugLayer.prototype._clearLabels = function () {
  29680. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29681. for (var index = 0; index < this._scene.meshes.length; index++) {
  29682. var mesh = this._scene.meshes[index];
  29683. mesh.renderOverlay = false;
  29684. }
  29685. };
  29686. DebugLayer.prototype._generateheader = function (root, text) {
  29687. var header = document.createElement("div");
  29688. header.innerHTML = text + "&nbsp;";
  29689. header.style.textAlign = "right";
  29690. header.style.width = "100%";
  29691. header.style.color = "white";
  29692. header.style.backgroundColor = "Black";
  29693. header.style.padding = "5px 5px 4px 0px";
  29694. header.style.marginLeft = "-5px";
  29695. header.style.fontWeight = "bold";
  29696. root.appendChild(header);
  29697. };
  29698. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29699. var label = document.createElement("label");
  29700. label.innerHTML = title;
  29701. label.style.color = color;
  29702. root.appendChild(label);
  29703. root.appendChild(document.createElement("br"));
  29704. };
  29705. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29706. if (tag === void 0) { tag = null; }
  29707. var label = document.createElement("label");
  29708. var boundingBoxesCheckbox = document.createElement("input");
  29709. boundingBoxesCheckbox.type = "checkbox";
  29710. boundingBoxesCheckbox.checked = initialState;
  29711. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29712. task(evt.target, tag);
  29713. });
  29714. label.appendChild(boundingBoxesCheckbox);
  29715. var container = document.createElement("span");
  29716. var leftPart = document.createElement("span");
  29717. var rightPart = document.createElement("span");
  29718. rightPart.style.cssFloat = "right";
  29719. leftPart.innerHTML = leftTitle;
  29720. rightPart.innerHTML = rightTitle;
  29721. rightPart.style.fontSize = "12px";
  29722. rightPart.style.maxWidth = "200px";
  29723. container.appendChild(leftPart);
  29724. container.appendChild(rightPart);
  29725. label.appendChild(container);
  29726. root.appendChild(label);
  29727. root.appendChild(document.createElement("br"));
  29728. };
  29729. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29730. if (tag === void 0) { tag = null; }
  29731. var label = document.createElement("label");
  29732. var checkBox = document.createElement("input");
  29733. checkBox.type = "checkbox";
  29734. checkBox.checked = initialState;
  29735. checkBox.addEventListener("change", function (evt) {
  29736. task(evt.target, tag);
  29737. });
  29738. label.appendChild(checkBox);
  29739. label.appendChild(document.createTextNode(title));
  29740. root.appendChild(label);
  29741. root.appendChild(document.createElement("br"));
  29742. };
  29743. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29744. if (tag === void 0) { tag = null; }
  29745. var button = document.createElement("button");
  29746. button.innerHTML = title;
  29747. button.style.height = "24px";
  29748. button.style.color = "#444444";
  29749. button.style.border = "1px solid white";
  29750. button.className = "debugLayerButton";
  29751. button.addEventListener("click", function (evt) {
  29752. task(evt.target, tag);
  29753. });
  29754. root.appendChild(button);
  29755. root.appendChild(document.createElement("br"));
  29756. };
  29757. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29758. if (tag === void 0) { tag = null; }
  29759. var label = document.createElement("label");
  29760. var boundingBoxesRadio = document.createElement("input");
  29761. boundingBoxesRadio.type = "radio";
  29762. boundingBoxesRadio.name = name;
  29763. boundingBoxesRadio.checked = initialState;
  29764. boundingBoxesRadio.addEventListener("change", function (evt) {
  29765. task(evt.target, tag);
  29766. });
  29767. label.appendChild(boundingBoxesRadio);
  29768. label.appendChild(document.createTextNode(title));
  29769. root.appendChild(label);
  29770. root.appendChild(document.createElement("br"));
  29771. };
  29772. DebugLayer.prototype._generateDOMelements = function () {
  29773. var _this = this;
  29774. this._globalDiv.id = "DebugLayer";
  29775. this._globalDiv.style.position = "absolute";
  29776. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29777. this._globalDiv.style.fontSize = "14px";
  29778. this._globalDiv.style.color = "white";
  29779. // Drawing canvas
  29780. this._drawingCanvas = document.createElement("canvas");
  29781. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29782. this._drawingCanvas.style.position = "absolute";
  29783. this._drawingCanvas.style.pointerEvents = "none";
  29784. this._drawingContext = this._drawingCanvas.getContext("2d");
  29785. this._globalDiv.appendChild(this._drawingCanvas);
  29786. if (this._showUI) {
  29787. var background = "rgba(128, 128, 128, 0.4)";
  29788. var border = "rgb(180, 180, 180) solid 1px";
  29789. // Stats
  29790. this._statsDiv = document.createElement("div");
  29791. this._statsDiv.id = "DebugLayerStats";
  29792. this._statsDiv.style.border = border;
  29793. this._statsDiv.style.position = "absolute";
  29794. this._statsDiv.style.background = background;
  29795. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29796. this._generateheader(this._statsDiv, "STATISTICS");
  29797. this._statsSubsetDiv = document.createElement("div");
  29798. this._statsSubsetDiv.style.paddingTop = "5px";
  29799. this._statsSubsetDiv.style.paddingBottom = "5px";
  29800. this._statsSubsetDiv.style.overflowY = "auto";
  29801. this._statsDiv.appendChild(this._statsSubsetDiv);
  29802. // Tree
  29803. this._treeDiv = document.createElement("div");
  29804. this._treeDiv.id = "DebugLayerTree";
  29805. this._treeDiv.style.border = border;
  29806. this._treeDiv.style.position = "absolute";
  29807. this._treeDiv.style.background = background;
  29808. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29809. this._treeDiv.style.display = "none";
  29810. this._generateheader(this._treeDiv, "MESHES TREE");
  29811. this._treeSubsetDiv = document.createElement("div");
  29812. this._treeSubsetDiv.style.paddingTop = "5px";
  29813. this._treeSubsetDiv.style.paddingRight = "5px";
  29814. this._treeSubsetDiv.style.overflowY = "auto";
  29815. this._treeSubsetDiv.style.maxHeight = "300px";
  29816. this._treeDiv.appendChild(this._treeSubsetDiv);
  29817. this._needToRefreshMeshesTree = true;
  29818. // Logs
  29819. this._logDiv = document.createElement("div");
  29820. this._logDiv.style.border = border;
  29821. this._logDiv.id = "DebugLayerLogs";
  29822. this._logDiv.style.position = "absolute";
  29823. this._logDiv.style.background = background;
  29824. this._logDiv.style.padding = "0px 0px 0px 5px";
  29825. this._logDiv.style.display = "none";
  29826. this._generateheader(this._logDiv, "LOGS");
  29827. this._logSubsetDiv = document.createElement("div");
  29828. this._logSubsetDiv.style.height = "127px";
  29829. this._logSubsetDiv.style.paddingTop = "5px";
  29830. this._logSubsetDiv.style.overflowY = "auto";
  29831. this._logSubsetDiv.style.fontSize = "12px";
  29832. this._logSubsetDiv.style.fontFamily = "consolas";
  29833. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29834. this._logDiv.appendChild(this._logSubsetDiv);
  29835. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29836. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29837. };
  29838. // Options
  29839. this._optionsDiv = document.createElement("div");
  29840. this._optionsDiv.id = "DebugLayerOptions";
  29841. this._optionsDiv.style.border = border;
  29842. this._optionsDiv.style.position = "absolute";
  29843. this._optionsDiv.style.background = background;
  29844. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29845. this._optionsDiv.style.overflowY = "auto";
  29846. this._generateheader(this._optionsDiv, "OPTIONS");
  29847. this._optionsSubsetDiv = document.createElement("div");
  29848. this._optionsSubsetDiv.style.paddingTop = "5px";
  29849. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29850. this._optionsSubsetDiv.style.overflowY = "auto";
  29851. this._optionsSubsetDiv.style.maxHeight = "200px";
  29852. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29853. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29854. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29855. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29856. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29857. _this._displayTree = element.checked;
  29858. _this._needToRefreshMeshesTree = true;
  29859. });
  29860. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29861. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29862. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29863. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29864. _this._labelsEnabled = element.checked;
  29865. if (!_this._labelsEnabled) {
  29866. _this._clearLabels();
  29867. }
  29868. });
  29869. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29870. if (element.checked) {
  29871. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29872. }
  29873. else {
  29874. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29875. }
  29876. });
  29877. ;
  29878. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29879. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29880. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29881. if (element.checked) {
  29882. _this._scene.forceWireframe = false;
  29883. _this._scene.forcePointsCloud = false;
  29884. }
  29885. });
  29886. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29887. if (element.checked) {
  29888. _this._scene.forceWireframe = true;
  29889. _this._scene.forcePointsCloud = false;
  29890. }
  29891. });
  29892. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29893. if (element.checked) {
  29894. _this._scene.forceWireframe = false;
  29895. _this._scene.forcePointsCloud = true;
  29896. }
  29897. });
  29898. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29899. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29900. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29901. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29902. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29903. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29904. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29905. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29906. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29907. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29908. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29909. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29910. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29911. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29912. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29913. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29914. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29915. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29916. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29917. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29918. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29919. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29920. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29921. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29922. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29923. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29924. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29925. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29926. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29927. if (element.checked) {
  29928. _this._scene.headphone = true;
  29929. }
  29930. });
  29931. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29932. if (element.checked) {
  29933. _this._scene.headphone = false;
  29934. }
  29935. });
  29936. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29937. _this._scene.audioEnabled = !element.checked;
  29938. });
  29939. }
  29940. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29941. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29942. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29943. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29944. this._globalDiv.appendChild(this._statsDiv);
  29945. this._globalDiv.appendChild(this._logDiv);
  29946. this._globalDiv.appendChild(this._optionsDiv);
  29947. this._globalDiv.appendChild(this._treeDiv);
  29948. }
  29949. };
  29950. DebugLayer.prototype._displayStats = function () {
  29951. var scene = this._scene;
  29952. var engine = scene.getEngine();
  29953. var glInfo = engine.getGlInfo();
  29954. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29955. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29956. + "<b>Count</b><br>"
  29957. + "Total meshes: " + scene.meshes.length + "<br>"
  29958. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29959. + "Total materials: " + scene.materials.length + "<br>"
  29960. + "Total textures: " + scene.textures.length + "<br>"
  29961. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29962. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29963. + "Active bones: " + scene.getActiveBones() + "<br>"
  29964. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29965. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29966. + "<b>Duration</b><br>"
  29967. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29968. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29969. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29970. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29971. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29972. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29973. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29974. + "</div>"
  29975. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29976. + "<b>Extensions</b><br>"
  29977. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29978. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29979. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29980. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29981. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29982. + "<b>Caps.</b><br>"
  29983. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29984. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29985. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29986. + "</div><br>"
  29987. + "<b>Info</b><br>"
  29988. + glInfo.version + "<br>"
  29989. + glInfo.renderer + "<br>";
  29990. if (this.customStatsFunction) {
  29991. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29992. }
  29993. };
  29994. return DebugLayer;
  29995. })();
  29996. BABYLON.DebugLayer = DebugLayer;
  29997. })(BABYLON || (BABYLON = {}));
  29998. //# sourceMappingURL=babylon.debugLayer.js.map
  29999. var __extends = this.__extends || function (d, b) {
  30000. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30001. function __() { this.constructor = d; }
  30002. __.prototype = b.prototype;
  30003. d.prototype = new __();
  30004. };
  30005. var BABYLON;
  30006. (function (BABYLON) {
  30007. var RawTexture = (function (_super) {
  30008. __extends(RawTexture, _super);
  30009. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30011. if (invertY === void 0) { invertY = false; }
  30012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30013. _super.call(this, null, scene, !generateMipMaps, invertY);
  30014. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30015. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30016. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30017. }
  30018. // Statics
  30019. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30020. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30021. if (invertY === void 0) { invertY = false; }
  30022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30023. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30024. };
  30025. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30026. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30027. if (invertY === void 0) { invertY = false; }
  30028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30029. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30030. };
  30031. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30032. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30033. if (invertY === void 0) { invertY = false; }
  30034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30035. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30036. };
  30037. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30038. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30039. if (invertY === void 0) { invertY = false; }
  30040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30041. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30042. };
  30043. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30044. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30045. if (invertY === void 0) { invertY = false; }
  30046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30047. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30048. };
  30049. return RawTexture;
  30050. })(BABYLON.Texture);
  30051. BABYLON.RawTexture = RawTexture;
  30052. })(BABYLON || (BABYLON = {}));
  30053. //# sourceMappingURL=babylon.rawTexture.js.map
  30054. var __extends = this.__extends || function (d, b) {
  30055. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30056. function __() { this.constructor = d; }
  30057. __.prototype = b.prototype;
  30058. d.prototype = new __();
  30059. };
  30060. var BABYLON;
  30061. (function (BABYLON) {
  30062. var IndexedVector2 = (function (_super) {
  30063. __extends(IndexedVector2, _super);
  30064. function IndexedVector2(original, index) {
  30065. _super.call(this, original.x, original.y);
  30066. this.index = index;
  30067. }
  30068. return IndexedVector2;
  30069. })(BABYLON.Vector2);
  30070. var PolygonPoints = (function () {
  30071. function PolygonPoints() {
  30072. this.elements = new Array();
  30073. }
  30074. PolygonPoints.prototype.add = function (originalPoints) {
  30075. var _this = this;
  30076. var result = new Array();
  30077. originalPoints.forEach(function (point) {
  30078. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30079. var newPoint = new IndexedVector2(point, _this.elements.length);
  30080. result.push(newPoint);
  30081. _this.elements.push(newPoint);
  30082. }
  30083. });
  30084. return result;
  30085. };
  30086. PolygonPoints.prototype.computeBounds = function () {
  30087. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30088. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30089. this.elements.forEach(function (point) {
  30090. // x
  30091. if (point.x < lmin.x) {
  30092. lmin.x = point.x;
  30093. }
  30094. else if (point.x > lmax.x) {
  30095. lmax.x = point.x;
  30096. }
  30097. // y
  30098. if (point.y < lmin.y) {
  30099. lmin.y = point.y;
  30100. }
  30101. else if (point.y > lmax.y) {
  30102. lmax.y = point.y;
  30103. }
  30104. });
  30105. return {
  30106. min: lmin,
  30107. max: lmax,
  30108. width: lmax.x - lmin.x,
  30109. height: lmax.y - lmin.y
  30110. };
  30111. };
  30112. return PolygonPoints;
  30113. })();
  30114. var Polygon = (function () {
  30115. function Polygon() {
  30116. }
  30117. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30118. return [
  30119. new BABYLON.Vector2(xmin, ymin),
  30120. new BABYLON.Vector2(xmax, ymin),
  30121. new BABYLON.Vector2(xmax, ymax),
  30122. new BABYLON.Vector2(xmin, ymax)
  30123. ];
  30124. };
  30125. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30126. if (cx === void 0) { cx = 0; }
  30127. if (cy === void 0) { cy = 0; }
  30128. if (numberOfSides === void 0) { numberOfSides = 32; }
  30129. var result = new Array();
  30130. var angle = 0;
  30131. var increment = (Math.PI * 2) / numberOfSides;
  30132. for (var i = 0; i < numberOfSides; i++) {
  30133. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30134. angle -= increment;
  30135. }
  30136. return result;
  30137. };
  30138. Polygon.Parse = function (input) {
  30139. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30140. var i, result = [];
  30141. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30142. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30143. }
  30144. return result;
  30145. };
  30146. Polygon.StartingAt = function (x, y) {
  30147. return BABYLON.Path2.StartingAt(x, y);
  30148. };
  30149. return Polygon;
  30150. })();
  30151. BABYLON.Polygon = Polygon;
  30152. var PolygonMeshBuilder = (function () {
  30153. function PolygonMeshBuilder(name, contours, scene) {
  30154. this._points = new PolygonPoints();
  30155. this._outlinepoints = new PolygonPoints();
  30156. this._holes = [];
  30157. if (!("poly2tri" in window)) {
  30158. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30159. }
  30160. this._name = name;
  30161. this._scene = scene;
  30162. var points;
  30163. if (contours instanceof BABYLON.Path2) {
  30164. points = contours.getPoints();
  30165. }
  30166. else {
  30167. points = contours;
  30168. }
  30169. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30170. this._outlinepoints.add(points);
  30171. }
  30172. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30173. this._swctx.addHole(this._points.add(hole));
  30174. var holepoints = new PolygonPoints();
  30175. holepoints.add(hole);
  30176. this._holes.push(holepoints);
  30177. return this;
  30178. };
  30179. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30180. var _this = this;
  30181. if (updatable === void 0) { updatable = false; }
  30182. var result = new BABYLON.Mesh(this._name, this._scene);
  30183. var normals = [];
  30184. var positions = [];
  30185. var uvs = [];
  30186. var bounds = this._points.computeBounds();
  30187. this._points.elements.forEach(function (p) {
  30188. normals.push(0, 1.0, 0);
  30189. positions.push(p.x, 0, p.y);
  30190. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30191. });
  30192. var indices = [];
  30193. this._swctx.triangulate();
  30194. this._swctx.getTriangles().forEach(function (triangle) {
  30195. triangle.getPoints().forEach(function (point) {
  30196. indices.push(point.index);
  30197. });
  30198. });
  30199. if (depth > 0) {
  30200. var positionscount = (positions.length / 3); //get the current pointcount
  30201. this._points.elements.forEach(function (p) {
  30202. normals.push(0, -1.0, 0);
  30203. positions.push(p.x, -depth, p.y);
  30204. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30205. });
  30206. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30207. var p2;
  30208. var poscounter = 0;
  30209. this._swctx.getTriangles().forEach(function (triangle) {
  30210. triangle.getPoints().forEach(function (point) {
  30211. switch (poscounter) {
  30212. case 0:
  30213. p1 = point;
  30214. break;
  30215. case 1:
  30216. p2 = point;
  30217. break;
  30218. case 2:
  30219. indices.push(point.index + positionscount);
  30220. indices.push(p2.index + positionscount);
  30221. indices.push(p1.index + positionscount);
  30222. poscounter = -1;
  30223. break;
  30224. }
  30225. poscounter++;
  30226. //indices.push((<IndexedVector2>point).index + positionscount);
  30227. });
  30228. });
  30229. //Add the sides
  30230. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30231. this._holes.forEach(function (hole) {
  30232. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30233. });
  30234. }
  30235. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30236. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30237. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30238. result.setIndices(indices);
  30239. return result;
  30240. };
  30241. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30242. var StartIndex = positions.length / 3;
  30243. var ulength = 0;
  30244. for (var i = 0; i < points.elements.length; i++) {
  30245. var p = points.elements[i];
  30246. var p1;
  30247. if ((i + 1) > points.elements.length - 1) {
  30248. p1 = points.elements[0];
  30249. }
  30250. else {
  30251. p1 = points.elements[i + 1];
  30252. }
  30253. positions.push(p.x, 0, p.y);
  30254. positions.push(p.x, -depth, p.y);
  30255. positions.push(p1.x, 0, p1.y);
  30256. positions.push(p1.x, -depth, p1.y);
  30257. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30258. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30259. var v3 = v2.subtract(v1);
  30260. var v4 = new BABYLON.Vector3(0, 1, 0);
  30261. var vn = BABYLON.Vector3.Cross(v3, v4);
  30262. vn = vn.normalize();
  30263. uvs.push(ulength / bounds.width, 0);
  30264. uvs.push(ulength / bounds.width, 1);
  30265. ulength += v3.length();
  30266. uvs.push((ulength / bounds.width), 0);
  30267. uvs.push((ulength / bounds.width), 1);
  30268. if (!flip) {
  30269. normals.push(-vn.x, -vn.y, -vn.z);
  30270. normals.push(-vn.x, -vn.y, -vn.z);
  30271. normals.push(-vn.x, -vn.y, -vn.z);
  30272. normals.push(-vn.x, -vn.y, -vn.z);
  30273. indices.push(StartIndex);
  30274. indices.push(StartIndex + 1);
  30275. indices.push(StartIndex + 2);
  30276. indices.push(StartIndex + 1);
  30277. indices.push(StartIndex + 3);
  30278. indices.push(StartIndex + 2);
  30279. }
  30280. else {
  30281. normals.push(vn.x, vn.y, vn.z);
  30282. normals.push(vn.x, vn.y, vn.z);
  30283. normals.push(vn.x, vn.y, vn.z);
  30284. normals.push(vn.x, vn.y, vn.z);
  30285. indices.push(StartIndex);
  30286. indices.push(StartIndex + 2);
  30287. indices.push(StartIndex + 1);
  30288. indices.push(StartIndex + 1);
  30289. indices.push(StartIndex + 2);
  30290. indices.push(StartIndex + 3);
  30291. }
  30292. StartIndex += 4;
  30293. }
  30294. ;
  30295. };
  30296. return PolygonMeshBuilder;
  30297. })();
  30298. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30299. })(BABYLON || (BABYLON = {}));
  30300. //# sourceMappingURL=babylon.polygonMesh.js.map
  30301. var BABYLON;
  30302. (function (BABYLON) {
  30303. var SimplificationSettings = (function () {
  30304. function SimplificationSettings(quality, distance, optimizeMesh) {
  30305. this.quality = quality;
  30306. this.distance = distance;
  30307. this.optimizeMesh = optimizeMesh;
  30308. }
  30309. return SimplificationSettings;
  30310. })();
  30311. BABYLON.SimplificationSettings = SimplificationSettings;
  30312. var SimplificationQueue = (function () {
  30313. function SimplificationQueue() {
  30314. this.running = false;
  30315. this._simplificationArray = [];
  30316. }
  30317. SimplificationQueue.prototype.addTask = function (task) {
  30318. this._simplificationArray.push(task);
  30319. };
  30320. SimplificationQueue.prototype.executeNext = function () {
  30321. var task = this._simplificationArray.pop();
  30322. if (task) {
  30323. this.running = true;
  30324. this.runSimplification(task);
  30325. }
  30326. else {
  30327. this.running = false;
  30328. }
  30329. };
  30330. SimplificationQueue.prototype.runSimplification = function (task) {
  30331. var _this = this;
  30332. if (task.parallelProcessing) {
  30333. //parallel simplifier
  30334. task.settings.forEach(function (setting) {
  30335. var simplifier = _this.getSimplifier(task);
  30336. simplifier.simplify(setting, function (newMesh) {
  30337. task.mesh.addLODLevel(setting.distance, newMesh);
  30338. newMesh.isVisible = true;
  30339. //check if it is the last
  30340. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30341. //all done, run the success callback.
  30342. task.successCallback();
  30343. }
  30344. _this.executeNext();
  30345. });
  30346. });
  30347. }
  30348. else {
  30349. //single simplifier.
  30350. var simplifier = this.getSimplifier(task);
  30351. var runDecimation = function (setting, callback) {
  30352. simplifier.simplify(setting, function (newMesh) {
  30353. task.mesh.addLODLevel(setting.distance, newMesh);
  30354. newMesh.isVisible = true;
  30355. //run the next quality level
  30356. callback();
  30357. });
  30358. };
  30359. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30360. runDecimation(task.settings[loop.index], function () {
  30361. loop.executeNext();
  30362. });
  30363. }, function () {
  30364. //execution ended, run the success callback.
  30365. if (task.successCallback) {
  30366. task.successCallback();
  30367. }
  30368. _this.executeNext();
  30369. });
  30370. }
  30371. };
  30372. SimplificationQueue.prototype.getSimplifier = function (task) {
  30373. switch (task.simplificationType) {
  30374. case SimplificationType.QUADRATIC:
  30375. default:
  30376. return new QuadraticErrorSimplification(task.mesh);
  30377. }
  30378. };
  30379. return SimplificationQueue;
  30380. })();
  30381. BABYLON.SimplificationQueue = SimplificationQueue;
  30382. /**
  30383. * The implemented types of simplification.
  30384. * At the moment only Quadratic Error Decimation is implemented.
  30385. */
  30386. (function (SimplificationType) {
  30387. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30388. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30389. var SimplificationType = BABYLON.SimplificationType;
  30390. var DecimationTriangle = (function () {
  30391. function DecimationTriangle(vertices) {
  30392. this.vertices = vertices;
  30393. this.error = new Array(4);
  30394. this.deleted = false;
  30395. this.isDirty = false;
  30396. this.deletePending = false;
  30397. this.borderFactor = 0;
  30398. }
  30399. return DecimationTriangle;
  30400. })();
  30401. BABYLON.DecimationTriangle = DecimationTriangle;
  30402. var DecimationVertex = (function () {
  30403. function DecimationVertex(position, id) {
  30404. this.position = position;
  30405. this.id = id;
  30406. this.isBorder = true;
  30407. this.q = new QuadraticMatrix();
  30408. this.triangleCount = 0;
  30409. this.triangleStart = 0;
  30410. this.originalOffsets = [];
  30411. }
  30412. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30413. this.position.copyFrom(newPosition);
  30414. };
  30415. return DecimationVertex;
  30416. })();
  30417. BABYLON.DecimationVertex = DecimationVertex;
  30418. var QuadraticMatrix = (function () {
  30419. function QuadraticMatrix(data) {
  30420. this.data = new Array(10);
  30421. for (var i = 0; i < 10; ++i) {
  30422. if (data && data[i]) {
  30423. this.data[i] = data[i];
  30424. }
  30425. else {
  30426. this.data[i] = 0;
  30427. }
  30428. }
  30429. }
  30430. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30431. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30432. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30433. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30434. return det;
  30435. };
  30436. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30437. for (var i = 0; i < 10; ++i) {
  30438. this.data[i] += matrix.data[i];
  30439. }
  30440. };
  30441. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30442. for (var i = 0; i < 10; ++i) {
  30443. this.data[i] += data[i];
  30444. }
  30445. };
  30446. QuadraticMatrix.prototype.add = function (matrix) {
  30447. var m = new QuadraticMatrix();
  30448. for (var i = 0; i < 10; ++i) {
  30449. m.data[i] = this.data[i] + matrix.data[i];
  30450. }
  30451. return m;
  30452. };
  30453. QuadraticMatrix.FromData = function (a, b, c, d) {
  30454. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30455. };
  30456. //returning an array to avoid garbage collection
  30457. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30458. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30459. };
  30460. return QuadraticMatrix;
  30461. })();
  30462. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30463. var Reference = (function () {
  30464. function Reference(vertexId, triangleId) {
  30465. this.vertexId = vertexId;
  30466. this.triangleId = triangleId;
  30467. }
  30468. return Reference;
  30469. })();
  30470. BABYLON.Reference = Reference;
  30471. /**
  30472. * An implementation of the Quadratic Error simplification algorithm.
  30473. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30474. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30475. * @author RaananW
  30476. */
  30477. var QuadraticErrorSimplification = (function () {
  30478. function QuadraticErrorSimplification(_mesh) {
  30479. this._mesh = _mesh;
  30480. this.initialized = false;
  30481. this.syncIterations = 5000;
  30482. this.aggressiveness = 7;
  30483. this.decimationIterations = 100;
  30484. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30485. }
  30486. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30487. var _this = this;
  30488. this.initDecimatedMesh();
  30489. //iterating through the submeshes array, one after the other.
  30490. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30491. _this.initWithMesh(loop.index, function () {
  30492. _this.runDecimation(settings, loop.index, function () {
  30493. loop.executeNext();
  30494. });
  30495. }, settings.optimizeMesh);
  30496. }, function () {
  30497. setTimeout(function () {
  30498. successCallback(_this._reconstructedMesh);
  30499. }, 0);
  30500. });
  30501. };
  30502. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30503. var _this = this;
  30504. var gCount = 0;
  30505. triangle.vertices.forEach(function (vertex) {
  30506. var count = 0;
  30507. var vPos = vertex.position;
  30508. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30509. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30510. ++count;
  30511. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30512. ++count;
  30513. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30514. ++count;
  30515. if (count > 1) {
  30516. ++gCount;
  30517. }
  30518. ;
  30519. });
  30520. if (gCount > 1) {
  30521. console.log(triangle, gCount);
  30522. }
  30523. return gCount > 1;
  30524. };
  30525. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30526. var _this = this;
  30527. var targetCount = ~~(this.triangles.length * settings.quality);
  30528. var deletedTriangles = 0;
  30529. var triangleCount = this.triangles.length;
  30530. var iterationFunction = function (iteration, callback) {
  30531. setTimeout(function () {
  30532. if (iteration % 5 === 0) {
  30533. _this.updateMesh(iteration === 0);
  30534. }
  30535. for (var i = 0; i < _this.triangles.length; ++i) {
  30536. _this.triangles[i].isDirty = false;
  30537. }
  30538. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30539. var trianglesIterator = function (i) {
  30540. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30541. var t = _this.triangles[tIdx];
  30542. if (!t)
  30543. return;
  30544. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30545. return;
  30546. }
  30547. for (var j = 0; j < 3; ++j) {
  30548. if (t.error[j] < threshold) {
  30549. var deleted0 = [];
  30550. var deleted1 = [];
  30551. var v0 = t.vertices[j];
  30552. var v1 = t.vertices[(j + 1) % 3];
  30553. if (v0.isBorder !== v1.isBorder)
  30554. continue;
  30555. var p = BABYLON.Vector3.Zero();
  30556. var n = BABYLON.Vector3.Zero();
  30557. var uv = BABYLON.Vector2.Zero();
  30558. var color = new BABYLON.Color4(0, 0, 0, 1);
  30559. _this.calculateError(v0, v1, p, n, uv, color);
  30560. var delTr = [];
  30561. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30562. continue;
  30563. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30564. continue;
  30565. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30566. continue;
  30567. var uniqueArray = [];
  30568. delTr.forEach(function (deletedT) {
  30569. if (uniqueArray.indexOf(deletedT) === -1) {
  30570. deletedT.deletePending = true;
  30571. uniqueArray.push(deletedT);
  30572. }
  30573. });
  30574. if (uniqueArray.length % 2 != 0) {
  30575. continue;
  30576. }
  30577. v0.q = v1.q.add(v0.q);
  30578. v0.updatePosition(p);
  30579. var tStart = _this.references.length;
  30580. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30581. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30582. var tCount = _this.references.length - tStart;
  30583. if (tCount <= v0.triangleCount) {
  30584. if (tCount) {
  30585. for (var c = 0; c < tCount; c++) {
  30586. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30587. }
  30588. }
  30589. }
  30590. else {
  30591. v0.triangleStart = tStart;
  30592. }
  30593. v0.triangleCount = tCount;
  30594. break;
  30595. }
  30596. }
  30597. };
  30598. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30599. }, 0);
  30600. };
  30601. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30602. if (triangleCount - deletedTriangles <= targetCount)
  30603. loop.breakLoop();
  30604. else {
  30605. iterationFunction(loop.index, function () {
  30606. loop.executeNext();
  30607. });
  30608. }
  30609. }, function () {
  30610. setTimeout(function () {
  30611. //reconstruct this part of the mesh
  30612. _this.reconstructMesh(submeshIndex);
  30613. successCallback();
  30614. }, 0);
  30615. });
  30616. };
  30617. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30618. var _this = this;
  30619. this.vertices = [];
  30620. this.triangles = [];
  30621. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30622. var indices = this._mesh.getIndices();
  30623. var submesh = this._mesh.subMeshes[submeshIndex];
  30624. var findInVertices = function (positionToSearch) {
  30625. if (optimizeMesh) {
  30626. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30627. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30628. return _this.vertices[ii];
  30629. }
  30630. }
  30631. }
  30632. return null;
  30633. };
  30634. var vertexReferences = [];
  30635. var vertexInit = function (i) {
  30636. var offset = i + submesh.verticesStart;
  30637. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30638. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30639. vertex.originalOffsets.push(offset);
  30640. if (vertex.id == _this.vertices.length) {
  30641. _this.vertices.push(vertex);
  30642. }
  30643. vertexReferences.push(vertex.id);
  30644. };
  30645. //var totalVertices = mesh.getTotalVertices();
  30646. var totalVertices = submesh.verticesCount;
  30647. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30648. var indicesInit = function (i) {
  30649. var offset = (submesh.indexStart / 3) + i;
  30650. var pos = (offset * 3);
  30651. var i0 = indices[pos + 0];
  30652. var i1 = indices[pos + 1];
  30653. var i2 = indices[pos + 2];
  30654. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30655. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30656. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30657. var triangle = new DecimationTriangle([v0, v1, v2]);
  30658. triangle.originalOffset = pos;
  30659. _this.triangles.push(triangle);
  30660. };
  30661. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30662. _this.init(callback);
  30663. });
  30664. });
  30665. };
  30666. QuadraticErrorSimplification.prototype.init = function (callback) {
  30667. var _this = this;
  30668. var triangleInit1 = function (i) {
  30669. var t = _this.triangles[i];
  30670. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30671. for (var j = 0; j < 3; j++) {
  30672. 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))));
  30673. }
  30674. };
  30675. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30676. var triangleInit2 = function (i) {
  30677. var t = _this.triangles[i];
  30678. for (var j = 0; j < 3; ++j) {
  30679. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30680. }
  30681. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30682. };
  30683. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30684. _this.initialized = true;
  30685. callback();
  30686. });
  30687. });
  30688. };
  30689. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30690. var newTriangles = [];
  30691. var i;
  30692. for (i = 0; i < this.vertices.length; ++i) {
  30693. this.vertices[i].triangleCount = 0;
  30694. }
  30695. var t;
  30696. var j;
  30697. for (i = 0; i < this.triangles.length; ++i) {
  30698. if (!this.triangles[i].deleted) {
  30699. t = this.triangles[i];
  30700. for (j = 0; j < 3; ++j) {
  30701. t.vertices[j].triangleCount = 1;
  30702. }
  30703. newTriangles.push(t);
  30704. }
  30705. }
  30706. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30707. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30708. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30709. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30710. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30711. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30712. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30713. var vertexCount = 0;
  30714. for (i = 0; i < this.vertices.length; ++i) {
  30715. var vertex = this.vertices[i];
  30716. vertex.id = vertexCount;
  30717. if (vertex.triangleCount) {
  30718. vertex.originalOffsets.forEach(function (originalOffset) {
  30719. newPositionData.push(vertex.position.x);
  30720. newPositionData.push(vertex.position.y);
  30721. newPositionData.push(vertex.position.z);
  30722. newNormalData.push(normalData[originalOffset * 3]);
  30723. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30724. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30725. if (uvs && uvs.length) {
  30726. newUVsData.push(uvs[(originalOffset * 2)]);
  30727. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30728. }
  30729. else if (colorsData && colorsData.length) {
  30730. newColorsData.push(colorsData[(originalOffset * 4)]);
  30731. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30732. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30733. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30734. }
  30735. ++vertexCount;
  30736. });
  30737. }
  30738. }
  30739. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30740. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30741. var submeshesArray = this._reconstructedMesh.subMeshes;
  30742. this._reconstructedMesh.subMeshes = [];
  30743. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30744. var originalIndices = this._mesh.getIndices();
  30745. for (i = 0; i < newTriangles.length; ++i) {
  30746. var t = newTriangles[i];
  30747. //now get the new referencing point for each vertex
  30748. [0, 1, 2].forEach(function (idx) {
  30749. var id = originalIndices[t.originalOffset + idx];
  30750. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30751. if (offset < 0)
  30752. offset = 0;
  30753. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30754. });
  30755. }
  30756. //overwriting the old vertex buffers and indices.
  30757. this._reconstructedMesh.setIndices(newIndicesArray);
  30758. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30760. if (newUVsData.length > 0)
  30761. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30762. if (newColorsData.length > 0)
  30763. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30764. //create submesh
  30765. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30766. if (submeshIndex > 0) {
  30767. this._reconstructedMesh.subMeshes = [];
  30768. submeshesArray.forEach(function (submesh) {
  30769. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30770. });
  30771. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30772. }
  30773. };
  30774. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30775. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30776. this._reconstructedMesh.material = this._mesh.material;
  30777. this._reconstructedMesh.parent = this._mesh.parent;
  30778. this._reconstructedMesh.isVisible = false;
  30779. };
  30780. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30781. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30782. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30783. if (t.deleted)
  30784. continue;
  30785. var s = this.references[vertex1.triangleStart + i].vertexId;
  30786. var v1 = t.vertices[(s + 1) % 3];
  30787. var v2 = t.vertices[(s + 2) % 3];
  30788. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30789. deletedArray[i] = true;
  30790. delTr.push(t);
  30791. continue;
  30792. }
  30793. var d1 = v1.position.subtract(point);
  30794. d1 = d1.normalize();
  30795. var d2 = v2.position.subtract(point);
  30796. d2 = d2.normalize();
  30797. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30798. return true;
  30799. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30800. deletedArray[i] = false;
  30801. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30802. return true;
  30803. }
  30804. return false;
  30805. };
  30806. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30807. var newDeleted = deletedTriangles;
  30808. for (var i = 0; i < vertex.triangleCount; ++i) {
  30809. var ref = this.references[vertex.triangleStart + i];
  30810. var t = this.triangles[ref.triangleId];
  30811. if (t.deleted)
  30812. continue;
  30813. if (deletedArray[i] && t.deletePending) {
  30814. t.deleted = true;
  30815. newDeleted++;
  30816. continue;
  30817. }
  30818. t.vertices[ref.vertexId] = origVertex;
  30819. t.isDirty = true;
  30820. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30821. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30822. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30823. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30824. this.references.push(ref);
  30825. }
  30826. return newDeleted;
  30827. };
  30828. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30829. for (var i = 0; i < this.vertices.length; ++i) {
  30830. var vCount = [];
  30831. var vId = [];
  30832. var v = this.vertices[i];
  30833. var j;
  30834. for (j = 0; j < v.triangleCount; ++j) {
  30835. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30836. for (var ii = 0; ii < 3; ii++) {
  30837. var ofs = 0;
  30838. var vv = triangle.vertices[ii];
  30839. while (ofs < vCount.length) {
  30840. if (vId[ofs] === vv.id)
  30841. break;
  30842. ++ofs;
  30843. }
  30844. if (ofs === vCount.length) {
  30845. vCount.push(1);
  30846. vId.push(vv.id);
  30847. }
  30848. else {
  30849. vCount[ofs]++;
  30850. }
  30851. }
  30852. }
  30853. for (j = 0; j < vCount.length; ++j) {
  30854. if (vCount[j] === 1) {
  30855. this.vertices[vId[j]].isBorder = true;
  30856. }
  30857. else {
  30858. this.vertices[vId[j]].isBorder = false;
  30859. }
  30860. }
  30861. }
  30862. };
  30863. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30864. if (identifyBorders === void 0) { identifyBorders = false; }
  30865. var i;
  30866. if (!identifyBorders) {
  30867. var newTrianglesVector = [];
  30868. for (i = 0; i < this.triangles.length; ++i) {
  30869. if (!this.triangles[i].deleted) {
  30870. newTrianglesVector.push(this.triangles[i]);
  30871. }
  30872. }
  30873. this.triangles = newTrianglesVector;
  30874. }
  30875. for (i = 0; i < this.vertices.length; ++i) {
  30876. this.vertices[i].triangleCount = 0;
  30877. this.vertices[i].triangleStart = 0;
  30878. }
  30879. var t;
  30880. var j;
  30881. var v;
  30882. for (i = 0; i < this.triangles.length; ++i) {
  30883. t = this.triangles[i];
  30884. for (j = 0; j < 3; ++j) {
  30885. v = t.vertices[j];
  30886. v.triangleCount++;
  30887. }
  30888. }
  30889. var tStart = 0;
  30890. for (i = 0; i < this.vertices.length; ++i) {
  30891. this.vertices[i].triangleStart = tStart;
  30892. tStart += this.vertices[i].triangleCount;
  30893. this.vertices[i].triangleCount = 0;
  30894. }
  30895. var newReferences = new Array(this.triangles.length * 3);
  30896. for (i = 0; i < this.triangles.length; ++i) {
  30897. t = this.triangles[i];
  30898. for (j = 0; j < 3; ++j) {
  30899. v = t.vertices[j];
  30900. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30901. v.triangleCount++;
  30902. }
  30903. }
  30904. this.references = newReferences;
  30905. if (identifyBorders) {
  30906. this.identifyBorder();
  30907. }
  30908. };
  30909. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30910. var x = point.x;
  30911. var y = point.y;
  30912. var z = point.z;
  30913. 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
  30914. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30915. };
  30916. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30917. var q = vertex1.q.add(vertex2.q);
  30918. var border = vertex1.isBorder && vertex2.isBorder;
  30919. var error = 0;
  30920. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30921. if (qDet !== 0 && !border) {
  30922. if (!pointResult) {
  30923. pointResult = BABYLON.Vector3.Zero();
  30924. }
  30925. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30926. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30927. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30928. error = this.vertexError(q, pointResult);
  30929. }
  30930. else {
  30931. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30932. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30933. var error1 = this.vertexError(q, vertex1.position);
  30934. var error2 = this.vertexError(q, vertex2.position);
  30935. var error3 = this.vertexError(q, p3);
  30936. error = Math.min(error1, error2, error3);
  30937. if (error === error1) {
  30938. if (pointResult) {
  30939. pointResult.copyFrom(vertex1.position);
  30940. }
  30941. }
  30942. else if (error === error2) {
  30943. if (pointResult) {
  30944. pointResult.copyFrom(vertex2.position);
  30945. }
  30946. }
  30947. else {
  30948. if (pointResult) {
  30949. pointResult.copyFrom(p3);
  30950. }
  30951. }
  30952. }
  30953. return error;
  30954. };
  30955. return QuadraticErrorSimplification;
  30956. })();
  30957. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30958. })(BABYLON || (BABYLON = {}));
  30959. //# sourceMappingURL=babylon.meshSimplification.js.map
  30960. var BABYLON;
  30961. (function (BABYLON) {
  30962. var Analyser = (function () {
  30963. function Analyser(scene) {
  30964. this.SMOOTHING = 0.75;
  30965. this.FFT_SIZE = 512;
  30966. this.BARGRAPHAMPLITUDE = 256;
  30967. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30968. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30969. this._scene = scene;
  30970. this._audioEngine = BABYLON.Engine.audioEngine;
  30971. if (this._audioEngine.canUseWebAudio) {
  30972. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30973. this._webAudioAnalyser.minDecibels = -140;
  30974. this._webAudioAnalyser.maxDecibels = 0;
  30975. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30976. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30977. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30978. }
  30979. }
  30980. Analyser.prototype.getFrequencyBinCount = function () {
  30981. if (this._audioEngine.canUseWebAudio) {
  30982. return this._webAudioAnalyser.frequencyBinCount;
  30983. }
  30984. else {
  30985. return 0;
  30986. }
  30987. };
  30988. Analyser.prototype.getByteFrequencyData = function () {
  30989. if (this._audioEngine.canUseWebAudio) {
  30990. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30991. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30992. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30993. }
  30994. return this._byteFreqs;
  30995. };
  30996. Analyser.prototype.getByteTimeDomainData = function () {
  30997. if (this._audioEngine.canUseWebAudio) {
  30998. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30999. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31000. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31001. }
  31002. return this._byteTime;
  31003. };
  31004. Analyser.prototype.getFloatFrequencyData = function () {
  31005. if (this._audioEngine.canUseWebAudio) {
  31006. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31007. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31008. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31009. }
  31010. return this._floatFreqs;
  31011. };
  31012. Analyser.prototype.drawDebugCanvas = function () {
  31013. var _this = this;
  31014. if (this._audioEngine.canUseWebAudio) {
  31015. if (!this._debugCanvas) {
  31016. this._debugCanvas = document.createElement("canvas");
  31017. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31018. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31019. this._debugCanvas.style.position = "absolute";
  31020. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31021. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31022. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31023. document.body.appendChild(this._debugCanvas);
  31024. this._registerFunc = function () {
  31025. _this.drawDebugCanvas();
  31026. };
  31027. this._scene.registerBeforeRender(this._registerFunc);
  31028. }
  31029. if (this._registerFunc) {
  31030. var workingArray = this.getByteFrequencyData();
  31031. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31032. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31033. // Draw the frequency domain chart.
  31034. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31035. var value = workingArray[i];
  31036. var percent = value / this.BARGRAPHAMPLITUDE;
  31037. var height = this.DEBUGCANVASSIZE.height * percent;
  31038. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31039. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31040. var hue = i / this.getFrequencyBinCount() * 360;
  31041. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31042. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31043. }
  31044. }
  31045. }
  31046. };
  31047. Analyser.prototype.stopDebugCanvas = function () {
  31048. if (this._debugCanvas) {
  31049. this._scene.unregisterBeforeRender(this._registerFunc);
  31050. this._registerFunc = null;
  31051. document.body.removeChild(this._debugCanvas);
  31052. this._debugCanvas = null;
  31053. this._debugCanvasContext = null;
  31054. }
  31055. };
  31056. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31057. if (this._audioEngine.canUseWebAudio) {
  31058. inputAudioNode.connect(this._webAudioAnalyser);
  31059. this._webAudioAnalyser.connect(outputAudioNode);
  31060. }
  31061. };
  31062. Analyser.prototype.dispose = function () {
  31063. if (this._audioEngine.canUseWebAudio) {
  31064. this._webAudioAnalyser.disconnect();
  31065. }
  31066. };
  31067. return Analyser;
  31068. })();
  31069. BABYLON.Analyser = Analyser;
  31070. })(BABYLON || (BABYLON = {}));
  31071. //# sourceMappingURL=babylon.analyser.js.map
  31072. var BABYLON;
  31073. (function (BABYLON) {
  31074. var DepthRenderer = (function () {
  31075. function DepthRenderer(scene, type) {
  31076. var _this = this;
  31077. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31078. this._viewMatrix = BABYLON.Matrix.Zero();
  31079. this._projectionMatrix = BABYLON.Matrix.Zero();
  31080. this._transformMatrix = BABYLON.Matrix.Zero();
  31081. this._worldViewProjection = BABYLON.Matrix.Zero();
  31082. this._scene = scene;
  31083. var engine = scene.getEngine();
  31084. // Render target
  31085. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31086. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31087. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31088. this._depthMap.refreshRate = 1;
  31089. this._depthMap.renderParticles = false;
  31090. this._depthMap.renderList = null;
  31091. // set default depth value to 1.0 (far away)
  31092. this._depthMap.onClear = function (engine) {
  31093. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31094. };
  31095. // Custom render function
  31096. var renderSubMesh = function (subMesh) {
  31097. var mesh = subMesh.getRenderingMesh();
  31098. var scene = _this._scene;
  31099. var engine = scene.getEngine();
  31100. // Culling
  31101. engine.setState(subMesh.getMaterial().backFaceCulling);
  31102. // Managing instances
  31103. var batch = mesh._getInstancesRenderList(subMesh._id);
  31104. if (batch.mustReturn) {
  31105. return;
  31106. }
  31107. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31108. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31109. engine.enableEffect(_this._effect);
  31110. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31111. var material = subMesh.getMaterial();
  31112. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31113. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31114. // Alpha test
  31115. if (material && material.needAlphaTesting()) {
  31116. var alphaTexture = material.getAlphaTestTexture();
  31117. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31118. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31119. }
  31120. // Bones
  31121. if (mesh.useBones) {
  31122. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31123. }
  31124. // Draw
  31125. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31126. }
  31127. };
  31128. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31129. var index;
  31130. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31131. renderSubMesh(opaqueSubMeshes.data[index]);
  31132. }
  31133. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31134. renderSubMesh(alphaTestSubMeshes.data[index]);
  31135. }
  31136. };
  31137. }
  31138. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31139. var defines = [];
  31140. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31141. var mesh = subMesh.getMesh();
  31142. var scene = mesh.getScene();
  31143. var material = subMesh.getMaterial();
  31144. // Alpha test
  31145. if (material && material.needAlphaTesting()) {
  31146. defines.push("#define ALPHATEST");
  31147. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31148. attribs.push(BABYLON.VertexBuffer.UVKind);
  31149. defines.push("#define UV1");
  31150. }
  31151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31152. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31153. defines.push("#define UV2");
  31154. }
  31155. }
  31156. // Bones
  31157. if (mesh.useBones) {
  31158. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31159. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31160. defines.push("#define BONES");
  31161. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31162. }
  31163. // Instances
  31164. if (useInstances) {
  31165. defines.push("#define INSTANCES");
  31166. attribs.push("world0");
  31167. attribs.push("world1");
  31168. attribs.push("world2");
  31169. attribs.push("world3");
  31170. }
  31171. // Get correct effect
  31172. var join = defines.join("\n");
  31173. if (this._cachedDefines !== join) {
  31174. this._cachedDefines = join;
  31175. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31176. }
  31177. return this._effect.isReady();
  31178. };
  31179. DepthRenderer.prototype.getDepthMap = function () {
  31180. return this._depthMap;
  31181. };
  31182. // Methods
  31183. DepthRenderer.prototype.dispose = function () {
  31184. this._depthMap.dispose();
  31185. };
  31186. return DepthRenderer;
  31187. })();
  31188. BABYLON.DepthRenderer = DepthRenderer;
  31189. })(BABYLON || (BABYLON = {}));
  31190. //# sourceMappingURL=babylon.depthRenderer.js.map
  31191. var __extends = this.__extends || function (d, b) {
  31192. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31193. function __() { this.constructor = d; }
  31194. __.prototype = b.prototype;
  31195. d.prototype = new __();
  31196. };
  31197. var BABYLON;
  31198. (function (BABYLON) {
  31199. var SSAORenderingPipeline = (function (_super) {
  31200. __extends(SSAORenderingPipeline, _super);
  31201. /**
  31202. * @constructor
  31203. * @param {string} name - The rendering pipeline name
  31204. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31205. * @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 }
  31206. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31207. */
  31208. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31209. var _this = this;
  31210. _super.call(this, scene.getEngine(), name);
  31211. // Members
  31212. /**
  31213. * The PassPostProcess id in the pipeline that contains the original scene color
  31214. * @type {string}
  31215. */
  31216. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31217. /**
  31218. * The SSAO PostProcess id in the pipeline
  31219. * @type {string}
  31220. */
  31221. this.SSAORenderEffect = "SSAORenderEffect";
  31222. /**
  31223. * The horizontal blur PostProcess id in the pipeline
  31224. * @type {string}
  31225. */
  31226. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31227. /**
  31228. * The vertical blur PostProcess id in the pipeline
  31229. * @type {string}
  31230. */
  31231. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31232. /**
  31233. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31234. * @type {string}
  31235. */
  31236. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31237. /**
  31238. * The output strength of the SSAO post-process. Default value is 1.0.
  31239. * @type {number}
  31240. */
  31241. this.totalStrength = 1.0;
  31242. /**
  31243. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31244. * @type {number}
  31245. */
  31246. this.radius = 0.0002;
  31247. /**
  31248. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31249. * Must not be equal to fallOff and superior to fallOff.
  31250. * Default value is 0.0075
  31251. * @type {number}
  31252. */
  31253. this.area = 0.0075;
  31254. /**
  31255. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31256. * Must not be equal to area and inferior to area.
  31257. * Default value is 0.0002
  31258. * @type {number}
  31259. */
  31260. this.fallOff = 0.0002;
  31261. this._firstUpdate = true;
  31262. this._scene = scene;
  31263. // Set up assets
  31264. this._createRandomTexture();
  31265. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31266. var ssaoRatio = ratio.ssaoRatio || ratio;
  31267. var combineRatio = ratio.combineRatio || ratio;
  31268. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31269. this._createSSAOPostProcess(ssaoRatio);
  31270. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31271. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31272. this._createSSAOCombinePostProcess(combineRatio);
  31273. // Set up pipeline
  31274. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31279. // Finish
  31280. scene.postProcessRenderPipelineManager.addPipeline(this);
  31281. if (cameras)
  31282. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31283. }
  31284. // Public Methods
  31285. /**
  31286. * Returns the horizontal blur PostProcess
  31287. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31288. */
  31289. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31290. return this._blurHPostProcess;
  31291. };
  31292. /**
  31293. * Returns the vertical blur PostProcess
  31294. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31295. */
  31296. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31297. return this._blurVPostProcess;
  31298. };
  31299. /**
  31300. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31301. */
  31302. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31303. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31304. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31305. this._originalColorPostProcess = undefined;
  31306. this._ssaoPostProcess = undefined;
  31307. this._blurHPostProcess = undefined;
  31308. this._blurVPostProcess = undefined;
  31309. this._ssaoCombinePostProcess = undefined;
  31310. this._randomTexture.dispose();
  31311. if (disableDepthRender)
  31312. this._scene.disableDepthRenderer();
  31313. };
  31314. // Private Methods
  31315. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31316. var _this = this;
  31317. var sampleSphere = [
  31318. 0.5381, 0.1856, -0.4319,
  31319. 0.1379, 0.2486, 0.4430,
  31320. 0.3371, 0.5679, -0.0057,
  31321. -0.6999, -0.0451, -0.0019,
  31322. 0.0689, -0.1598, -0.8547,
  31323. 0.0560, 0.0069, -0.1843,
  31324. -0.0146, 0.1402, 0.0762,
  31325. 0.0100, -0.1924, -0.0344,
  31326. -0.3577, -0.5301, -0.4358,
  31327. -0.3169, 0.1063, 0.0158,
  31328. 0.0103, -0.5869, 0.0046,
  31329. -0.0897, -0.4940, 0.3287,
  31330. 0.7119, -0.0154, -0.0918,
  31331. -0.0533, 0.0596, -0.5411,
  31332. 0.0352, -0.0631, 0.5460,
  31333. -0.4776, 0.2847, -0.0271
  31334. ];
  31335. var samplesFactor = 1.0 / 16.0;
  31336. 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);
  31337. this._ssaoPostProcess.onApply = function (effect) {
  31338. if (_this._firstUpdate) {
  31339. effect.setArray3("sampleSphere", sampleSphere);
  31340. effect.setFloat("samplesFactor", samplesFactor);
  31341. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31342. _this._firstUpdate = false;
  31343. }
  31344. effect.setFloat("totalStrength", _this.totalStrength);
  31345. effect.setFloat("radius", _this.radius);
  31346. effect.setFloat("area", _this.area);
  31347. effect.setFloat("fallOff", _this.fallOff);
  31348. effect.setTexture("textureSampler", _this._depthTexture);
  31349. effect.setTexture("randomSampler", _this._randomTexture);
  31350. };
  31351. };
  31352. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31353. var _this = this;
  31354. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31355. this._ssaoCombinePostProcess.onApply = function (effect) {
  31356. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31357. };
  31358. };
  31359. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31360. var size = 512;
  31361. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31362. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31363. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31364. var context = this._randomTexture.getContext();
  31365. var rand = function (min, max) {
  31366. return Math.random() * (max - min) + min;
  31367. };
  31368. for (var x = 0; x < size; x++) {
  31369. for (var y = 0; y < size; y++) {
  31370. var randVector = BABYLON.Vector3.Zero();
  31371. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31372. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31373. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31374. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31375. context.fillRect(x, y, 1, 1);
  31376. }
  31377. }
  31378. this._randomTexture.update(false);
  31379. };
  31380. return SSAORenderingPipeline;
  31381. })(BABYLON.PostProcessRenderPipeline);
  31382. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31383. })(BABYLON || (BABYLON = {}));
  31384. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31385. var __extends = this.__extends || function (d, b) {
  31386. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31387. function __() { this.constructor = d; }
  31388. __.prototype = b.prototype;
  31389. d.prototype = new __();
  31390. };
  31391. var BABYLON;
  31392. (function (BABYLON) {
  31393. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31394. var VolumetricLightScatteringPostProcess = (function (_super) {
  31395. __extends(VolumetricLightScatteringPostProcess, _super);
  31396. /**
  31397. * @constructor
  31398. * @param {string} name - The post-process name
  31399. * @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)
  31400. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31401. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31402. * @param {number} samples - The post-process quality, default 100
  31403. * @param {number} samplingMode - The post-process filtering mode
  31404. * @param {BABYLON.Engine} engine - The babylon engine
  31405. * @param {boolean} reusable - If the post-process is reusable
  31406. */
  31407. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31408. var _this = this;
  31409. if (samples === void 0) { samples = 100; }
  31410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31411. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31412. this._screenCoordinates = BABYLON.Vector2.Zero();
  31413. /**
  31414. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31415. * @type {boolean}
  31416. */
  31417. this.useCustomMeshPosition = false;
  31418. /**
  31419. * If the post-process should inverse the light scattering direction
  31420. * @type {boolean}
  31421. */
  31422. this.invert = true;
  31423. /**
  31424. * Array containing the excluded meshes not rendered in the internal pass
  31425. */
  31426. this.excludedMeshes = new Array();
  31427. this.exposure = 0.3;
  31428. this.decay = 0.96815;
  31429. this.weight = 0.58767;
  31430. this.density = 0.926;
  31431. var scene = camera.getScene();
  31432. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31433. // Configure mesh
  31434. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31435. // Configure
  31436. this._createPass(scene, ratio.passRatio || ratio);
  31437. this.onApply = function (effect) {
  31438. _this._updateMeshScreenCoordinates(scene);
  31439. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31440. effect.setFloat("exposure", _this.exposure);
  31441. effect.setFloat("decay", _this.decay);
  31442. effect.setFloat("weight", _this.weight);
  31443. effect.setFloat("density", _this.density);
  31444. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31445. };
  31446. }
  31447. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31448. var mesh = subMesh.getMesh();
  31449. var defines = [];
  31450. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31451. var material = subMesh.getMaterial();
  31452. var needUV = false;
  31453. // Render this.mesh as default
  31454. if (mesh === this.mesh) {
  31455. defines.push("#define BASIC_RENDER");
  31456. defines.push("#define NEED_UV");
  31457. needUV = true;
  31458. }
  31459. // Alpha test
  31460. if (material) {
  31461. if (material.needAlphaTesting() || mesh === this.mesh)
  31462. defines.push("#define ALPHATEST");
  31463. if (material.opacityTexture !== undefined) {
  31464. defines.push("#define OPACITY");
  31465. if (material.opacityTexture.getAlphaFromRGB)
  31466. defines.push("#define OPACITYRGB");
  31467. if (!needUV)
  31468. defines.push("#define NEED_UV");
  31469. }
  31470. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31471. attribs.push(BABYLON.VertexBuffer.UVKind);
  31472. defines.push("#define UV1");
  31473. }
  31474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31475. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31476. defines.push("#define UV2");
  31477. }
  31478. }
  31479. // Bones
  31480. if (mesh.useBones) {
  31481. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31482. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31483. defines.push("#define BONES");
  31484. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31485. }
  31486. // Instances
  31487. if (useInstances) {
  31488. defines.push("#define INSTANCES");
  31489. attribs.push("world0");
  31490. attribs.push("world1");
  31491. attribs.push("world2");
  31492. attribs.push("world3");
  31493. }
  31494. // Get correct effect
  31495. var join = defines.join("\n");
  31496. if (this._cachedDefines !== join) {
  31497. this._cachedDefines = join;
  31498. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31499. }
  31500. return this._volumetricLightScatteringPass.isReady();
  31501. };
  31502. /**
  31503. * Sets the new light position for light scattering effect
  31504. * @param {BABYLON.Vector3} The new custom light position
  31505. */
  31506. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31507. this._customMeshPosition = position;
  31508. };
  31509. /**
  31510. * Returns the light position for light scattering effect
  31511. * @return {BABYLON.Vector3} The custom light position
  31512. */
  31513. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31514. return this._customMeshPosition;
  31515. };
  31516. /**
  31517. * Disposes the internal assets and detaches the post-process from the camera
  31518. */
  31519. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31520. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31521. if (rttIndex !== -1) {
  31522. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31523. }
  31524. this._volumetricLightScatteringRTT.dispose();
  31525. _super.prototype.dispose.call(this, camera);
  31526. };
  31527. /**
  31528. * Returns the render target texture used by the post-process
  31529. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31530. */
  31531. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31532. return this._volumetricLightScatteringRTT;
  31533. };
  31534. // Private methods
  31535. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31536. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31537. return true;
  31538. }
  31539. return false;
  31540. };
  31541. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31542. var _this = this;
  31543. var engine = scene.getEngine();
  31544. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31545. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31546. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31547. this._volumetricLightScatteringRTT.renderList = null;
  31548. this._volumetricLightScatteringRTT.renderParticles = false;
  31549. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31550. // Custom render function for submeshes
  31551. var renderSubMesh = function (subMesh) {
  31552. var mesh = subMesh.getRenderingMesh();
  31553. if (_this._meshExcluded(mesh)) {
  31554. return;
  31555. }
  31556. var scene = mesh.getScene();
  31557. var engine = scene.getEngine();
  31558. // Culling
  31559. engine.setState(subMesh.getMaterial().backFaceCulling);
  31560. // Managing instances
  31561. var batch = mesh._getInstancesRenderList(subMesh._id);
  31562. if (batch.mustReturn) {
  31563. return;
  31564. }
  31565. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31566. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31567. engine.enableEffect(_this._volumetricLightScatteringPass);
  31568. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31569. var material = subMesh.getMaterial();
  31570. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31571. // Alpha test
  31572. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31573. var alphaTexture = material.getAlphaTestTexture();
  31574. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31575. if (alphaTexture) {
  31576. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31577. }
  31578. if (material.opacityTexture !== undefined) {
  31579. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31580. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31581. }
  31582. }
  31583. // Bones
  31584. if (mesh.useBones) {
  31585. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31586. }
  31587. // Draw
  31588. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31589. }
  31590. };
  31591. // Render target texture callbacks
  31592. var savedSceneClearColor;
  31593. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31594. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31595. savedSceneClearColor = scene.clearColor;
  31596. scene.clearColor = sceneClearColor;
  31597. };
  31598. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31599. scene.clearColor = savedSceneClearColor;
  31600. };
  31601. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31602. var engine = scene.getEngine();
  31603. var index;
  31604. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31605. renderSubMesh(opaqueSubMeshes.data[index]);
  31606. }
  31607. engine.setAlphaTesting(true);
  31608. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31609. renderSubMesh(alphaTestSubMeshes.data[index]);
  31610. }
  31611. engine.setAlphaTesting(false);
  31612. if (transparentSubMeshes.length) {
  31613. // Sort sub meshes
  31614. for (index = 0; index < transparentSubMeshes.length; index++) {
  31615. var submesh = transparentSubMeshes.data[index];
  31616. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31617. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31618. }
  31619. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31620. sortedArray.sort(function (a, b) {
  31621. // Alpha index first
  31622. if (a._alphaIndex > b._alphaIndex) {
  31623. return 1;
  31624. }
  31625. if (a._alphaIndex < b._alphaIndex) {
  31626. return -1;
  31627. }
  31628. // Then distance to camera
  31629. if (a._distanceToCamera < b._distanceToCamera) {
  31630. return 1;
  31631. }
  31632. if (a._distanceToCamera > b._distanceToCamera) {
  31633. return -1;
  31634. }
  31635. return 0;
  31636. });
  31637. // Render sub meshes
  31638. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31639. for (index = 0; index < sortedArray.length; index++) {
  31640. renderSubMesh(sortedArray[index]);
  31641. }
  31642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31643. }
  31644. };
  31645. };
  31646. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31647. var transform = scene.getTransformMatrix();
  31648. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31649. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31650. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31651. if (this.invert)
  31652. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31653. };
  31654. // Static methods
  31655. /**
  31656. * Creates a default mesh for the Volumeric Light Scattering post-process
  31657. * @param {string} The mesh name
  31658. * @param {BABYLON.Scene} The scene where to create the mesh
  31659. * @return {BABYLON.Mesh} the default mesh
  31660. */
  31661. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31662. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31663. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31664. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31665. return mesh;
  31666. };
  31667. return VolumetricLightScatteringPostProcess;
  31668. })(BABYLON.PostProcess);
  31669. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31670. })(BABYLON || (BABYLON = {}));
  31671. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31672. var __extends = this.__extends || function (d, b) {
  31673. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31674. function __() { this.constructor = d; }
  31675. __.prototype = b.prototype;
  31676. d.prototype = new __();
  31677. };
  31678. var BABYLON;
  31679. (function (BABYLON) {
  31680. var LensRenderingPipeline = (function (_super) {
  31681. __extends(LensRenderingPipeline, _super);
  31682. /**
  31683. * @constructor
  31684. *
  31685. * Effect parameters are as follow:
  31686. * {
  31687. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31688. * edge_blur: number; // from 0 to x (1 for realism)
  31689. * distortion: number; // from 0 to x (1 for realism)
  31690. * grain_amount: number; // from 0 to 1
  31691. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31692. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31693. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31694. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31695. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31696. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31697. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31698. * }
  31699. * Note: if an effect parameter is unset, effect is disabled
  31700. *
  31701. * @param {string} name - The rendering pipeline name
  31702. * @param {object} parameters - An object containing all parameters (see above)
  31703. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31704. * @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)
  31705. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31706. */
  31707. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31708. var _this = this;
  31709. if (ratio === void 0) { ratio = 1.0; }
  31710. _super.call(this, scene.getEngine(), name);
  31711. // Lens effects can be of the following:
  31712. // - chromatic aberration (slight shift of RGB colors)
  31713. // - blur on the edge of the lens
  31714. // - lens distortion
  31715. // - depth-of-field blur & highlights enhancing
  31716. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31717. // - grain effect (noise or custom texture)
  31718. // Two additional texture samplers are needed:
  31719. // - depth map (for depth-of-field)
  31720. // - grain texture
  31721. /**
  31722. * The chromatic aberration PostProcess id in the pipeline
  31723. * @type {string}
  31724. */
  31725. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31726. /**
  31727. * The highlights enhancing PostProcess id in the pipeline
  31728. * @type {string}
  31729. */
  31730. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31731. /**
  31732. * The depth-of-field PostProcess id in the pipeline
  31733. * @type {string}
  31734. */
  31735. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31736. this._scene = scene;
  31737. // Fetch texture samplers
  31738. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31739. if (parameters.grain_texture) {
  31740. this._grainTexture = parameters.grain_texture;
  31741. }
  31742. else {
  31743. this._createGrainTexture();
  31744. }
  31745. // save parameters
  31746. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31747. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31748. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31749. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31750. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31751. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31752. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31753. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31754. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31755. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31756. // Create effects
  31757. this._createChromaticAberrationPostProcess(ratio);
  31758. this._createHighlightsPostProcess(ratio);
  31759. this._createDepthOfFieldPostProcess(ratio);
  31760. // Set up pipeline
  31761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31764. if (this._highlightsGain == -1) {
  31765. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31766. }
  31767. // Finish
  31768. scene.postProcessRenderPipelineManager.addPipeline(this);
  31769. if (cameras) {
  31770. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31771. }
  31772. }
  31773. // public methods (self explanatory)
  31774. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31775. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31776. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31777. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31778. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31779. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31780. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31781. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31782. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31783. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31784. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31785. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31786. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31787. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31788. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31789. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31790. this._highlightsGain = amount;
  31791. };
  31792. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31793. if (this._highlightsGain == -1) {
  31794. this._highlightsGain = 1.0;
  31795. }
  31796. this._highlightsThreshold = amount;
  31797. };
  31798. LensRenderingPipeline.prototype.disableHighlights = function () {
  31799. this._highlightsGain = -1;
  31800. };
  31801. /**
  31802. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31803. */
  31804. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31805. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31806. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31807. this._chromaticAberrationPostProcess = undefined;
  31808. this._highlightsPostProcess = undefined;
  31809. this._depthOfFieldPostProcess = undefined;
  31810. this._grainTexture.dispose();
  31811. if (disableDepthRender)
  31812. this._scene.disableDepthRenderer();
  31813. };
  31814. // colors shifting and distortion
  31815. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31816. var _this = this;
  31817. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31818. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31819. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31820. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31821. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31822. };
  31823. };
  31824. // highlights enhancing
  31825. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31826. var _this = this;
  31827. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31828. this._highlightsPostProcess.onApply = function (effect) {
  31829. effect.setFloat('gain', _this._highlightsGain);
  31830. effect.setFloat('threshold', _this._highlightsThreshold);
  31831. effect.setBool('pentagon', _this._dofPentagon);
  31832. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31833. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31834. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31835. };
  31836. };
  31837. // colors shifting and distortion
  31838. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31839. var _this = this;
  31840. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31841. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31842. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31843. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31844. this._depthOfFieldPostProcess.onApply = function (effect) {
  31845. effect.setBool('blur_noise', _this._blurNoise);
  31846. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31847. effect.setFloat('grain_amount', _this._grainAmount);
  31848. effect.setTexture("depthSampler", _this._depthTexture);
  31849. effect.setTexture("grainSampler", _this._grainTexture);
  31850. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31851. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31852. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31853. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31854. effect.setFloat('distortion', _this._distortion);
  31855. effect.setFloat('focus_depth', _this._dofDepth);
  31856. effect.setFloat('aperture', _this._dofAperture);
  31857. effect.setFloat('edge_blur', _this._edgeBlur);
  31858. effect.setBool('highlights', (_this._highlightsGain != -1));
  31859. };
  31860. };
  31861. // creates a black and white random noise texture, 512x512
  31862. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31863. var size = 512;
  31864. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31865. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31866. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31867. var context = this._grainTexture.getContext();
  31868. var rand = function (min, max) {
  31869. return Math.random() * (max - min) + min;
  31870. };
  31871. var value;
  31872. for (var x = 0; x < size; x++) {
  31873. for (var y = 0; y < size; y++) {
  31874. value = Math.floor(rand(0.42, 0.58) * 255);
  31875. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31876. context.fillRect(x, y, 1, 1);
  31877. }
  31878. }
  31879. this._grainTexture.update(false);
  31880. };
  31881. return LensRenderingPipeline;
  31882. })(BABYLON.PostProcessRenderPipeline);
  31883. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31884. })(BABYLON || (BABYLON = {}));
  31885. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31886. //
  31887. // This post-process allows the modification of rendered colors by using
  31888. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31889. //
  31890. // The object needs to be provided an url to a texture containing the color
  31891. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31892. // Use an image editing software to tweak the LUT to match your needs.
  31893. //
  31894. // For an example of a color LUT, see here:
  31895. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31896. // For explanations on color grading, see here:
  31897. // http://udn.epicgames.com/Three/ColorGrading.html
  31898. //
  31899. var __extends = this.__extends || function (d, b) {
  31900. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31901. function __() { this.constructor = d; }
  31902. __.prototype = b.prototype;
  31903. d.prototype = new __();
  31904. };
  31905. var BABYLON;
  31906. (function (BABYLON) {
  31907. var ColorCorrectionPostProcess = (function (_super) {
  31908. __extends(ColorCorrectionPostProcess, _super);
  31909. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31910. var _this = this;
  31911. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31912. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31913. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31914. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31915. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31916. this.onApply = function (effect) {
  31917. effect.setTexture("colorTable", _this._colorTableTexture);
  31918. };
  31919. }
  31920. return ColorCorrectionPostProcess;
  31921. })(BABYLON.PostProcess);
  31922. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31923. })(BABYLON || (BABYLON = {}));
  31924. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31925. var __extends = this.__extends || function (d, b) {
  31926. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31927. function __() { this.constructor = d; }
  31928. __.prototype = b.prototype;
  31929. d.prototype = new __();
  31930. };
  31931. var BABYLON;
  31932. (function (BABYLON) {
  31933. var StereogramFreeCamera = (function (_super) {
  31934. __extends(StereogramFreeCamera, _super);
  31935. function StereogramFreeCamera(name, position, eyeSpace, isVertical, scene) {
  31936. _super.call(this, name, position, scene);
  31937. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31938. }
  31939. return StereogramFreeCamera;
  31940. })(BABYLON.FreeCamera);
  31941. BABYLON.StereogramFreeCamera = StereogramFreeCamera;
  31942. var StereogramArcRotateCamera = (function (_super) {
  31943. __extends(StereogramArcRotateCamera, _super);
  31944. function StereogramArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  31945. _super.call(this, name, alpha, beta, radius, target, scene);
  31946. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31947. }
  31948. return StereogramArcRotateCamera;
  31949. })(BABYLON.ArcRotateCamera);
  31950. BABYLON.StereogramArcRotateCamera = StereogramArcRotateCamera;
  31951. var StereogramGamepadCamera = (function (_super) {
  31952. __extends(StereogramGamepadCamera, _super);
  31953. function StereogramGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  31954. _super.call(this, name, position, scene);
  31955. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31956. }
  31957. return StereogramGamepadCamera;
  31958. })(BABYLON.GamepadCamera);
  31959. BABYLON.StereogramGamepadCamera = StereogramGamepadCamera;
  31960. })(BABYLON || (BABYLON = {}));
  31961. //# sourceMappingURL=babylon.stereogramCamera.js.map
  31962. 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}"};
  31963. 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 e=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=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,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!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},e.prototype.collideForSubMesh=function(e,i,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(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,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(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE: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={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.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}},t.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()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=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=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function 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,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,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 n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return 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,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,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(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),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,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,n,r){var s,e,a,h=i.Normalize(o),u=(i.Normalize(n),i.Normalize(r)),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=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,i.y=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,i.z=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,i.w=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w,this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,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-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+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):r>h&&r>f?(o=2*Math.sqrt(1+r-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-r-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-r-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 n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],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+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*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-n*M+r*w)*R,t.m[5]=(i*z-n*I+r*d)*R,t.m[9]=-(i*M-o*I+r*D)*R,t.m[13]=(i*w-o*d+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*V)*R,t.m[7]=(i*L-n*E+r*Z)*R,t.m[11]=-(i*q-o*E+r*N)*R,t.m[15]=(i*V-o*Z+n*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,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),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),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 n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],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]=n*w+r*S+s*R+e*F,i[o+1]=n*I+r*v+s*_+e*P,i[o+2]=n*d+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+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 n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var l=SIMD.float32x4.load(n,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(n,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(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15]);\n\n},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=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,n,r,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]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=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,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var 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(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,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(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,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(n).multiply(r).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,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*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 n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[10]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=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,n=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=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 r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var 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)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.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?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),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.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,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]=r.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=r.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 n;if(void 0===o||null===o){var s;1!==i.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=w;var I=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,t.x,o.x,n.x),a(h/s,t.y,o.y,n.y),a(h/s,t.z,o.z,n.z)));return new i(e)},i.CreateCubicBezier=function(t,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,t.x,o.x,n.x,s.x),h(u/e,t.y,o.y,n.y,s.y),h(u/e,t.z,o.z,n.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,n,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,n,r,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new i(n);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=I;var d=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";